babylon.no-module.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /** @hidden */
  159. this._bonesComputationForcedToCPU = false;
  160. this._uniformBuffersNames = {};
  161. this._isReady = false;
  162. this._compilationError = "";
  163. this.name = baseName;
  164. if (attributesNamesOrOptions.attributes) {
  165. var options = attributesNamesOrOptions;
  166. this._engine = uniformsNamesOrEngine;
  167. this._attributesNames = options.attributes;
  168. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  169. this._samplers = options.samplers.slice();
  170. this.defines = options.defines;
  171. this.onError = options.onError;
  172. this.onCompiled = options.onCompiled;
  173. this._fallbacks = options.fallbacks;
  174. this._indexParameters = options.indexParameters;
  175. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  176. if (options.uniformBuffersNames) {
  177. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  178. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  179. }
  180. }
  181. }
  182. else {
  183. this._engine = engine;
  184. this.defines = defines;
  185. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  186. this._samplers = samplers ? samplers.slice() : [];
  187. this._attributesNames = attributesNamesOrOptions;
  188. this.onError = onError;
  189. this.onCompiled = onCompiled;
  190. this._indexParameters = indexParameters;
  191. this._fallbacks = fallbacks;
  192. }
  193. this.uniqueId = Effect._uniqueIdSeed++;
  194. var vertexSource;
  195. var fragmentSource;
  196. if (baseName.vertexElement) {
  197. vertexSource = document.getElementById(baseName.vertexElement);
  198. if (!vertexSource) {
  199. vertexSource = baseName.vertexElement;
  200. }
  201. }
  202. else {
  203. vertexSource = baseName.vertex || baseName;
  204. }
  205. if (baseName.fragmentElement) {
  206. fragmentSource = document.getElementById(baseName.fragmentElement);
  207. if (!fragmentSource) {
  208. fragmentSource = baseName.fragmentElement;
  209. }
  210. }
  211. else {
  212. fragmentSource = baseName.fragment || baseName;
  213. }
  214. this._loadVertexShader(vertexSource, function (vertexCode) {
  215. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  216. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  217. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  218. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  219. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  220. if (baseName) {
  221. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  222. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  223. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  224. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  225. }
  226. else {
  227. _this._vertexSourceCode = migratedVertexCode;
  228. _this._fragmentSourceCode = migratedFragmentCode;
  229. }
  230. _this._prepareEffect();
  231. });
  232. });
  233. });
  234. });
  235. });
  236. });
  237. }
  238. Object.defineProperty(Effect.prototype, "onBindObservable", {
  239. /**
  240. * Observable that will be called when effect is bound.
  241. */
  242. get: function () {
  243. if (!this._onBindObservable) {
  244. this._onBindObservable = new BABYLON.Observable();
  245. }
  246. return this._onBindObservable;
  247. },
  248. enumerable: true,
  249. configurable: true
  250. });
  251. Object.defineProperty(Effect.prototype, "key", {
  252. /**
  253. * Unique key for this effect
  254. */
  255. get: function () {
  256. return this._key;
  257. },
  258. enumerable: true,
  259. configurable: true
  260. });
  261. /**
  262. * If the effect has been compiled and prepared.
  263. * @returns if the effect is compiled and prepared.
  264. */
  265. Effect.prototype.isReady = function () {
  266. return this._isReady;
  267. };
  268. /**
  269. * The engine the effect was initialized with.
  270. * @returns the engine.
  271. */
  272. Effect.prototype.getEngine = function () {
  273. return this._engine;
  274. };
  275. /**
  276. * The compiled webGL program for the effect
  277. * @returns the webGL program.
  278. */
  279. Effect.prototype.getProgram = function () {
  280. return this._program;
  281. };
  282. /**
  283. * The set of names of attribute variables for the shader.
  284. * @returns An array of attribute names.
  285. */
  286. Effect.prototype.getAttributesNames = function () {
  287. return this._attributesNames;
  288. };
  289. /**
  290. * Returns the attribute at the given index.
  291. * @param index The index of the attribute.
  292. * @returns The location of the attribute.
  293. */
  294. Effect.prototype.getAttributeLocation = function (index) {
  295. return this._attributes[index];
  296. };
  297. /**
  298. * Returns the attribute based on the name of the variable.
  299. * @param name of the attribute to look up.
  300. * @returns the attribute location.
  301. */
  302. Effect.prototype.getAttributeLocationByName = function (name) {
  303. var index = this._attributesNames.indexOf(name);
  304. return this._attributes[index];
  305. };
  306. /**
  307. * The number of attributes.
  308. * @returns the numnber of attributes.
  309. */
  310. Effect.prototype.getAttributesCount = function () {
  311. return this._attributes.length;
  312. };
  313. /**
  314. * Gets the index of a uniform variable.
  315. * @param uniformName of the uniform to look up.
  316. * @returns the index.
  317. */
  318. Effect.prototype.getUniformIndex = function (uniformName) {
  319. return this._uniformsNames.indexOf(uniformName);
  320. };
  321. /**
  322. * Returns the attribute based on the name of the variable.
  323. * @param uniformName of the uniform to look up.
  324. * @returns the location of the uniform.
  325. */
  326. Effect.prototype.getUniform = function (uniformName) {
  327. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  328. };
  329. /**
  330. * Returns an array of sampler variable names
  331. * @returns The array of sampler variable neames.
  332. */
  333. Effect.prototype.getSamplers = function () {
  334. return this._samplers;
  335. };
  336. /**
  337. * The error from the last compilation.
  338. * @returns the error string.
  339. */
  340. Effect.prototype.getCompilationError = function () {
  341. return this._compilationError;
  342. };
  343. /**
  344. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  345. * @param func The callback to be used.
  346. */
  347. Effect.prototype.executeWhenCompiled = function (func) {
  348. if (this.isReady()) {
  349. func(this);
  350. return;
  351. }
  352. this.onCompileObservable.add(function (effect) {
  353. func(effect);
  354. });
  355. };
  356. /** @hidden */
  357. Effect.prototype._loadVertexShader = function (vertex, callback) {
  358. if (BABYLON.Tools.IsWindowObjectExist()) {
  359. // DOM element ?
  360. if (vertex instanceof HTMLElement) {
  361. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  362. callback(vertexCode);
  363. return;
  364. }
  365. }
  366. // Base64 encoded ?
  367. if (vertex.substr(0, 7) === "base64:") {
  368. var vertexBinary = window.atob(vertex.substr(7));
  369. callback(vertexBinary);
  370. return;
  371. }
  372. // Is in local store ?
  373. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  374. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  375. return;
  376. }
  377. var vertexShaderUrl;
  378. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  379. vertexShaderUrl = vertex;
  380. }
  381. else {
  382. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  383. }
  384. // Vertex shader
  385. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  386. };
  387. /** @hidden */
  388. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  389. if (BABYLON.Tools.IsWindowObjectExist()) {
  390. // DOM element ?
  391. if (fragment instanceof HTMLElement) {
  392. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  393. callback(fragmentCode);
  394. return;
  395. }
  396. }
  397. // Base64 encoded ?
  398. if (fragment.substr(0, 7) === "base64:") {
  399. var fragmentBinary = window.atob(fragment.substr(7));
  400. callback(fragmentBinary);
  401. return;
  402. }
  403. // Is in local store ?
  404. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  405. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  406. return;
  407. }
  408. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  409. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  410. return;
  411. }
  412. var fragmentShaderUrl;
  413. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  414. fragmentShaderUrl = fragment;
  415. }
  416. else {
  417. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  418. }
  419. // Fragment shader
  420. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  421. };
  422. /** @hidden */
  423. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  424. // Rebuild shaders source code
  425. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  426. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  427. vertexCode = prefix + vertexCode;
  428. fragmentCode = prefix + fragmentCode;
  429. // Number lines of shaders source code
  430. var i = 2;
  431. var regex = /\n/gm;
  432. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  433. i = 2;
  434. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  435. // Dump shaders name and formatted source code
  436. if (this.name.vertexElement) {
  437. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  438. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  439. }
  440. else if (this.name.vertex) {
  441. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  442. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  443. }
  444. else {
  445. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  446. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  447. }
  448. };
  449. ;
  450. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  451. var preparedSourceCode = this._processPrecision(sourceCode);
  452. if (this._engine.webGLVersion == 1) {
  453. callback(preparedSourceCode);
  454. return;
  455. }
  456. // Already converted
  457. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  458. callback(preparedSourceCode.replace("#version 300 es", ""));
  459. return;
  460. }
  461. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  462. // Remove extensions
  463. // #extension GL_OES_standard_derivatives : enable
  464. // #extension GL_EXT_shader_texture_lod : enable
  465. // #extension GL_EXT_frag_depth : enable
  466. // #extension GL_EXT_draw_buffers : require
  467. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  468. var result = preparedSourceCode.replace(regex, "");
  469. // Migrate to GLSL v300
  470. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  471. result = result.replace(/attribute[ \t]/g, "in ");
  472. result = result.replace(/[ \t]attribute/g, " in");
  473. if (isFragment) {
  474. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  475. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  476. result = result.replace(/texture2D\s*\(/g, "texture(");
  477. result = result.replace(/textureCube\s*\(/g, "texture(");
  478. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  479. result = result.replace(/gl_FragColor/g, "glFragColor");
  480. result = result.replace(/gl_FragData/g, "glFragData");
  481. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  482. }
  483. callback(result);
  484. };
  485. Effect.prototype._processIncludes = function (sourceCode, callback) {
  486. var _this = this;
  487. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  488. var match = regex.exec(sourceCode);
  489. var returnValue = new String(sourceCode);
  490. while (match != null) {
  491. var includeFile = match[1];
  492. // Uniform declaration
  493. if (includeFile.indexOf("__decl__") !== -1) {
  494. includeFile = includeFile.replace(/__decl__/, "");
  495. if (this._engine.supportsUniformBuffers) {
  496. includeFile = includeFile.replace(/Vertex/, "Ubo");
  497. includeFile = includeFile.replace(/Fragment/, "Ubo");
  498. }
  499. includeFile = includeFile + "Declaration";
  500. }
  501. if (Effect.IncludesShadersStore[includeFile]) {
  502. // Substitution
  503. var includeContent = Effect.IncludesShadersStore[includeFile];
  504. if (match[2]) {
  505. var splits = match[3].split(",");
  506. for (var index = 0; index < splits.length; index += 2) {
  507. var source = new RegExp(splits[index], "g");
  508. var dest = splits[index + 1];
  509. includeContent = includeContent.replace(source, dest);
  510. }
  511. }
  512. if (match[4]) {
  513. var indexString = match[5];
  514. if (indexString.indexOf("..") !== -1) {
  515. var indexSplits = indexString.split("..");
  516. var minIndex = parseInt(indexSplits[0]);
  517. var maxIndex = parseInt(indexSplits[1]);
  518. var sourceIncludeContent = includeContent.slice(0);
  519. includeContent = "";
  520. if (isNaN(maxIndex)) {
  521. maxIndex = this._indexParameters[indexSplits[1]];
  522. }
  523. for (var i = minIndex; i < maxIndex; i++) {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  531. }
  532. }
  533. else {
  534. if (!this._engine.supportsUniformBuffers) {
  535. // Ubo replacement
  536. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  537. return p1 + "{X}";
  538. });
  539. }
  540. includeContent = includeContent.replace(/\{X\}/g, indexString);
  541. }
  542. }
  543. // Replace
  544. returnValue = returnValue.replace(match[0], includeContent);
  545. }
  546. else {
  547. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  548. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  549. Effect.IncludesShadersStore[includeFile] = fileContent;
  550. _this._processIncludes(returnValue, callback);
  551. });
  552. return;
  553. }
  554. match = regex.exec(sourceCode);
  555. }
  556. callback(returnValue);
  557. };
  558. Effect.prototype._processPrecision = function (source) {
  559. if (source.indexOf("precision highp float") === -1) {
  560. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  561. source = "precision mediump float;\n" + source;
  562. }
  563. else {
  564. source = "precision highp float;\n" + source;
  565. }
  566. }
  567. else {
  568. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  569. source = source.replace("precision highp float", "precision mediump float");
  570. }
  571. }
  572. return source;
  573. };
  574. /**
  575. * Recompiles the webGL program
  576. * @param vertexSourceCode The source code for the vertex shader.
  577. * @param fragmentSourceCode The source code for the fragment shader.
  578. * @param onCompiled Callback called when completed.
  579. * @param onError Callback called on error.
  580. * @hidden
  581. */
  582. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  583. var _this = this;
  584. this._isReady = false;
  585. this._vertexSourceCodeOverride = vertexSourceCode;
  586. this._fragmentSourceCodeOverride = fragmentSourceCode;
  587. this.onError = function (effect, error) {
  588. if (onError) {
  589. onError(error);
  590. }
  591. };
  592. this.onCompiled = function () {
  593. var scenes = _this.getEngine().scenes;
  594. for (var i = 0; i < scenes.length; i++) {
  595. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  596. }
  597. if (onCompiled) {
  598. onCompiled(_this._program);
  599. }
  600. };
  601. this._fallbacks = null;
  602. this._prepareEffect();
  603. };
  604. /**
  605. * Gets the uniform locations of the the specified variable names
  606. * @param names THe names of the variables to lookup.
  607. * @returns Array of locations in the same order as variable names.
  608. */
  609. Effect.prototype.getSpecificUniformLocations = function (names) {
  610. var engine = this._engine;
  611. return engine.getUniforms(this._program, names);
  612. };
  613. /**
  614. * Prepares the effect
  615. * @hidden
  616. */
  617. Effect.prototype._prepareEffect = function () {
  618. var attributesNames = this._attributesNames;
  619. var defines = this.defines;
  620. var fallbacks = this._fallbacks;
  621. this._valueCache = {};
  622. var previousProgram = this._program;
  623. try {
  624. var engine = this._engine;
  625. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  626. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  627. }
  628. else {
  629. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  630. }
  631. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  632. if (engine.supportsUniformBuffers) {
  633. for (var name in this._uniformBuffersNames) {
  634. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  635. }
  636. }
  637. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  638. this._attributes = engine.getAttributes(this._program, attributesNames);
  639. var index;
  640. for (index = 0; index < this._samplers.length; index++) {
  641. var sampler = this.getUniform(this._samplers[index]);
  642. if (sampler == null) {
  643. this._samplers.splice(index, 1);
  644. index--;
  645. }
  646. }
  647. engine.bindSamplers(this);
  648. this._compilationError = "";
  649. this._isReady = true;
  650. if (this.onCompiled) {
  651. this.onCompiled(this);
  652. }
  653. this.onCompileObservable.notifyObservers(this);
  654. this.onCompileObservable.clear();
  655. // Unbind mesh reference in fallbacks
  656. if (this._fallbacks) {
  657. this._fallbacks.unBindMesh();
  658. }
  659. if (previousProgram) {
  660. this.getEngine()._deleteProgram(previousProgram);
  661. }
  662. }
  663. catch (e) {
  664. this._compilationError = e.message;
  665. // Let's go through fallbacks then
  666. BABYLON.Tools.Error("Unable to compile effect:");
  667. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  668. return " " + uniform;
  669. }));
  670. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  671. return " " + attribute;
  672. }));
  673. BABYLON.Tools.Error("Error: " + this._compilationError);
  674. if (previousProgram) {
  675. this._program = previousProgram;
  676. this._isReady = true;
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. }
  682. if (fallbacks && fallbacks.isMoreFallbacks) {
  683. BABYLON.Tools.Error("Trying next fallback.");
  684. this.defines = fallbacks.reduce(this.defines, this);
  685. this._prepareEffect();
  686. }
  687. else { // Sorry we did everything we can
  688. if (this.onError) {
  689. this.onError(this, this._compilationError);
  690. }
  691. this.onErrorObservable.notifyObservers(this);
  692. this.onErrorObservable.clear();
  693. // Unbind mesh reference in fallbacks
  694. if (this._fallbacks) {
  695. this._fallbacks.unBindMesh();
  696. }
  697. }
  698. }
  699. };
  700. Object.defineProperty(Effect.prototype, "isSupported", {
  701. /**
  702. * Checks if the effect is supported. (Must be called after compilation)
  703. */
  704. get: function () {
  705. return this._compilationError === "";
  706. },
  707. enumerable: true,
  708. configurable: true
  709. });
  710. /**
  711. * Binds a texture to the engine to be used as output of the shader.
  712. * @param channel Name of the output variable.
  713. * @param texture Texture to bind.
  714. * @hidden
  715. */
  716. Effect.prototype._bindTexture = function (channel, texture) {
  717. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  718. };
  719. /**
  720. * Sets a texture on the engine to be used in the shader.
  721. * @param channel Name of the sampler variable.
  722. * @param texture Texture to set.
  723. */
  724. Effect.prototype.setTexture = function (channel, texture) {
  725. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  726. };
  727. /**
  728. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  729. * @param channel Name of the sampler variable.
  730. * @param texture Texture to set.
  731. */
  732. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  733. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  734. };
  735. /**
  736. * Sets an array of textures on the engine to be used in the shader.
  737. * @param channel Name of the variable.
  738. * @param textures Textures to set.
  739. */
  740. Effect.prototype.setTextureArray = function (channel, textures) {
  741. if (this._samplers.indexOf(channel + "Ex") === -1) {
  742. var initialPos = this._samplers.indexOf(channel);
  743. for (var index = 1; index < textures.length; index++) {
  744. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  745. }
  746. }
  747. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  748. };
  749. /**
  750. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  751. * @param channel Name of the sampler variable.
  752. * @param postProcess Post process to get the input texture from.
  753. */
  754. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  755. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  756. };
  757. /**
  758. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  759. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  760. * @param channel Name of the sampler variable.
  761. * @param postProcess Post process to get the output texture from.
  762. */
  763. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  764. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  765. };
  766. /** @hidden */
  767. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  768. var cache = this._valueCache[uniformName];
  769. var flag = matrix.updateFlag;
  770. if (cache !== undefined && cache === flag) {
  771. return false;
  772. }
  773. this._valueCache[uniformName] = flag;
  774. return true;
  775. };
  776. /** @hidden */
  777. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  778. var cache = this._valueCache[uniformName];
  779. if (!cache) {
  780. cache = [x, y];
  781. this._valueCache[uniformName] = cache;
  782. return true;
  783. }
  784. var changed = false;
  785. if (cache[0] !== x) {
  786. cache[0] = x;
  787. changed = true;
  788. }
  789. if (cache[1] !== y) {
  790. cache[1] = y;
  791. changed = true;
  792. }
  793. return changed;
  794. };
  795. /** @hidden */
  796. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  797. var cache = this._valueCache[uniformName];
  798. if (!cache) {
  799. cache = [x, y, z];
  800. this._valueCache[uniformName] = cache;
  801. return true;
  802. }
  803. var changed = false;
  804. if (cache[0] !== x) {
  805. cache[0] = x;
  806. changed = true;
  807. }
  808. if (cache[1] !== y) {
  809. cache[1] = y;
  810. changed = true;
  811. }
  812. if (cache[2] !== z) {
  813. cache[2] = z;
  814. changed = true;
  815. }
  816. return changed;
  817. };
  818. /** @hidden */
  819. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  820. var cache = this._valueCache[uniformName];
  821. if (!cache) {
  822. cache = [x, y, z, w];
  823. this._valueCache[uniformName] = cache;
  824. return true;
  825. }
  826. var changed = false;
  827. if (cache[0] !== x) {
  828. cache[0] = x;
  829. changed = true;
  830. }
  831. if (cache[1] !== y) {
  832. cache[1] = y;
  833. changed = true;
  834. }
  835. if (cache[2] !== z) {
  836. cache[2] = z;
  837. changed = true;
  838. }
  839. if (cache[3] !== w) {
  840. cache[3] = w;
  841. changed = true;
  842. }
  843. return changed;
  844. };
  845. /**
  846. * Binds a buffer to a uniform.
  847. * @param buffer Buffer to bind.
  848. * @param name Name of the uniform variable to bind to.
  849. */
  850. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  851. var bufferName = this._uniformBuffersNames[name];
  852. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  853. return;
  854. }
  855. Effect._baseCache[bufferName] = buffer;
  856. this._engine.bindUniformBufferBase(buffer, bufferName);
  857. };
  858. /**
  859. * Binds block to a uniform.
  860. * @param blockName Name of the block to bind.
  861. * @param index Index to bind.
  862. */
  863. Effect.prototype.bindUniformBlock = function (blockName, index) {
  864. this._engine.bindUniformBlock(this._program, blockName, index);
  865. };
  866. /**
  867. * Sets an interger value on a uniform variable.
  868. * @param uniformName Name of the variable.
  869. * @param value Value to be set.
  870. * @returns this effect.
  871. */
  872. Effect.prototype.setInt = function (uniformName, value) {
  873. var cache = this._valueCache[uniformName];
  874. if (cache !== undefined && cache === value)
  875. return this;
  876. this._valueCache[uniformName] = value;
  877. this._engine.setInt(this.getUniform(uniformName), value);
  878. return this;
  879. };
  880. /**
  881. * Sets an int array on a uniform variable.
  882. * @param uniformName Name of the variable.
  883. * @param array array to be set.
  884. * @returns this effect.
  885. */
  886. Effect.prototype.setIntArray = function (uniformName, array) {
  887. this._valueCache[uniformName] = null;
  888. this._engine.setIntArray(this.getUniform(uniformName), array);
  889. return this;
  890. };
  891. /**
  892. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  893. * @param uniformName Name of the variable.
  894. * @param array array to be set.
  895. * @returns this effect.
  896. */
  897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  898. this._valueCache[uniformName] = null;
  899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  900. return this;
  901. };
  902. /**
  903. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  904. * @param uniformName Name of the variable.
  905. * @param array array to be set.
  906. * @returns this effect.
  907. */
  908. Effect.prototype.setIntArray3 = function (uniformName, array) {
  909. this._valueCache[uniformName] = null;
  910. this._engine.setIntArray3(this.getUniform(uniformName), array);
  911. return this;
  912. };
  913. /**
  914. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  915. * @param uniformName Name of the variable.
  916. * @param array array to be set.
  917. * @returns this effect.
  918. */
  919. Effect.prototype.setIntArray4 = function (uniformName, array) {
  920. this._valueCache[uniformName] = null;
  921. this._engine.setIntArray4(this.getUniform(uniformName), array);
  922. return this;
  923. };
  924. /**
  925. * Sets an float array on a uniform variable.
  926. * @param uniformName Name of the variable.
  927. * @param array array to be set.
  928. * @returns this effect.
  929. */
  930. Effect.prototype.setFloatArray = function (uniformName, array) {
  931. this._valueCache[uniformName] = null;
  932. this._engine.setFloatArray(this.getUniform(uniformName), array);
  933. return this;
  934. };
  935. /**
  936. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  937. * @param uniformName Name of the variable.
  938. * @param array array to be set.
  939. * @returns this effect.
  940. */
  941. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  942. this._valueCache[uniformName] = null;
  943. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  944. return this;
  945. };
  946. /**
  947. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  948. * @param uniformName Name of the variable.
  949. * @param array array to be set.
  950. * @returns this effect.
  951. */
  952. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  953. this._valueCache[uniformName] = null;
  954. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  955. return this;
  956. };
  957. /**
  958. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  959. * @param uniformName Name of the variable.
  960. * @param array array to be set.
  961. * @returns this effect.
  962. */
  963. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  964. this._valueCache[uniformName] = null;
  965. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  966. return this;
  967. };
  968. /**
  969. * Sets an array on a uniform variable.
  970. * @param uniformName Name of the variable.
  971. * @param array array to be set.
  972. * @returns this effect.
  973. */
  974. Effect.prototype.setArray = function (uniformName, array) {
  975. this._valueCache[uniformName] = null;
  976. this._engine.setArray(this.getUniform(uniformName), array);
  977. return this;
  978. };
  979. /**
  980. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  981. * @param uniformName Name of the variable.
  982. * @param array array to be set.
  983. * @returns this effect.
  984. */
  985. Effect.prototype.setArray2 = function (uniformName, array) {
  986. this._valueCache[uniformName] = null;
  987. this._engine.setArray2(this.getUniform(uniformName), array);
  988. return this;
  989. };
  990. /**
  991. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  992. * @param uniformName Name of the variable.
  993. * @param array array to be set.
  994. * @returns this effect.
  995. */
  996. Effect.prototype.setArray3 = function (uniformName, array) {
  997. this._valueCache[uniformName] = null;
  998. this._engine.setArray3(this.getUniform(uniformName), array);
  999. return this;
  1000. };
  1001. /**
  1002. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1003. * @param uniformName Name of the variable.
  1004. * @param array array to be set.
  1005. * @returns this effect.
  1006. */
  1007. Effect.prototype.setArray4 = function (uniformName, array) {
  1008. this._valueCache[uniformName] = null;
  1009. this._engine.setArray4(this.getUniform(uniformName), array);
  1010. return this;
  1011. };
  1012. /**
  1013. * Sets matrices on a uniform variable.
  1014. * @param uniformName Name of the variable.
  1015. * @param matrices matrices to be set.
  1016. * @returns this effect.
  1017. */
  1018. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1019. if (!matrices) {
  1020. return this;
  1021. }
  1022. this._valueCache[uniformName] = null;
  1023. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1024. return this;
  1025. };
  1026. /**
  1027. * Sets matrix on a uniform variable.
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1033. if (this._cacheMatrix(uniformName, matrix)) {
  1034. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1040. * @param uniformName Name of the variable.
  1041. * @param matrix matrix to be set.
  1042. * @returns this effect.
  1043. */
  1044. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1045. this._valueCache[uniformName] = null;
  1046. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1047. return this;
  1048. };
  1049. /**
  1050. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1051. * @param uniformName Name of the variable.
  1052. * @param matrix matrix to be set.
  1053. * @returns this effect.
  1054. */
  1055. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1056. this._valueCache[uniformName] = null;
  1057. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1058. return this;
  1059. };
  1060. /**
  1061. * Sets a float on a uniform variable.
  1062. * @param uniformName Name of the variable.
  1063. * @param value value to be set.
  1064. * @returns this effect.
  1065. */
  1066. Effect.prototype.setFloat = function (uniformName, value) {
  1067. var cache = this._valueCache[uniformName];
  1068. if (cache !== undefined && cache === value)
  1069. return this;
  1070. this._valueCache[uniformName] = value;
  1071. this._engine.setFloat(this.getUniform(uniformName), value);
  1072. return this;
  1073. };
  1074. /**
  1075. * Sets a boolean on a uniform variable.
  1076. * @param uniformName Name of the variable.
  1077. * @param bool value to be set.
  1078. * @returns this effect.
  1079. */
  1080. Effect.prototype.setBool = function (uniformName, bool) {
  1081. var cache = this._valueCache[uniformName];
  1082. if (cache !== undefined && cache === bool)
  1083. return this;
  1084. this._valueCache[uniformName] = bool;
  1085. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a Vector2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param vector2 vector2 to be set.
  1092. * @returns this effect.
  1093. */
  1094. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1095. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1096. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1097. }
  1098. return this;
  1099. };
  1100. /**
  1101. * Sets a float2 on a uniform variable.
  1102. * @param uniformName Name of the variable.
  1103. * @param x First float in float2.
  1104. * @param y Second float in float2.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1108. if (this._cacheFloat2(uniformName, x, y)) {
  1109. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a Vector3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param vector3 Value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1120. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1121. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1122. }
  1123. return this;
  1124. };
  1125. /**
  1126. * Sets a float3 on a uniform variable.
  1127. * @param uniformName Name of the variable.
  1128. * @param x First float in float3.
  1129. * @param y Second float in float3.
  1130. * @param z Third float in float3.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1134. if (this._cacheFloat3(uniformName, x, y, z)) {
  1135. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a Vector4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param vector4 Value to be set.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1146. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a float4 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param x First float in float4.
  1155. * @param y Second float in float4.
  1156. * @param z Third float in float4.
  1157. * @param w Fourth float in float4.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1161. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1162. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setColor3 = function (uniformName, color3) {
  1173. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1174. this._engine.setColor3(this.getUniform(uniformName), color3);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a Color4 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param color3 Value to be set.
  1182. * @param alpha Alpha value to be set.
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1186. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1187. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Sets a Color4 on a uniform variable
  1193. * @param uniformName defines the name of the variable
  1194. * @param color4 defines the value to be set
  1195. * @returns this effect.
  1196. */
  1197. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1198. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1199. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1200. }
  1201. return this;
  1202. };
  1203. /**
  1204. * This function will add a new shader to the shader store
  1205. * @param name the name of the shader
  1206. * @param pixelShader optional pixel shader content
  1207. * @param vertexShader optional vertex shader content
  1208. */
  1209. Effect.RegisterShader = function (name, pixelShader, vertexShader) {
  1210. if (pixelShader) {
  1211. Effect.ShadersStore[name + "PixelShader"] = pixelShader;
  1212. }
  1213. if (vertexShader) {
  1214. Effect.ShadersStore[name + "VertexShader"] = vertexShader;
  1215. }
  1216. };
  1217. /**
  1218. * Resets the cache of effects.
  1219. */
  1220. Effect.ResetCache = function () {
  1221. Effect._baseCache = {};
  1222. };
  1223. Effect._uniqueIdSeed = 0;
  1224. Effect._baseCache = {};
  1225. /**
  1226. * Store of each shader (The can be looked up using effect.key)
  1227. */
  1228. Effect.ShadersStore = {};
  1229. /**
  1230. * Store of each included file for a shader (The can be looked up using effect.key)
  1231. */
  1232. Effect.IncludesShadersStore = {};
  1233. return Effect;
  1234. }());
  1235. BABYLON.Effect = Effect;
  1236. })(BABYLON || (BABYLON = {}));
  1237. //# sourceMappingURL=babylon.effect.js.map
  1238. //# sourceMappingURL=babylon.types.js.map
  1239. var BABYLON;
  1240. (function (BABYLON) {
  1241. /**
  1242. * Gather the list of keyboard event types as constants.
  1243. */
  1244. var KeyboardEventTypes = /** @class */ (function () {
  1245. function KeyboardEventTypes() {
  1246. }
  1247. /**
  1248. * The keydown event is fired when a key becomes active (pressed).
  1249. */
  1250. KeyboardEventTypes.KEYDOWN = 0x01;
  1251. /**
  1252. * The keyup event is fired when a key has been released.
  1253. */
  1254. KeyboardEventTypes.KEYUP = 0x02;
  1255. return KeyboardEventTypes;
  1256. }());
  1257. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1258. /**
  1259. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1260. */
  1261. var KeyboardInfo = /** @class */ (function () {
  1262. /**
  1263. * Instantiates a new keyboard info.
  1264. * This class is used to store keyboard related info for the onKeyboardObservable event.
  1265. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1266. * @param event Defines the related dom event
  1267. */
  1268. function KeyboardInfo(
  1269. /**
  1270. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1271. */
  1272. type,
  1273. /**
  1274. * Defines the related dom event
  1275. */
  1276. event) {
  1277. this.type = type;
  1278. this.event = event;
  1279. }
  1280. return KeyboardInfo;
  1281. }());
  1282. BABYLON.KeyboardInfo = KeyboardInfo;
  1283. /**
  1284. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1285. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1286. */
  1287. var KeyboardInfoPre = /** @class */ (function (_super) {
  1288. __extends(KeyboardInfoPre, _super);
  1289. /**
  1290. * Instantiates a new keyboard pre info.
  1291. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1292. * @param type Defines the type of event (BABYLON.KeyboardEventTypes)
  1293. * @param event Defines the related dom event
  1294. */
  1295. function KeyboardInfoPre(
  1296. /**
  1297. * Defines the type of event (BABYLON.KeyboardEventTypes)
  1298. */
  1299. type,
  1300. /**
  1301. * Defines the related dom event
  1302. */
  1303. event) {
  1304. var _this = _super.call(this, type, event) || this;
  1305. _this.type = type;
  1306. _this.event = event;
  1307. _this.skipOnPointerObservable = false;
  1308. return _this;
  1309. }
  1310. return KeyboardInfoPre;
  1311. }(KeyboardInfo));
  1312. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1313. })(BABYLON || (BABYLON = {}));
  1314. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1315. var BABYLON;
  1316. (function (BABYLON) {
  1317. /**
  1318. * Gather the list of pointer event types as constants.
  1319. */
  1320. var PointerEventTypes = /** @class */ (function () {
  1321. function PointerEventTypes() {
  1322. }
  1323. /**
  1324. * The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
  1325. */
  1326. PointerEventTypes.POINTERDOWN = 0x01;
  1327. /**
  1328. * The pointerup event is fired when a pointer is no longer active.
  1329. */
  1330. PointerEventTypes.POINTERUP = 0x02;
  1331. /**
  1332. * The pointermove event is fired when a pointer changes coordinates.
  1333. */
  1334. PointerEventTypes.POINTERMOVE = 0x04;
  1335. /**
  1336. * The pointerwheel event is fired when a mouse wheel has been rotated.
  1337. */
  1338. PointerEventTypes.POINTERWHEEL = 0x08;
  1339. /**
  1340. * The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
  1341. */
  1342. PointerEventTypes.POINTERPICK = 0x10;
  1343. /**
  1344. * The pointertap event is fired when a the object has been touched and released without drag.
  1345. */
  1346. PointerEventTypes.POINTERTAP = 0x20;
  1347. /**
  1348. * The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
  1349. */
  1350. PointerEventTypes.POINTERDOUBLETAP = 0x40;
  1351. return PointerEventTypes;
  1352. }());
  1353. BABYLON.PointerEventTypes = PointerEventTypes;
  1354. /**
  1355. * Base class of pointer info types.
  1356. */
  1357. var PointerInfoBase = /** @class */ (function () {
  1358. /**
  1359. * Instantiates the base class of pointers info.
  1360. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1361. * @param event Defines the related dom event
  1362. */
  1363. function PointerInfoBase(
  1364. /**
  1365. * Defines the type of event (BABYLON.PointerEventTypes)
  1366. */
  1367. type,
  1368. /**
  1369. * Defines the related dom event
  1370. */
  1371. event) {
  1372. this.type = type;
  1373. this.event = event;
  1374. }
  1375. return PointerInfoBase;
  1376. }());
  1377. BABYLON.PointerInfoBase = PointerInfoBase;
  1378. /**
  1379. * This class is used to store pointer related info for the onPrePointerObservable event.
  1380. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1381. */
  1382. var PointerInfoPre = /** @class */ (function (_super) {
  1383. __extends(PointerInfoPre, _super);
  1384. /**
  1385. * Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
  1386. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1387. * @param event Defines the related dom event
  1388. * @param localX Defines the local x coordinates of the pointer when the event occured
  1389. * @param localY Defines the local y coordinates of the pointer when the event occured
  1390. */
  1391. function PointerInfoPre(type, event, localX, localY) {
  1392. var _this = _super.call(this, type, event) || this;
  1393. /**
  1394. * Ray from a pointer if availible (eg. 6dof controller)
  1395. */
  1396. _this.ray = null;
  1397. _this.skipOnPointerObservable = false;
  1398. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1399. return _this;
  1400. }
  1401. return PointerInfoPre;
  1402. }(PointerInfoBase));
  1403. BABYLON.PointerInfoPre = PointerInfoPre;
  1404. /**
  1405. * This type contains all the data related to a pointer event in Babylon.js.
  1406. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1407. */
  1408. var PointerInfo = /** @class */ (function (_super) {
  1409. __extends(PointerInfo, _super);
  1410. /**
  1411. * Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
  1412. * @param type Defines the type of event (BABYLON.PointerEventTypes)
  1413. * @param event Defines the related dom event
  1414. * @param pickInfo Defines the picking info associated to the info (if any)\
  1415. */
  1416. function PointerInfo(type, event,
  1417. /**
  1418. * Defines the picking info associated to the info (if any)\
  1419. */
  1420. pickInfo) {
  1421. var _this = _super.call(this, type, event) || this;
  1422. _this.pickInfo = pickInfo;
  1423. return _this;
  1424. }
  1425. return PointerInfo;
  1426. }(PointerInfoBase));
  1427. BABYLON.PointerInfo = PointerInfo;
  1428. })(BABYLON || (BABYLON = {}));
  1429. //# sourceMappingURL=babylon.pointerEvents.js.map
  1430. var BABYLON;
  1431. (function (BABYLON) {
  1432. /**
  1433. * Constant used to convert a value to gamma space
  1434. * @ignorenaming
  1435. */
  1436. BABYLON.ToGammaSpace = 1 / 2.2;
  1437. /**
  1438. * Constant used to convert a value to linear space
  1439. * @ignorenaming
  1440. */
  1441. BABYLON.ToLinearSpace = 2.2;
  1442. /**
  1443. * Constant used to define the minimal number value in Babylon.js
  1444. * @ignorenaming
  1445. */
  1446. BABYLON.Epsilon = 0.001;
  1447. /**
  1448. * Class used to hold a RBG color
  1449. */
  1450. var Color3 = /** @class */ (function () {
  1451. /**
  1452. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1453. * @param r defines the red component (between 0 and 1, default is 0)
  1454. * @param g defines the green component (between 0 and 1, default is 0)
  1455. * @param b defines the blue component (between 0 and 1, default is 0)
  1456. */
  1457. function Color3(
  1458. /**
  1459. * Defines the red component (between 0 and 1, default is 0)
  1460. */
  1461. r,
  1462. /**
  1463. * Defines the green component (between 0 and 1, default is 0)
  1464. */
  1465. g,
  1466. /**
  1467. * Defines the blue component (between 0 and 1, default is 0)
  1468. */
  1469. b) {
  1470. if (r === void 0) { r = 0; }
  1471. if (g === void 0) { g = 0; }
  1472. if (b === void 0) { b = 0; }
  1473. this.r = r;
  1474. this.g = g;
  1475. this.b = b;
  1476. }
  1477. /**
  1478. * Creates a string with the Color3 current values
  1479. * @returns the string representation of the Color3 object
  1480. */
  1481. Color3.prototype.toString = function () {
  1482. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1483. };
  1484. /**
  1485. * Returns the string "Color3"
  1486. * @returns "Color3"
  1487. */
  1488. Color3.prototype.getClassName = function () {
  1489. return "Color3";
  1490. };
  1491. /**
  1492. * Compute the Color3 hash code
  1493. * @returns an unique number that can be used to hash Color3 objects
  1494. */
  1495. Color3.prototype.getHashCode = function () {
  1496. var hash = this.r || 0;
  1497. hash = (hash * 397) ^ (this.g || 0);
  1498. hash = (hash * 397) ^ (this.b || 0);
  1499. return hash;
  1500. };
  1501. // Operators
  1502. /**
  1503. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1504. * @param array defines the array where to store the r,g,b components
  1505. * @param index defines an optional index in the target array to define where to start storing values
  1506. * @returns the current Color3 object
  1507. */
  1508. Color3.prototype.toArray = function (array, index) {
  1509. if (index === undefined) {
  1510. index = 0;
  1511. }
  1512. array[index] = this.r;
  1513. array[index + 1] = this.g;
  1514. array[index + 2] = this.b;
  1515. return this;
  1516. };
  1517. /**
  1518. * Returns a new Color4 object from the current Color3 and the given alpha
  1519. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  1520. * @returns a new Color4 object
  1521. */
  1522. Color3.prototype.toColor4 = function (alpha) {
  1523. if (alpha === void 0) { alpha = 1; }
  1524. return new Color4(this.r, this.g, this.b, alpha);
  1525. };
  1526. /**
  1527. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1528. * @returns the new array
  1529. */
  1530. Color3.prototype.asArray = function () {
  1531. var result = new Array();
  1532. this.toArray(result, 0);
  1533. return result;
  1534. };
  1535. /**
  1536. * Returns the luminance value
  1537. * @returns a float value
  1538. */
  1539. Color3.prototype.toLuminance = function () {
  1540. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1541. };
  1542. /**
  1543. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1544. * @param otherColor defines the second operand
  1545. * @returns the new Color3 object
  1546. */
  1547. Color3.prototype.multiply = function (otherColor) {
  1548. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1549. };
  1550. /**
  1551. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1552. * @param otherColor defines the second operand
  1553. * @param result defines the Color3 object where to store the result
  1554. * @returns the current Color3
  1555. */
  1556. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1557. result.r = this.r * otherColor.r;
  1558. result.g = this.g * otherColor.g;
  1559. result.b = this.b * otherColor.b;
  1560. return this;
  1561. };
  1562. /**
  1563. * Determines equality between Color3 objects
  1564. * @param otherColor defines the second operand
  1565. * @returns true if the rgb values are equal to the given ones
  1566. */
  1567. Color3.prototype.equals = function (otherColor) {
  1568. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1569. };
  1570. /**
  1571. * Determines equality between the current Color3 object and a set of r,b,g values
  1572. * @param r defines the red component to check
  1573. * @param g defines the green component to check
  1574. * @param b defines the blue component to check
  1575. * @returns true if the rgb values are equal to the given ones
  1576. */
  1577. Color3.prototype.equalsFloats = function (r, g, b) {
  1578. return this.r === r && this.g === g && this.b === b;
  1579. };
  1580. /**
  1581. * Multiplies in place each rgb value by scale
  1582. * @param scale defines the scaling factor
  1583. * @returns the updated Color3
  1584. */
  1585. Color3.prototype.scale = function (scale) {
  1586. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1587. };
  1588. /**
  1589. * Multiplies the rgb values by scale and stores the result into "result"
  1590. * @param scale defines the scaling factor
  1591. * @param result defines the Color3 object where to store the result
  1592. * @returns the unmodified current Color3
  1593. */
  1594. Color3.prototype.scaleToRef = function (scale, result) {
  1595. result.r = this.r * scale;
  1596. result.g = this.g * scale;
  1597. result.b = this.b * scale;
  1598. return this;
  1599. };
  1600. /**
  1601. * Scale the current Color3 values by a factor and add the result to a given Color3
  1602. * @param scale defines the scale factor
  1603. * @param result defines color to store the result into
  1604. * @returns the unmodified current Color3
  1605. */
  1606. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1607. result.r += this.r * scale;
  1608. result.g += this.g * scale;
  1609. result.b += this.b * scale;
  1610. return this;
  1611. };
  1612. /**
  1613. * Clamps the rgb values by the min and max values and stores the result into "result"
  1614. * @param min defines minimum clamping value (default is 0)
  1615. * @param max defines maximum clamping value (default is 1)
  1616. * @param result defines color to store the result into
  1617. * @returns the original Color3
  1618. */
  1619. Color3.prototype.clampToRef = function (min, max, result) {
  1620. if (min === void 0) { min = 0; }
  1621. if (max === void 0) { max = 1; }
  1622. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1623. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1624. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1625. return this;
  1626. };
  1627. /**
  1628. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1629. * @param otherColor defines the second operand
  1630. * @returns the new Color3
  1631. */
  1632. Color3.prototype.add = function (otherColor) {
  1633. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1634. };
  1635. /**
  1636. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1637. * @param otherColor defines the second operand
  1638. * @param result defines Color3 object to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.addToRef = function (otherColor, result) {
  1642. result.r = this.r + otherColor.r;
  1643. result.g = this.g + otherColor.g;
  1644. result.b = this.b + otherColor.b;
  1645. return this;
  1646. };
  1647. /**
  1648. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1649. * @param otherColor defines the second operand
  1650. * @returns the new Color3
  1651. */
  1652. Color3.prototype.subtract = function (otherColor) {
  1653. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1654. };
  1655. /**
  1656. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1657. * @param otherColor defines the second operand
  1658. * @param result defines Color3 object to store the result into
  1659. * @returns the unmodified current Color3
  1660. */
  1661. Color3.prototype.subtractToRef = function (otherColor, result) {
  1662. result.r = this.r - otherColor.r;
  1663. result.g = this.g - otherColor.g;
  1664. result.b = this.b - otherColor.b;
  1665. return this;
  1666. };
  1667. /**
  1668. * Copy the current object
  1669. * @returns a new Color3 copied the current one
  1670. */
  1671. Color3.prototype.clone = function () {
  1672. return new Color3(this.r, this.g, this.b);
  1673. };
  1674. /**
  1675. * Copies the rgb values from the source in the current Color3
  1676. * @param source defines the source Color3 object
  1677. * @returns the updated Color3 object
  1678. */
  1679. Color3.prototype.copyFrom = function (source) {
  1680. this.r = source.r;
  1681. this.g = source.g;
  1682. this.b = source.b;
  1683. return this;
  1684. };
  1685. /**
  1686. * Updates the Color3 rgb values from the given floats
  1687. * @param r defines the red component to read from
  1688. * @param g defines the green component to read from
  1689. * @param b defines the blue component to read from
  1690. * @returns the current Color3 object
  1691. */
  1692. Color3.prototype.copyFromFloats = function (r, g, b) {
  1693. this.r = r;
  1694. this.g = g;
  1695. this.b = b;
  1696. return this;
  1697. };
  1698. /**
  1699. * Updates the Color3 rgb values from the given floats
  1700. * @param r defines the red component to read from
  1701. * @param g defines the green component to read from
  1702. * @param b defines the blue component to read from
  1703. * @returns the current Color3 object
  1704. */
  1705. Color3.prototype.set = function (r, g, b) {
  1706. return this.copyFromFloats(r, g, b);
  1707. };
  1708. /**
  1709. * Compute the Color3 hexadecimal code as a string
  1710. * @returns a string containing the hexadecimal representation of the Color3 object
  1711. */
  1712. Color3.prototype.toHexString = function () {
  1713. var intR = (this.r * 255) | 0;
  1714. var intG = (this.g * 255) | 0;
  1715. var intB = (this.b * 255) | 0;
  1716. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1717. };
  1718. /**
  1719. * Computes a new Color3 converted from the current one to linear space
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.prototype.toLinearSpace = function () {
  1723. var convertedColor = new Color3();
  1724. this.toLinearSpaceToRef(convertedColor);
  1725. return convertedColor;
  1726. };
  1727. /**
  1728. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1729. * @param convertedColor defines the Color3 object where to store the linear space version
  1730. * @returns the unmodified Color3
  1731. */
  1732. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1733. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1734. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1735. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1736. return this;
  1737. };
  1738. /**
  1739. * Computes a new Color3 converted from the current one to gamma space
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.prototype.toGammaSpace = function () {
  1743. var convertedColor = new Color3();
  1744. this.toGammaSpaceToRef(convertedColor);
  1745. return convertedColor;
  1746. };
  1747. /**
  1748. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1749. * @param convertedColor defines the Color3 object where to store the gamma space version
  1750. * @returns the unmodified Color3
  1751. */
  1752. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1753. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1754. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1755. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1756. return this;
  1757. };
  1758. // Statics
  1759. /**
  1760. * Creates a new Color3 from the string containing valid hexadecimal values
  1761. * @param hex defines a string containing valid hexadecimal values
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.FromHexString = function (hex) {
  1765. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1766. return new Color3(0, 0, 0);
  1767. }
  1768. var r = parseInt(hex.substring(1, 3), 16);
  1769. var g = parseInt(hex.substring(3, 5), 16);
  1770. var b = parseInt(hex.substring(5, 7), 16);
  1771. return Color3.FromInts(r, g, b);
  1772. };
  1773. /**
  1774. * Creates a new Vector3 from the starting index of the given array
  1775. * @param array defines the source array
  1776. * @param offset defines an offset in the source array
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.FromArray = function (array, offset) {
  1780. if (offset === void 0) { offset = 0; }
  1781. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1782. };
  1783. /**
  1784. * Creates a new Color3 from integer values (< 256)
  1785. * @param r defines the red component to read from (value between 0 and 255)
  1786. * @param g defines the green component to read from (value between 0 and 255)
  1787. * @param b defines the blue component to read from (value between 0 and 255)
  1788. * @returns a new Color3 object
  1789. */
  1790. Color3.FromInts = function (r, g, b) {
  1791. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1792. };
  1793. /**
  1794. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1795. * @param start defines the start Color3 value
  1796. * @param end defines the end Color3 value
  1797. * @param amount defines the gradient value between start and end
  1798. * @returns a new Color3 object
  1799. */
  1800. Color3.Lerp = function (start, end, amount) {
  1801. var result = new Color3(0.0, 0.0, 0.0);
  1802. Color3.LerpToRef(start, end, amount, result);
  1803. return result;
  1804. };
  1805. /**
  1806. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1807. * @param left defines the start value
  1808. * @param right defines the end value
  1809. * @param amount defines the gradient factor
  1810. * @param result defines the Color3 object where to store the result
  1811. */
  1812. Color3.LerpToRef = function (left, right, amount, result) {
  1813. result.r = left.r + ((right.r - left.r) * amount);
  1814. result.g = left.g + ((right.g - left.g) * amount);
  1815. result.b = left.b + ((right.b - left.b) * amount);
  1816. };
  1817. /**
  1818. * Returns a Color3 value containing a red color
  1819. * @returns a new Color3 object
  1820. */
  1821. Color3.Red = function () { return new Color3(1, 0, 0); };
  1822. /**
  1823. * Returns a Color3 value containing a green color
  1824. * @returns a new Color3 object
  1825. */
  1826. Color3.Green = function () { return new Color3(0, 1, 0); };
  1827. /**
  1828. * Returns a Color3 value containing a blue color
  1829. * @returns a new Color3 object
  1830. */
  1831. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1832. /**
  1833. * Returns a Color3 value containing a black color
  1834. * @returns a new Color3 object
  1835. */
  1836. Color3.Black = function () { return new Color3(0, 0, 0); };
  1837. /**
  1838. * Returns a Color3 value containing a white color
  1839. * @returns a new Color3 object
  1840. */
  1841. Color3.White = function () { return new Color3(1, 1, 1); };
  1842. /**
  1843. * Returns a Color3 value containing a purple color
  1844. * @returns a new Color3 object
  1845. */
  1846. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1847. /**
  1848. * Returns a Color3 value containing a magenta color
  1849. * @returns a new Color3 object
  1850. */
  1851. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1852. /**
  1853. * Returns a Color3 value containing a yellow color
  1854. * @returns a new Color3 object
  1855. */
  1856. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1857. /**
  1858. * Returns a Color3 value containing a gray color
  1859. * @returns a new Color3 object
  1860. */
  1861. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1862. /**
  1863. * Returns a Color3 value containing a teal color
  1864. * @returns a new Color3 object
  1865. */
  1866. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1867. /**
  1868. * Returns a Color3 value containing a random color
  1869. * @returns a new Color3 object
  1870. */
  1871. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1872. return Color3;
  1873. }());
  1874. BABYLON.Color3 = Color3;
  1875. /**
  1876. * Class used to hold a RBGA color
  1877. */
  1878. var Color4 = /** @class */ (function () {
  1879. /**
  1880. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1881. * @param r defines the red component (between 0 and 1, default is 0)
  1882. * @param g defines the green component (between 0 and 1, default is 0)
  1883. * @param b defines the blue component (between 0 and 1, default is 0)
  1884. * @param a defines the alpha component (between 0 and 1, default is 1)
  1885. */
  1886. function Color4(
  1887. /**
  1888. * Defines the red component (between 0 and 1, default is 0)
  1889. */
  1890. r,
  1891. /**
  1892. * Defines the green component (between 0 and 1, default is 0)
  1893. */
  1894. g,
  1895. /**
  1896. * Defines the blue component (between 0 and 1, default is 0)
  1897. */
  1898. b,
  1899. /**
  1900. * Defines the alpha component (between 0 and 1, default is 1)
  1901. */
  1902. a) {
  1903. if (r === void 0) { r = 0; }
  1904. if (g === void 0) { g = 0; }
  1905. if (b === void 0) { b = 0; }
  1906. if (a === void 0) { a = 1; }
  1907. this.r = r;
  1908. this.g = g;
  1909. this.b = b;
  1910. this.a = a;
  1911. }
  1912. // Operators
  1913. /**
  1914. * Adds in place the given Color4 values to the current Color4 object
  1915. * @param right defines the second operand
  1916. * @returns the current updated Color4 object
  1917. */
  1918. Color4.prototype.addInPlace = function (right) {
  1919. this.r += right.r;
  1920. this.g += right.g;
  1921. this.b += right.b;
  1922. this.a += right.a;
  1923. return this;
  1924. };
  1925. /**
  1926. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1927. * @returns the new array
  1928. */
  1929. Color4.prototype.asArray = function () {
  1930. var result = new Array();
  1931. this.toArray(result, 0);
  1932. return result;
  1933. };
  1934. /**
  1935. * Stores from the starting index in the given array the Color4 successive values
  1936. * @param array defines the array where to store the r,g,b components
  1937. * @param index defines an optional index in the target array to define where to start storing values
  1938. * @returns the current Color4 object
  1939. */
  1940. Color4.prototype.toArray = function (array, index) {
  1941. if (index === undefined) {
  1942. index = 0;
  1943. }
  1944. array[index] = this.r;
  1945. array[index + 1] = this.g;
  1946. array[index + 2] = this.b;
  1947. array[index + 3] = this.a;
  1948. return this;
  1949. };
  1950. /**
  1951. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1952. * @param right defines the second operand
  1953. * @returns a new Color4 object
  1954. */
  1955. Color4.prototype.add = function (right) {
  1956. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1957. };
  1958. /**
  1959. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1960. * @param right defines the second operand
  1961. * @returns a new Color4 object
  1962. */
  1963. Color4.prototype.subtract = function (right) {
  1964. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1965. };
  1966. /**
  1967. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1968. * @param right defines the second operand
  1969. * @param result defines the Color4 object where to store the result
  1970. * @returns the current Color4 object
  1971. */
  1972. Color4.prototype.subtractToRef = function (right, result) {
  1973. result.r = this.r - right.r;
  1974. result.g = this.g - right.g;
  1975. result.b = this.b - right.b;
  1976. result.a = this.a - right.a;
  1977. return this;
  1978. };
  1979. /**
  1980. * Creates a new Color4 with the current Color4 values multiplied by scale
  1981. * @param scale defines the scaling factor to apply
  1982. * @returns a new Color4 object
  1983. */
  1984. Color4.prototype.scale = function (scale) {
  1985. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1986. };
  1987. /**
  1988. * Multiplies the current Color4 values by scale and stores the result in "result"
  1989. * @param scale defines the scaling factor to apply
  1990. * @param result defines the Color4 object where to store the result
  1991. * @returns the current unmodified Color4
  1992. */
  1993. Color4.prototype.scaleToRef = function (scale, result) {
  1994. result.r = this.r * scale;
  1995. result.g = this.g * scale;
  1996. result.b = this.b * scale;
  1997. result.a = this.a * scale;
  1998. return this;
  1999. };
  2000. /**
  2001. * Scale the current Color4 values by a factor and add the result to a given Color4
  2002. * @param scale defines the scale factor
  2003. * @param result defines the Color4 object where to store the result
  2004. * @returns the unmodified current Color4
  2005. */
  2006. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2007. result.r += this.r * scale;
  2008. result.g += this.g * scale;
  2009. result.b += this.b * scale;
  2010. result.a += this.a * scale;
  2011. return this;
  2012. };
  2013. /**
  2014. * Clamps the rgb values by the min and max values and stores the result into "result"
  2015. * @param min defines minimum clamping value (default is 0)
  2016. * @param max defines maximum clamping value (default is 1)
  2017. * @param result defines color to store the result into.
  2018. * @returns the cuurent Color4
  2019. */
  2020. Color4.prototype.clampToRef = function (min, max, result) {
  2021. if (min === void 0) { min = 0; }
  2022. if (max === void 0) { max = 1; }
  2023. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2024. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2025. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2026. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2027. return this;
  2028. };
  2029. /**
  2030. * Multipy an Color4 value by another and return a new Color4 object
  2031. * @param color defines the Color4 value to multiply by
  2032. * @returns a new Color4 object
  2033. */
  2034. Color4.prototype.multiply = function (color) {
  2035. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2036. };
  2037. /**
  2038. * Multipy a Color4 value by another and push the result in a reference value
  2039. * @param color defines the Color4 value to multiply by
  2040. * @param result defines the Color4 to fill the result in
  2041. * @returns the result Color4
  2042. */
  2043. Color4.prototype.multiplyToRef = function (color, result) {
  2044. result.r = this.r * color.r;
  2045. result.g = this.g * color.g;
  2046. result.b = this.b * color.b;
  2047. result.a = this.a * color.a;
  2048. return result;
  2049. };
  2050. /**
  2051. * Creates a string with the Color4 current values
  2052. * @returns the string representation of the Color4 object
  2053. */
  2054. Color4.prototype.toString = function () {
  2055. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2056. };
  2057. /**
  2058. * Returns the string "Color4"
  2059. * @returns "Color4"
  2060. */
  2061. Color4.prototype.getClassName = function () {
  2062. return "Color4";
  2063. };
  2064. /**
  2065. * Compute the Color4 hash code
  2066. * @returns an unique number that can be used to hash Color4 objects
  2067. */
  2068. Color4.prototype.getHashCode = function () {
  2069. var hash = this.r || 0;
  2070. hash = (hash * 397) ^ (this.g || 0);
  2071. hash = (hash * 397) ^ (this.b || 0);
  2072. hash = (hash * 397) ^ (this.a || 0);
  2073. return hash;
  2074. };
  2075. /**
  2076. * Creates a new Color4 copied from the current one
  2077. * @returns a new Color4 object
  2078. */
  2079. Color4.prototype.clone = function () {
  2080. return new Color4(this.r, this.g, this.b, this.a);
  2081. };
  2082. /**
  2083. * Copies the given Color4 values into the current one
  2084. * @param source defines the source Color4 object
  2085. * @returns the current updated Color4 object
  2086. */
  2087. Color4.prototype.copyFrom = function (source) {
  2088. this.r = source.r;
  2089. this.g = source.g;
  2090. this.b = source.b;
  2091. this.a = source.a;
  2092. return this;
  2093. };
  2094. /**
  2095. * Copies the given float values into the current one
  2096. * @param r defines the red component to read from
  2097. * @param g defines the green component to read from
  2098. * @param b defines the blue component to read from
  2099. * @param a defines the alpha component to read from
  2100. * @returns the current updated Color4 object
  2101. */
  2102. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2103. this.r = r;
  2104. this.g = g;
  2105. this.b = b;
  2106. this.a = a;
  2107. return this;
  2108. };
  2109. /**
  2110. * Copies the given float values into the current one
  2111. * @param r defines the red component to read from
  2112. * @param g defines the green component to read from
  2113. * @param b defines the blue component to read from
  2114. * @param a defines the alpha component to read from
  2115. * @returns the current updated Color4 object
  2116. */
  2117. Color4.prototype.set = function (r, g, b, a) {
  2118. return this.copyFromFloats(r, g, b, a);
  2119. };
  2120. /**
  2121. * Compute the Color4 hexadecimal code as a string
  2122. * @returns a string containing the hexadecimal representation of the Color4 object
  2123. */
  2124. Color4.prototype.toHexString = function () {
  2125. var intR = (this.r * 255) | 0;
  2126. var intG = (this.g * 255) | 0;
  2127. var intB = (this.b * 255) | 0;
  2128. var intA = (this.a * 255) | 0;
  2129. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2130. };
  2131. /**
  2132. * Computes a new Color4 converted from the current one to linear space
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.prototype.toLinearSpace = function () {
  2136. var convertedColor = new Color4();
  2137. this.toLinearSpaceToRef(convertedColor);
  2138. return convertedColor;
  2139. };
  2140. /**
  2141. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2142. * @param convertedColor defines the Color4 object where to store the linear space version
  2143. * @returns the unmodified Color4
  2144. */
  2145. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2146. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2147. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2148. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2149. convertedColor.a = this.a;
  2150. return this;
  2151. };
  2152. /**
  2153. * Computes a new Color4 converted from the current one to gamma space
  2154. * @returns a new Color4 object
  2155. */
  2156. Color4.prototype.toGammaSpace = function () {
  2157. var convertedColor = new Color4();
  2158. this.toGammaSpaceToRef(convertedColor);
  2159. return convertedColor;
  2160. };
  2161. /**
  2162. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2163. * @param convertedColor defines the Color4 object where to store the gamma space version
  2164. * @returns the unmodified Color4
  2165. */
  2166. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2167. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2168. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2169. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2170. convertedColor.a = this.a;
  2171. return this;
  2172. };
  2173. // Statics
  2174. /**
  2175. * Creates a new Color4 from the string containing valid hexadecimal values
  2176. * @param hex defines a string containing valid hexadecimal values
  2177. * @returns a new Color4 object
  2178. */
  2179. Color4.FromHexString = function (hex) {
  2180. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2181. return new Color4(0.0, 0.0, 0.0, 0.0);
  2182. }
  2183. var r = parseInt(hex.substring(1, 3), 16);
  2184. var g = parseInt(hex.substring(3, 5), 16);
  2185. var b = parseInt(hex.substring(5, 7), 16);
  2186. var a = parseInt(hex.substring(7, 9), 16);
  2187. return Color4.FromInts(r, g, b, a);
  2188. };
  2189. /**
  2190. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2191. * @param left defines the start value
  2192. * @param right defines the end value
  2193. * @param amount defines the gradient factor
  2194. * @returns a new Color4 object
  2195. */
  2196. Color4.Lerp = function (left, right, amount) {
  2197. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2198. Color4.LerpToRef(left, right, amount, result);
  2199. return result;
  2200. };
  2201. /**
  2202. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2203. * @param left defines the start value
  2204. * @param right defines the end value
  2205. * @param amount defines the gradient factor
  2206. * @param result defines the Color4 object where to store data
  2207. */
  2208. Color4.LerpToRef = function (left, right, amount, result) {
  2209. result.r = left.r + (right.r - left.r) * amount;
  2210. result.g = left.g + (right.g - left.g) * amount;
  2211. result.b = left.b + (right.b - left.b) * amount;
  2212. result.a = left.a + (right.a - left.a) * amount;
  2213. };
  2214. /**
  2215. * Creates a new Color4 from a Color3 and an alpha value
  2216. * @param color3 defines the source Color3 to read from
  2217. * @param alpha defines the alpha component (1.0 by default)
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.FromColor3 = function (color3, alpha) {
  2221. if (alpha === void 0) { alpha = 1.0; }
  2222. return new Color4(color3.r, color3.g, color3.b, alpha);
  2223. };
  2224. /**
  2225. * Creates a new Color4 from the starting index element of the given array
  2226. * @param array defines the source array to read from
  2227. * @param offset defines the offset in the source array
  2228. * @returns a new Color4 object
  2229. */
  2230. Color4.FromArray = function (array, offset) {
  2231. if (offset === void 0) { offset = 0; }
  2232. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2233. };
  2234. /**
  2235. * Creates a new Color3 from integer values (< 256)
  2236. * @param r defines the red component to read from (value between 0 and 255)
  2237. * @param g defines the green component to read from (value between 0 and 255)
  2238. * @param b defines the blue component to read from (value between 0 and 255)
  2239. * @param a defines the alpha component to read from (value between 0 and 255)
  2240. * @returns a new Color3 object
  2241. */
  2242. Color4.FromInts = function (r, g, b, a) {
  2243. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2244. };
  2245. /**
  2246. * Check the content of a given array and convert it to an array containing RGBA data
  2247. * If the original array was already containing count * 4 values then it is returned directly
  2248. * @param colors defines the array to check
  2249. * @param count defines the number of RGBA data to expect
  2250. * @returns an array containing count * 4 values (RGBA)
  2251. */
  2252. Color4.CheckColors4 = function (colors, count) {
  2253. // Check if color3 was used
  2254. if (colors.length === count * 3) {
  2255. var colors4 = [];
  2256. for (var index = 0; index < colors.length; index += 3) {
  2257. var newIndex = (index / 3) * 4;
  2258. colors4[newIndex] = colors[index];
  2259. colors4[newIndex + 1] = colors[index + 1];
  2260. colors4[newIndex + 2] = colors[index + 2];
  2261. colors4[newIndex + 3] = 1.0;
  2262. }
  2263. return colors4;
  2264. }
  2265. return colors;
  2266. };
  2267. return Color4;
  2268. }());
  2269. BABYLON.Color4 = Color4;
  2270. /**
  2271. * Class representing a vector containing 2 coordinates
  2272. */
  2273. var Vector2 = /** @class */ (function () {
  2274. /**
  2275. * Creates a new Vector2 from the given x and y coordinates
  2276. * @param x defines the first coordinate
  2277. * @param y defines the second coordinate
  2278. */
  2279. function Vector2(
  2280. /** defines the first coordinate */
  2281. x,
  2282. /** defines the second coordinate */
  2283. y) {
  2284. if (x === void 0) { x = 0; }
  2285. if (y === void 0) { y = 0; }
  2286. this.x = x;
  2287. this.y = y;
  2288. }
  2289. /**
  2290. * Gets a string with the Vector2 coordinates
  2291. * @returns a string with the Vector2 coordinates
  2292. */
  2293. Vector2.prototype.toString = function () {
  2294. return "{X: " + this.x + " Y:" + this.y + "}";
  2295. };
  2296. /**
  2297. * Gets class name
  2298. * @returns the string "Vector2"
  2299. */
  2300. Vector2.prototype.getClassName = function () {
  2301. return "Vector2";
  2302. };
  2303. /**
  2304. * Gets current vector hash code
  2305. * @returns the Vector2 hash code as a number
  2306. */
  2307. Vector2.prototype.getHashCode = function () {
  2308. var hash = this.x || 0;
  2309. hash = (hash * 397) ^ (this.y || 0);
  2310. return hash;
  2311. };
  2312. // Operators
  2313. /**
  2314. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2315. * @param array defines the source array
  2316. * @param index defines the offset in source array
  2317. * @returns the current Vector2
  2318. */
  2319. Vector2.prototype.toArray = function (array, index) {
  2320. if (index === void 0) { index = 0; }
  2321. array[index] = this.x;
  2322. array[index + 1] = this.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Copy the current vector to an array
  2327. * @returns a new array with 2 elements: the Vector2 coordinates.
  2328. */
  2329. Vector2.prototype.asArray = function () {
  2330. var result = new Array();
  2331. this.toArray(result, 0);
  2332. return result;
  2333. };
  2334. /**
  2335. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2336. * @param source defines the source Vector2
  2337. * @returns the current updated Vector2
  2338. */
  2339. Vector2.prototype.copyFrom = function (source) {
  2340. this.x = source.x;
  2341. this.y = source.y;
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the Vector2 coordinates with the given floats
  2346. * @param x defines the first coordinate
  2347. * @param y defines the second coordinate
  2348. * @returns the current updated Vector2
  2349. */
  2350. Vector2.prototype.copyFromFloats = function (x, y) {
  2351. this.x = x;
  2352. this.y = y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Sets the Vector2 coordinates with the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns the current updated Vector2
  2360. */
  2361. Vector2.prototype.set = function (x, y) {
  2362. return this.copyFromFloats(x, y);
  2363. };
  2364. /**
  2365. * Add another vector with the current one
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2368. */
  2369. Vector2.prototype.add = function (otherVector) {
  2370. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.addToRef = function (otherVector, result) {
  2379. result.x = this.x + otherVector.x;
  2380. result.y = this.y + otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.addInPlace = function (otherVector) {
  2389. this.x += otherVector.x;
  2390. this.y += otherVector.y;
  2391. return this;
  2392. };
  2393. /**
  2394. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2395. * @param otherVector defines the other vector
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.addVector3 = function (otherVector) {
  2399. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2400. };
  2401. /**
  2402. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2403. * @param otherVector defines the other vector
  2404. * @returns a new Vector2
  2405. */
  2406. Vector2.prototype.subtract = function (otherVector) {
  2407. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2408. };
  2409. /**
  2410. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2411. * @param otherVector defines the other vector
  2412. * @param result defines the target vector
  2413. * @returns the unmodified current Vector2
  2414. */
  2415. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2416. result.x = this.x - otherVector.x;
  2417. result.y = this.y - otherVector.y;
  2418. return this;
  2419. };
  2420. /**
  2421. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2422. * @param otherVector defines the other vector
  2423. * @returns the current updated Vector2
  2424. */
  2425. Vector2.prototype.subtractInPlace = function (otherVector) {
  2426. this.x -= otherVector.x;
  2427. this.y -= otherVector.y;
  2428. return this;
  2429. };
  2430. /**
  2431. * Multiplies in place the current Vector2 coordinates by the given ones
  2432. * @param otherVector defines the other vector
  2433. * @returns the current updated Vector2
  2434. */
  2435. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2436. this.x *= otherVector.x;
  2437. this.y *= otherVector.y;
  2438. return this;
  2439. };
  2440. /**
  2441. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2442. * @param otherVector defines the other vector
  2443. * @returns a new Vector2
  2444. */
  2445. Vector2.prototype.multiply = function (otherVector) {
  2446. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2447. };
  2448. /**
  2449. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2450. * @param otherVector defines the other vector
  2451. * @param result defines the target vector
  2452. * @returns the unmodified current Vector2
  2453. */
  2454. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2455. result.x = this.x * otherVector.x;
  2456. result.y = this.y * otherVector.y;
  2457. return this;
  2458. };
  2459. /**
  2460. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2461. * @param x defines the first coordinate
  2462. * @param y defines the second coordinate
  2463. * @returns a new Vector2
  2464. */
  2465. Vector2.prototype.multiplyByFloats = function (x, y) {
  2466. return new Vector2(this.x * x, this.y * y);
  2467. };
  2468. /**
  2469. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2470. * @param otherVector defines the other vector
  2471. * @returns a new Vector2
  2472. */
  2473. Vector2.prototype.divide = function (otherVector) {
  2474. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2475. };
  2476. /**
  2477. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2478. * @param otherVector defines the other vector
  2479. * @param result defines the target vector
  2480. * @returns the unmodified current Vector2
  2481. */
  2482. Vector2.prototype.divideToRef = function (otherVector, result) {
  2483. result.x = this.x / otherVector.x;
  2484. result.y = this.y / otherVector.y;
  2485. return this;
  2486. };
  2487. /**
  2488. * Divides the current Vector2 coordinates by the given ones
  2489. * @param otherVector defines the other vector
  2490. * @returns the current updated Vector2
  2491. */
  2492. Vector2.prototype.divideInPlace = function (otherVector) {
  2493. return this.divideToRef(otherVector, this);
  2494. };
  2495. /**
  2496. * Gets a new Vector2 with current Vector2 negated coordinates
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.prototype.negate = function () {
  2500. return new Vector2(-this.x, -this.y);
  2501. };
  2502. /**
  2503. * Multiply the Vector2 coordinates by scale
  2504. * @param scale defines the scaling factor
  2505. * @returns the current updated Vector2
  2506. */
  2507. Vector2.prototype.scaleInPlace = function (scale) {
  2508. this.x *= scale;
  2509. this.y *= scale;
  2510. return this;
  2511. };
  2512. /**
  2513. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2514. * @param scale defines the scaling factor
  2515. * @returns a new Vector2
  2516. */
  2517. Vector2.prototype.scale = function (scale) {
  2518. var result = new Vector2(0, 0);
  2519. this.scaleToRef(scale, result);
  2520. return result;
  2521. };
  2522. /**
  2523. * Scale the current Vector2 values by a factor to a given Vector2
  2524. * @param scale defines the scale factor
  2525. * @param result defines the Vector2 object where to store the result
  2526. * @returns the unmodified current Vector2
  2527. */
  2528. Vector2.prototype.scaleToRef = function (scale, result) {
  2529. result.x = this.x * scale;
  2530. result.y = this.y * scale;
  2531. return this;
  2532. };
  2533. /**
  2534. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2535. * @param scale defines the scale factor
  2536. * @param result defines the Vector2 object where to store the result
  2537. * @returns the unmodified current Vector2
  2538. */
  2539. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2540. result.x += this.x * scale;
  2541. result.y += this.y * scale;
  2542. return this;
  2543. };
  2544. /**
  2545. * Gets a boolean if two vectors are equals
  2546. * @param otherVector defines the other vector
  2547. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2548. */
  2549. Vector2.prototype.equals = function (otherVector) {
  2550. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2551. };
  2552. /**
  2553. * Gets a boolean if two vectors are equals (using an epsilon value)
  2554. * @param otherVector defines the other vector
  2555. * @param epsilon defines the minimal distance to consider equality
  2556. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2557. */
  2558. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2559. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2560. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2561. };
  2562. /**
  2563. * Gets a new Vector2 from current Vector2 floored values
  2564. * @returns a new Vector2
  2565. */
  2566. Vector2.prototype.floor = function () {
  2567. return new Vector2(Math.floor(this.x), Math.floor(this.y));
  2568. };
  2569. /**
  2570. * Gets a new Vector2 from current Vector2 floored values
  2571. * @returns a new Vector2
  2572. */
  2573. Vector2.prototype.fract = function () {
  2574. return new Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y));
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. return this.minimizeInPlaceFromFloats(other.x, other.y, other.z);
  3174. };
  3175. /**
  3176. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3177. * @param other defines the second operand
  3178. * @returns the current updated Vector3
  3179. */
  3180. Vector3.prototype.maximizeInPlace = function (other) {
  3181. return this.maximizeInPlaceFromFloats(other.x, other.y, other.z);
  3182. };
  3183. /**
  3184. * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
  3185. * @param x defines the x coordinate of the operand
  3186. * @param y defines the y coordinate of the operand
  3187. * @param z defines the z coordinate of the operand
  3188. * @returns the current updated Vector3
  3189. */
  3190. Vector3.prototype.minimizeInPlaceFromFloats = function (x, y, z) {
  3191. if (x < this.x)
  3192. this.x = x;
  3193. if (y < this.y)
  3194. this.y = y;
  3195. if (z < this.z)
  3196. this.z = z;
  3197. return this;
  3198. };
  3199. /**
  3200. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3201. * @param x defines the x coordinate of the operand
  3202. * @param y defines the y coordinate of the operand
  3203. * @param z defines the z coordinate of the operand
  3204. * @returns the current updated Vector3
  3205. */
  3206. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3207. if (x > this.x)
  3208. this.x = x;
  3209. if (y > this.y)
  3210. this.y = y;
  3211. if (z > this.z)
  3212. this.z = z;
  3213. return this;
  3214. };
  3215. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3216. /**
  3217. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3218. */
  3219. get: function () {
  3220. var absX = Math.abs(this.x);
  3221. var absY = Math.abs(this.y);
  3222. if (absX !== absY) {
  3223. return true;
  3224. }
  3225. var absZ = Math.abs(this.z);
  3226. if (absX !== absZ) {
  3227. return true;
  3228. }
  3229. if (absY !== absZ) {
  3230. return true;
  3231. }
  3232. return false;
  3233. },
  3234. enumerable: true,
  3235. configurable: true
  3236. });
  3237. /**
  3238. * Gets a new Vector3 from current Vector3 floored values
  3239. * @returns a new Vector3
  3240. */
  3241. Vector3.prototype.floor = function () {
  3242. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3243. };
  3244. /**
  3245. * Gets a new Vector3 from current Vector3 floored values
  3246. * @returns a new Vector3
  3247. */
  3248. Vector3.prototype.fract = function () {
  3249. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3250. };
  3251. // Properties
  3252. /**
  3253. * Gets the length of the Vector3
  3254. * @returns the length of the Vecto3
  3255. */
  3256. Vector3.prototype.length = function () {
  3257. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3258. };
  3259. /**
  3260. * Gets the squared length of the Vector3
  3261. * @returns squared length of the Vector3
  3262. */
  3263. Vector3.prototype.lengthSquared = function () {
  3264. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3265. };
  3266. /**
  3267. * Normalize the current Vector3.
  3268. * Please note that this is an in place operation.
  3269. * @returns the current updated Vector3
  3270. */
  3271. Vector3.prototype.normalize = function () {
  3272. var len = this.length();
  3273. if (len === 0 || len === 1.0)
  3274. return this;
  3275. var num = 1.0 / len;
  3276. this.x *= num;
  3277. this.y *= num;
  3278. this.z *= num;
  3279. return this;
  3280. };
  3281. /**
  3282. * Normalize the current Vector3 to a new vector
  3283. * @returns the new Vector3
  3284. */
  3285. Vector3.prototype.normalizeToNew = function () {
  3286. var normalized = new Vector3(0, 0, 0);
  3287. this.normalizeToRef(normalized);
  3288. return normalized;
  3289. };
  3290. /**
  3291. * Normalize the current Vector3 to the reference
  3292. * @param reference define the Vector3 to update
  3293. * @returns the updated Vector3
  3294. */
  3295. Vector3.prototype.normalizeToRef = function (reference) {
  3296. var len = this.length();
  3297. if (len === 0 || len === 1.0) {
  3298. reference.set(this.x, this.y, this.z);
  3299. return reference;
  3300. }
  3301. var scale = 1.0 / len;
  3302. this.scaleToRef(scale, reference);
  3303. return reference;
  3304. };
  3305. /**
  3306. * Creates a new Vector3 copied from the current Vector3
  3307. * @returns the new Vector3
  3308. */
  3309. Vector3.prototype.clone = function () {
  3310. return new Vector3(this.x, this.y, this.z);
  3311. };
  3312. /**
  3313. * Copies the given vector coordinates to the current Vector3 ones
  3314. * @param source defines the source Vector3
  3315. * @returns the current updated Vector3
  3316. */
  3317. Vector3.prototype.copyFrom = function (source) {
  3318. this.x = source.x;
  3319. this.y = source.y;
  3320. this.z = source.z;
  3321. return this;
  3322. };
  3323. /**
  3324. * Copies the given floats to the current Vector3 coordinates
  3325. * @param x defines the x coordinate of the operand
  3326. * @param y defines the y coordinate of the operand
  3327. * @param z defines the z coordinate of the operand
  3328. * @returns the current updated Vector3
  3329. */
  3330. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3331. this.x = x;
  3332. this.y = y;
  3333. this.z = z;
  3334. return this;
  3335. };
  3336. /**
  3337. * Copies the given floats to the current Vector3 coordinates
  3338. * @param x defines the x coordinate of the operand
  3339. * @param y defines the y coordinate of the operand
  3340. * @param z defines the z coordinate of the operand
  3341. * @returns the current updated Vector3
  3342. */
  3343. Vector3.prototype.set = function (x, y, z) {
  3344. return this.copyFromFloats(x, y, z);
  3345. };
  3346. // Statics
  3347. /**
  3348. * Get the clip factor between two vectors
  3349. * @param vector0 defines the first operand
  3350. * @param vector1 defines the second operand
  3351. * @param axis defines the axis to use
  3352. * @param size defines the size along the axis
  3353. * @returns the clip factor
  3354. */
  3355. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3356. var d0 = Vector3.Dot(vector0, axis) - size;
  3357. var d1 = Vector3.Dot(vector1, axis) - size;
  3358. var s = d0 / (d0 - d1);
  3359. return s;
  3360. };
  3361. /**
  3362. * Get angle between two vectors
  3363. * @param vector0 angle between vector0 and vector1
  3364. * @param vector1 angle between vector0 and vector1
  3365. * @param normal direction of the normal
  3366. * @return the angle between vector0 and vector1
  3367. */
  3368. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3369. var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
  3370. var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
  3371. var dot = Vector3.Dot(v0, v1);
  3372. var n = MathTmp.Vector3[3];
  3373. Vector3.CrossToRef(v0, v1, n);
  3374. if (Vector3.Dot(n, normal) > 0) {
  3375. return Math.acos(dot);
  3376. }
  3377. return -Math.acos(dot);
  3378. };
  3379. /**
  3380. * Returns a new Vector3 set from the index "offset" of the given array
  3381. * @param array defines the source array
  3382. * @param offset defines the offset in the source array
  3383. * @returns the new Vector3
  3384. */
  3385. Vector3.FromArray = function (array, offset) {
  3386. if (!offset) {
  3387. offset = 0;
  3388. }
  3389. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3390. };
  3391. /**
  3392. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3393. * This function is deprecated. Use FromArray instead
  3394. * @param array defines the source array
  3395. * @param offset defines the offset in the source array
  3396. * @returns the new Vector3
  3397. */
  3398. Vector3.FromFloatArray = function (array, offset) {
  3399. return Vector3.FromArray(array, offset);
  3400. };
  3401. /**
  3402. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3403. * @param array defines the source array
  3404. * @param offset defines the offset in the source array
  3405. * @param result defines the Vector3 where to store the result
  3406. */
  3407. Vector3.FromArrayToRef = function (array, offset, result) {
  3408. result.x = array[offset];
  3409. result.y = array[offset + 1];
  3410. result.z = array[offset + 2];
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3414. * This function is deprecated. Use FromArrayToRef instead.
  3415. * @param array defines the source array
  3416. * @param offset defines the offset in the source array
  3417. * @param result defines the Vector3 where to store the result
  3418. */
  3419. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3420. return Vector3.FromArrayToRef(array, offset, result);
  3421. };
  3422. /**
  3423. * Sets the given vector "result" with the given floats.
  3424. * @param x defines the x coordinate of the source
  3425. * @param y defines the y coordinate of the source
  3426. * @param z defines the z coordinate of the source
  3427. * @param result defines the Vector3 where to store the result
  3428. */
  3429. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3430. result.x = x;
  3431. result.y = y;
  3432. result.z = z;
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3436. * @returns a new empty Vector3
  3437. */
  3438. Vector3.Zero = function () {
  3439. return new Vector3(0.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3443. * @returns a new unit Vector3
  3444. */
  3445. Vector3.One = function () {
  3446. return new Vector3(1.0, 1.0, 1.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3450. * @returns a new up Vector3
  3451. */
  3452. Vector3.Up = function () {
  3453. return new Vector3(0.0, 1.0, 0.0);
  3454. };
  3455. /**
  3456. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3457. * @returns a new down Vector3
  3458. */
  3459. Vector3.Down = function () {
  3460. return new Vector3(0.0, -1.0, 0.0);
  3461. };
  3462. /**
  3463. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3464. * @returns a new forward Vector3
  3465. */
  3466. Vector3.Forward = function () {
  3467. return new Vector3(0.0, 0.0, 1.0);
  3468. };
  3469. /**
  3470. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3471. * @returns a new forward Vector3
  3472. */
  3473. Vector3.Backward = function () {
  3474. return new Vector3(0.0, 0.0, -1.0);
  3475. };
  3476. /**
  3477. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3478. * @returns a new right Vector3
  3479. */
  3480. Vector3.Right = function () {
  3481. return new Vector3(1.0, 0.0, 0.0);
  3482. };
  3483. /**
  3484. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3485. * @returns a new left Vector3
  3486. */
  3487. Vector3.Left = function () {
  3488. return new Vector3(-1.0, 0.0, 0.0);
  3489. };
  3490. /**
  3491. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3492. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3493. * @param vector defines the Vector3 to transform
  3494. * @param transformation defines the transformation matrix
  3495. * @returns the transformed Vector3
  3496. */
  3497. Vector3.TransformCoordinates = function (vector, transformation) {
  3498. var result = Vector3.Zero();
  3499. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3500. return result;
  3501. };
  3502. /**
  3503. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3504. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3505. * @param vector defines the Vector3 to transform
  3506. * @param transformation defines the transformation matrix
  3507. * @param result defines the Vector3 where to store the result
  3508. */
  3509. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3510. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3511. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3512. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3513. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3514. result.x = x / w;
  3515. result.y = y / w;
  3516. result.z = z / w;
  3517. };
  3518. /**
  3519. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3520. * This method computes tranformed coordinates only, not transformed direction vectors
  3521. * @param x define the x coordinate of the source vector
  3522. * @param y define the y coordinate of the source vector
  3523. * @param z define the z coordinate of the source vector
  3524. * @param transformation defines the transformation matrix
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3528. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3529. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3530. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3531. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3532. result.x = rx / rw;
  3533. result.y = ry / rw;
  3534. result.z = rz / rw;
  3535. };
  3536. /**
  3537. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3538. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3539. * @param vector defines the Vector3 to transform
  3540. * @param transformation defines the transformation matrix
  3541. * @returns the new Vector3
  3542. */
  3543. Vector3.TransformNormal = function (vector, transformation) {
  3544. var result = Vector3.Zero();
  3545. Vector3.TransformNormalToRef(vector, transformation, result);
  3546. return result;
  3547. };
  3548. /**
  3549. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3550. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3551. * @param vector defines the Vector3 to transform
  3552. * @param transformation defines the transformation matrix
  3553. * @param result defines the Vector3 where to store the result
  3554. */
  3555. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3558. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3559. result.x = x;
  3560. result.y = y;
  3561. result.z = z;
  3562. };
  3563. /**
  3564. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3565. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3566. * @param x define the x coordinate of the source vector
  3567. * @param y define the y coordinate of the source vector
  3568. * @param z define the z coordinate of the source vector
  3569. * @param transformation defines the transformation matrix
  3570. * @param result defines the Vector3 where to store the result
  3571. */
  3572. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3573. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3574. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3575. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3576. };
  3577. /**
  3578. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3579. * @param value1 defines the first control point
  3580. * @param value2 defines the second control point
  3581. * @param value3 defines the third control point
  3582. * @param value4 defines the fourth control point
  3583. * @param amount defines the amount on the spline to use
  3584. * @returns the new Vector3
  3585. */
  3586. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3587. var squared = amount * amount;
  3588. var cubed = amount * squared;
  3589. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3590. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3591. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3592. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3593. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3594. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3595. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3596. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3597. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * 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"
  3602. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3603. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3604. * @param value defines the current value
  3605. * @param min defines the lower range value
  3606. * @param max defines the upper range value
  3607. * @returns the new Vector3
  3608. */
  3609. Vector3.Clamp = function (value, min, max) {
  3610. var x = value.x;
  3611. x = (x > max.x) ? max.x : x;
  3612. x = (x < min.x) ? min.x : x;
  3613. var y = value.y;
  3614. y = (y > max.y) ? max.y : y;
  3615. y = (y < min.y) ? min.y : y;
  3616. var z = value.z;
  3617. z = (z > max.z) ? max.z : z;
  3618. z = (z < min.z) ? min.z : z;
  3619. return new Vector3(x, y, z);
  3620. };
  3621. /**
  3622. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3623. * @param value1 defines the first control point
  3624. * @param tangent1 defines the first tangent vector
  3625. * @param value2 defines the second control point
  3626. * @param tangent2 defines the second tangent vector
  3627. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3628. * @returns the new Vector3
  3629. */
  3630. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3631. var squared = amount * amount;
  3632. var cubed = amount * squared;
  3633. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3634. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3635. var part3 = (cubed - (2.0 * squared)) + amount;
  3636. var part4 = cubed - squared;
  3637. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3638. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3639. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3640. return new Vector3(x, y, z);
  3641. };
  3642. /**
  3643. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3644. * @param start defines the start value
  3645. * @param end defines the end value
  3646. * @param amount max defines amount between both (between 0 and 1)
  3647. * @returns the new Vector3
  3648. */
  3649. Vector3.Lerp = function (start, end, amount) {
  3650. var result = new Vector3(0, 0, 0);
  3651. Vector3.LerpToRef(start, end, amount, result);
  3652. return result;
  3653. };
  3654. /**
  3655. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3656. * @param start defines the start value
  3657. * @param end defines the end value
  3658. * @param amount max defines amount between both (between 0 and 1)
  3659. * @param result defines the Vector3 where to store the result
  3660. */
  3661. Vector3.LerpToRef = function (start, end, amount, result) {
  3662. result.x = start.x + ((end.x - start.x) * amount);
  3663. result.y = start.y + ((end.y - start.y) * amount);
  3664. result.z = start.z + ((end.z - start.z) * amount);
  3665. };
  3666. /**
  3667. * Returns the dot product (float) between the vectors "left" and "right"
  3668. * @param left defines the left operand
  3669. * @param right defines the right operand
  3670. * @returns the dot product
  3671. */
  3672. Vector3.Dot = function (left, right) {
  3673. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3674. };
  3675. /**
  3676. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3677. * The cross product is then orthogonal to both "left" and "right"
  3678. * @param left defines the left operand
  3679. * @param right defines the right operand
  3680. * @returns the cross product
  3681. */
  3682. Vector3.Cross = function (left, right) {
  3683. var result = Vector3.Zero();
  3684. Vector3.CrossToRef(left, right, result);
  3685. return result;
  3686. };
  3687. /**
  3688. * Sets the given vector "result" with the cross product of "left" and "right"
  3689. * The cross product is then orthogonal to both "left" and "right"
  3690. * @param left defines the left operand
  3691. * @param right defines the right operand
  3692. * @param result defines the Vector3 where to store the result
  3693. */
  3694. Vector3.CrossToRef = function (left, right, result) {
  3695. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3696. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3697. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3698. result.copyFrom(MathTmp.Vector3[0]);
  3699. };
  3700. /**
  3701. * Returns a new Vector3 as the normalization of the given vector
  3702. * @param vector defines the Vector3 to normalize
  3703. * @returns the new Vector3
  3704. */
  3705. Vector3.Normalize = function (vector) {
  3706. var result = Vector3.Zero();
  3707. Vector3.NormalizeToRef(vector, result);
  3708. return result;
  3709. };
  3710. /**
  3711. * Sets the given vector "result" with the normalization of the given first vector
  3712. * @param vector defines the Vector3 to normalize
  3713. * @param result defines the Vector3 where to store the result
  3714. */
  3715. Vector3.NormalizeToRef = function (vector, result) {
  3716. result.copyFrom(vector);
  3717. result.normalize();
  3718. };
  3719. /**
  3720. * Project a Vector3 onto screen space
  3721. * @param vector defines the Vector3 to project
  3722. * @param world defines the world matrix to use
  3723. * @param transform defines the transform (view x projection) matrix to use
  3724. * @param viewport defines the screen viewport to use
  3725. * @returns the new Vector3
  3726. */
  3727. Vector3.Project = function (vector, world, transform, viewport) {
  3728. var cw = viewport.width;
  3729. var ch = viewport.height;
  3730. var cx = viewport.x;
  3731. var cy = viewport.y;
  3732. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3733. 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);
  3734. var matrix = MathTmp.Matrix[0];
  3735. world.multiplyToRef(transform, matrix);
  3736. matrix.multiplyToRef(viewportMatrix, matrix);
  3737. return Vector3.TransformCoordinates(vector, matrix);
  3738. };
  3739. /**
  3740. * Unproject from screen space to object space
  3741. * @param source defines the screen space Vector3 to use
  3742. * @param viewportWidth defines the current width of the viewport
  3743. * @param viewportHeight defines the current height of the viewport
  3744. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3745. * @param transform defines the transform (view x projection) matrix to use
  3746. * @returns the new Vector3
  3747. */
  3748. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3749. var matrix = MathTmp.Matrix[0];
  3750. world.multiplyToRef(transform, matrix);
  3751. matrix.invert();
  3752. source.x = source.x / viewportWidth * 2 - 1;
  3753. source.y = -(source.y / viewportHeight * 2 - 1);
  3754. var vector = Vector3.TransformCoordinates(source, matrix);
  3755. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3756. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3757. vector = vector.scale(1.0 / num);
  3758. }
  3759. return vector;
  3760. };
  3761. /**
  3762. * Unproject from screen space to object space
  3763. * @param source defines the screen space Vector3 to use
  3764. * @param viewportWidth defines the current width of the viewport
  3765. * @param viewportHeight defines the current height of the viewport
  3766. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3767. * @param view defines the view matrix to use
  3768. * @param projection defines the projection matrix to use
  3769. * @returns the new Vector3
  3770. */
  3771. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3772. var result = Vector3.Zero();
  3773. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3774. return result;
  3775. };
  3776. /**
  3777. * Unproject from screen space to object space
  3778. * @param source defines the screen space Vector3 to use
  3779. * @param viewportWidth defines the current width of the viewport
  3780. * @param viewportHeight defines the current height of the viewport
  3781. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3782. * @param view defines the view matrix to use
  3783. * @param projection defines the projection matrix to use
  3784. * @param result defines the Vector3 where to store the result
  3785. */
  3786. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3787. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3788. };
  3789. /**
  3790. * Unproject from screen space to object space
  3791. * @param sourceX defines the screen space x coordinate to use
  3792. * @param sourceY defines the screen space y coordinate to use
  3793. * @param sourceZ defines the screen space z coordinate to use
  3794. * @param viewportWidth defines the current width of the viewport
  3795. * @param viewportHeight defines the current height of the viewport
  3796. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3797. * @param view defines the view matrix to use
  3798. * @param projection defines the projection matrix to use
  3799. * @param result defines the Vector3 where to store the result
  3800. */
  3801. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3802. var matrix = MathTmp.Matrix[0];
  3803. world.multiplyToRef(view, matrix);
  3804. matrix.multiplyToRef(projection, matrix);
  3805. matrix.invert();
  3806. var screenSource = MathTmp.Vector3[0];
  3807. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3808. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3809. screenSource.z = 2 * sourceZ - 1.0;
  3810. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3811. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3812. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3813. result.scaleInPlace(1.0 / num);
  3814. }
  3815. };
  3816. /**
  3817. * Gets the minimal coordinate values between two Vector3
  3818. * @param left defines the first operand
  3819. * @param right defines the second operand
  3820. * @returns the new Vector3
  3821. */
  3822. Vector3.Minimize = function (left, right) {
  3823. var min = left.clone();
  3824. min.minimizeInPlace(right);
  3825. return min;
  3826. };
  3827. /**
  3828. * Gets the maximal coordinate values between two Vector3
  3829. * @param left defines the first operand
  3830. * @param right defines the second operand
  3831. * @returns the new Vector3
  3832. */
  3833. Vector3.Maximize = function (left, right) {
  3834. var max = left.clone();
  3835. max.maximizeInPlace(right);
  3836. return max;
  3837. };
  3838. /**
  3839. * Returns the distance between the vectors "value1" and "value2"
  3840. * @param value1 defines the first operand
  3841. * @param value2 defines the second operand
  3842. * @returns the distance
  3843. */
  3844. Vector3.Distance = function (value1, value2) {
  3845. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3846. };
  3847. /**
  3848. * Returns the squared distance between the vectors "value1" and "value2"
  3849. * @param value1 defines the first operand
  3850. * @param value2 defines the second operand
  3851. * @returns the squared distance
  3852. */
  3853. Vector3.DistanceSquared = function (value1, value2) {
  3854. var x = value1.x - value2.x;
  3855. var y = value1.y - value2.y;
  3856. var z = value1.z - value2.z;
  3857. return (x * x) + (y * y) + (z * z);
  3858. };
  3859. /**
  3860. * Returns a new Vector3 located at the center between "value1" and "value2"
  3861. * @param value1 defines the first operand
  3862. * @param value2 defines the second operand
  3863. * @returns the new Vector3
  3864. */
  3865. Vector3.Center = function (value1, value2) {
  3866. var center = value1.add(value2);
  3867. center.scaleInPlace(0.5);
  3868. return center;
  3869. };
  3870. /**
  3871. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3872. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3873. * to something in order to rotate it from its local system to the given target system
  3874. * Note: axis1, axis2 and axis3 are normalized during this operation
  3875. * @param axis1 defines the first axis
  3876. * @param axis2 defines the second axis
  3877. * @param axis3 defines the third axis
  3878. * @returns a new Vector3
  3879. */
  3880. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3881. var rotation = Vector3.Zero();
  3882. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3883. return rotation;
  3884. };
  3885. /**
  3886. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3887. * @param axis1 defines the first axis
  3888. * @param axis2 defines the second axis
  3889. * @param axis3 defines the third axis
  3890. * @param ref defines the Vector3 where to store the result
  3891. */
  3892. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3893. var quat = MathTmp.Quaternion[0];
  3894. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3895. quat.toEulerAnglesToRef(ref);
  3896. };
  3897. return Vector3;
  3898. }());
  3899. BABYLON.Vector3 = Vector3;
  3900. /**
  3901. * Vector4 class created for EulerAngle class conversion to Quaternion
  3902. */
  3903. var Vector4 = /** @class */ (function () {
  3904. /**
  3905. * Creates a Vector4 object from the given floats.
  3906. * @param x x value of the vector
  3907. * @param y y value of the vector
  3908. * @param z z value of the vector
  3909. * @param w w value of the vector
  3910. */
  3911. function Vector4(
  3912. /** x value of the vector */
  3913. x,
  3914. /** y value of the vector */
  3915. y,
  3916. /** z value of the vector */
  3917. z,
  3918. /** w value of the vector */
  3919. w) {
  3920. this.x = x;
  3921. this.y = y;
  3922. this.z = z;
  3923. this.w = w;
  3924. }
  3925. /**
  3926. * Returns the string with the Vector4 coordinates.
  3927. * @returns a string containing all the vector values
  3928. */
  3929. Vector4.prototype.toString = function () {
  3930. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3931. };
  3932. /**
  3933. * Returns the string "Vector4".
  3934. * @returns "Vector4"
  3935. */
  3936. Vector4.prototype.getClassName = function () {
  3937. return "Vector4";
  3938. };
  3939. /**
  3940. * Returns the Vector4 hash code.
  3941. * @returns a unique hash code
  3942. */
  3943. Vector4.prototype.getHashCode = function () {
  3944. var hash = this.x || 0;
  3945. hash = (hash * 397) ^ (this.y || 0);
  3946. hash = (hash * 397) ^ (this.z || 0);
  3947. hash = (hash * 397) ^ (this.w || 0);
  3948. return hash;
  3949. };
  3950. // Operators
  3951. /**
  3952. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3953. * @returns the resulting array
  3954. */
  3955. Vector4.prototype.asArray = function () {
  3956. var result = new Array();
  3957. this.toArray(result, 0);
  3958. return result;
  3959. };
  3960. /**
  3961. * Populates the given array from the given index with the Vector4 coordinates.
  3962. * @param array array to populate
  3963. * @param index index of the array to start at (default: 0)
  3964. * @returns the Vector4.
  3965. */
  3966. Vector4.prototype.toArray = function (array, index) {
  3967. if (index === undefined) {
  3968. index = 0;
  3969. }
  3970. array[index] = this.x;
  3971. array[index + 1] = this.y;
  3972. array[index + 2] = this.z;
  3973. array[index + 3] = this.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Adds the given vector to the current Vector4.
  3978. * @param otherVector the vector to add
  3979. * @returns the updated Vector4.
  3980. */
  3981. Vector4.prototype.addInPlace = function (otherVector) {
  3982. this.x += otherVector.x;
  3983. this.y += otherVector.y;
  3984. this.z += otherVector.z;
  3985. this.w += otherVector.w;
  3986. return this;
  3987. };
  3988. /**
  3989. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3990. * @param otherVector the vector to add
  3991. * @returns the resulting vector
  3992. */
  3993. Vector4.prototype.add = function (otherVector) {
  3994. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3995. };
  3996. /**
  3997. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3998. * @param otherVector the vector to add
  3999. * @param result the vector to store the result
  4000. * @returns the current Vector4.
  4001. */
  4002. Vector4.prototype.addToRef = function (otherVector, result) {
  4003. result.x = this.x + otherVector.x;
  4004. result.y = this.y + otherVector.y;
  4005. result.z = this.z + otherVector.z;
  4006. result.w = this.w + otherVector.w;
  4007. return this;
  4008. };
  4009. /**
  4010. * Subtract in place the given vector from the current Vector4.
  4011. * @param otherVector the vector to subtract
  4012. * @returns the updated Vector4.
  4013. */
  4014. Vector4.prototype.subtractInPlace = function (otherVector) {
  4015. this.x -= otherVector.x;
  4016. this.y -= otherVector.y;
  4017. this.z -= otherVector.z;
  4018. this.w -= otherVector.w;
  4019. return this;
  4020. };
  4021. /**
  4022. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4023. * @param otherVector the vector to add
  4024. * @returns the new vector with the result
  4025. */
  4026. Vector4.prototype.subtract = function (otherVector) {
  4027. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4028. };
  4029. /**
  4030. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4031. * @param otherVector the vector to subtract
  4032. * @param result the vector to store the result
  4033. * @returns the current Vector4.
  4034. */
  4035. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4036. result.x = this.x - otherVector.x;
  4037. result.y = this.y - otherVector.y;
  4038. result.z = this.z - otherVector.z;
  4039. result.w = this.w - otherVector.w;
  4040. return this;
  4041. };
  4042. /**
  4043. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4044. */
  4045. /**
  4046. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4047. * @param x value to subtract
  4048. * @param y value to subtract
  4049. * @param z value to subtract
  4050. * @param w value to subtract
  4051. * @returns new vector containing the result
  4052. */
  4053. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4054. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4055. };
  4056. /**
  4057. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4058. * @param x value to subtract
  4059. * @param y value to subtract
  4060. * @param z value to subtract
  4061. * @param w value to subtract
  4062. * @param result the vector to store the result in
  4063. * @returns the current Vector4.
  4064. */
  4065. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4066. result.x = this.x - x;
  4067. result.y = this.y - y;
  4068. result.z = this.z - z;
  4069. result.w = this.w - w;
  4070. return this;
  4071. };
  4072. /**
  4073. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4074. * @returns a new vector with the negated values
  4075. */
  4076. Vector4.prototype.negate = function () {
  4077. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4078. };
  4079. /**
  4080. * Multiplies the current Vector4 coordinates by scale (float).
  4081. * @param scale the number to scale with
  4082. * @returns the updated Vector4.
  4083. */
  4084. Vector4.prototype.scaleInPlace = function (scale) {
  4085. this.x *= scale;
  4086. this.y *= scale;
  4087. this.z *= scale;
  4088. this.w *= scale;
  4089. return this;
  4090. };
  4091. /**
  4092. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4093. * @param scale the number to scale with
  4094. * @returns a new vector with the result
  4095. */
  4096. Vector4.prototype.scale = function (scale) {
  4097. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4098. };
  4099. /**
  4100. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4101. * @param scale the number to scale with
  4102. * @param result a vector to store the result in
  4103. * @returns the current Vector4.
  4104. */
  4105. Vector4.prototype.scaleToRef = function (scale, result) {
  4106. result.x = this.x * scale;
  4107. result.y = this.y * scale;
  4108. result.z = this.z * scale;
  4109. result.w = this.w * scale;
  4110. return this;
  4111. };
  4112. /**
  4113. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4114. * @param scale defines the scale factor
  4115. * @param result defines the Vector4 object where to store the result
  4116. * @returns the unmodified current Vector4
  4117. */
  4118. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4119. result.x += this.x * scale;
  4120. result.y += this.y * scale;
  4121. result.z += this.z * scale;
  4122. result.w += this.w * scale;
  4123. return this;
  4124. };
  4125. /**
  4126. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4127. * @param otherVector the vector to compare against
  4128. * @returns true if they are equal
  4129. */
  4130. Vector4.prototype.equals = function (otherVector) {
  4131. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4132. };
  4133. /**
  4134. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4135. * @param otherVector vector to compare against
  4136. * @param epsilon (Default: very small number)
  4137. * @returns true if they are equal
  4138. */
  4139. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4140. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4141. return otherVector
  4142. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4143. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4144. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4145. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4146. };
  4147. /**
  4148. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4149. * @param x x value to compare against
  4150. * @param y y value to compare against
  4151. * @param z z value to compare against
  4152. * @param w w value to compare against
  4153. * @returns true if equal
  4154. */
  4155. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4156. return this.x === x && this.y === y && this.z === z && this.w === w;
  4157. };
  4158. /**
  4159. * Multiplies in place the current Vector4 by the given one.
  4160. * @param otherVector vector to multiple with
  4161. * @returns the updated Vector4.
  4162. */
  4163. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4164. this.x *= otherVector.x;
  4165. this.y *= otherVector.y;
  4166. this.z *= otherVector.z;
  4167. this.w *= otherVector.w;
  4168. return this;
  4169. };
  4170. /**
  4171. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4172. * @param otherVector vector to multiple with
  4173. * @returns resulting new vector
  4174. */
  4175. Vector4.prototype.multiply = function (otherVector) {
  4176. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4177. };
  4178. /**
  4179. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4180. * @param otherVector vector to multiple with
  4181. * @param result vector to store the result
  4182. * @returns the current Vector4.
  4183. */
  4184. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4185. result.x = this.x * otherVector.x;
  4186. result.y = this.y * otherVector.y;
  4187. result.z = this.z * otherVector.z;
  4188. result.w = this.w * otherVector.w;
  4189. return this;
  4190. };
  4191. /**
  4192. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4193. * @param x x value multiply with
  4194. * @param y y value multiply with
  4195. * @param z z value multiply with
  4196. * @param w w value multiply with
  4197. * @returns resulting new vector
  4198. */
  4199. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4200. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4201. };
  4202. /**
  4203. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4204. * @param otherVector vector to devide with
  4205. * @returns resulting new vector
  4206. */
  4207. Vector4.prototype.divide = function (otherVector) {
  4208. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4209. };
  4210. /**
  4211. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4212. * @param otherVector vector to devide with
  4213. * @param result vector to store the result
  4214. * @returns the current Vector4.
  4215. */
  4216. Vector4.prototype.divideToRef = function (otherVector, result) {
  4217. result.x = this.x / otherVector.x;
  4218. result.y = this.y / otherVector.y;
  4219. result.z = this.z / otherVector.z;
  4220. result.w = this.w / otherVector.w;
  4221. return this;
  4222. };
  4223. /**
  4224. * Divides the current Vector3 coordinates by the given ones.
  4225. * @param otherVector vector to devide with
  4226. * @returns the updated Vector3.
  4227. */
  4228. Vector4.prototype.divideInPlace = function (otherVector) {
  4229. return this.divideToRef(otherVector, this);
  4230. };
  4231. /**
  4232. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4233. * @param other defines the second operand
  4234. * @returns the current updated Vector4
  4235. */
  4236. Vector4.prototype.minimizeInPlace = function (other) {
  4237. if (other.x < this.x)
  4238. this.x = other.x;
  4239. if (other.y < this.y)
  4240. this.y = other.y;
  4241. if (other.z < this.z)
  4242. this.z = other.z;
  4243. if (other.w < this.w)
  4244. this.w = other.w;
  4245. return this;
  4246. };
  4247. /**
  4248. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4249. * @param other defines the second operand
  4250. * @returns the current updated Vector4
  4251. */
  4252. Vector4.prototype.maximizeInPlace = function (other) {
  4253. if (other.x > this.x)
  4254. this.x = other.x;
  4255. if (other.y > this.y)
  4256. this.y = other.y;
  4257. if (other.z > this.z)
  4258. this.z = other.z;
  4259. if (other.w > this.w)
  4260. this.w = other.w;
  4261. return this;
  4262. };
  4263. /**
  4264. * Gets a new Vector4 from current Vector4 floored values
  4265. * @returns a new Vector4
  4266. */
  4267. Vector4.prototype.floor = function () {
  4268. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4269. };
  4270. /**
  4271. * Gets a new Vector4 from current Vector3 floored values
  4272. * @returns a new Vector4
  4273. */
  4274. Vector4.prototype.fract = function () {
  4275. 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));
  4276. };
  4277. // Properties
  4278. /**
  4279. * Returns the Vector4 length (float).
  4280. * @returns the length
  4281. */
  4282. Vector4.prototype.length = function () {
  4283. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4284. };
  4285. /**
  4286. * Returns the Vector4 squared length (float).
  4287. * @returns the length squared
  4288. */
  4289. Vector4.prototype.lengthSquared = function () {
  4290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4291. };
  4292. // Methods
  4293. /**
  4294. * Normalizes in place the Vector4.
  4295. * @returns the updated Vector4.
  4296. */
  4297. Vector4.prototype.normalize = function () {
  4298. var len = this.length();
  4299. if (len === 0)
  4300. return this;
  4301. var num = 1.0 / len;
  4302. this.x *= num;
  4303. this.y *= num;
  4304. this.z *= num;
  4305. this.w *= num;
  4306. return this;
  4307. };
  4308. /**
  4309. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4310. * @returns this converted to a new vector3
  4311. */
  4312. Vector4.prototype.toVector3 = function () {
  4313. return new Vector3(this.x, this.y, this.z);
  4314. };
  4315. /**
  4316. * Returns a new Vector4 copied from the current one.
  4317. * @returns the new cloned vector
  4318. */
  4319. Vector4.prototype.clone = function () {
  4320. return new Vector4(this.x, this.y, this.z, this.w);
  4321. };
  4322. /**
  4323. * Updates the current Vector4 with the given one coordinates.
  4324. * @param source the source vector to copy from
  4325. * @returns the updated Vector4.
  4326. */
  4327. Vector4.prototype.copyFrom = function (source) {
  4328. this.x = source.x;
  4329. this.y = source.y;
  4330. this.z = source.z;
  4331. this.w = source.w;
  4332. return this;
  4333. };
  4334. /**
  4335. * Updates the current Vector4 coordinates with the given floats.
  4336. * @param x float to copy from
  4337. * @param y float to copy from
  4338. * @param z float to copy from
  4339. * @param w float to copy from
  4340. * @returns the updated Vector4.
  4341. */
  4342. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4343. this.x = x;
  4344. this.y = y;
  4345. this.z = z;
  4346. this.w = w;
  4347. return this;
  4348. };
  4349. /**
  4350. * Updates the current Vector4 coordinates with the given floats.
  4351. * @param x float to set from
  4352. * @param y float to set from
  4353. * @param z float to set from
  4354. * @param w float to set from
  4355. * @returns the updated Vector4.
  4356. */
  4357. Vector4.prototype.set = function (x, y, z, w) {
  4358. return this.copyFromFloats(x, y, z, w);
  4359. };
  4360. // Statics
  4361. /**
  4362. * Returns a new Vector4 set from the starting index of the given array.
  4363. * @param array the array to pull values from
  4364. * @param offset the offset into the array to start at
  4365. * @returns the new vector
  4366. */
  4367. Vector4.FromArray = function (array, offset) {
  4368. if (!offset) {
  4369. offset = 0;
  4370. }
  4371. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4372. };
  4373. /**
  4374. * Updates the given vector "result" from the starting index of the given array.
  4375. * @param array the array to pull values from
  4376. * @param offset the offset into the array to start at
  4377. * @param result the vector to store the result in
  4378. */
  4379. Vector4.FromArrayToRef = function (array, offset, result) {
  4380. result.x = array[offset];
  4381. result.y = array[offset + 1];
  4382. result.z = array[offset + 2];
  4383. result.w = array[offset + 3];
  4384. };
  4385. /**
  4386. * Updates the given vector "result" from the starting index of the given Float32Array.
  4387. * @param array the array to pull values from
  4388. * @param offset the offset into the array to start at
  4389. * @param result the vector to store the result in
  4390. */
  4391. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4392. Vector4.FromArrayToRef(array, offset, result);
  4393. };
  4394. /**
  4395. * Updates the given vector "result" coordinates from the given floats.
  4396. * @param x float to set from
  4397. * @param y float to set from
  4398. * @param z float to set from
  4399. * @param w float to set from
  4400. * @param result the vector to the floats in
  4401. */
  4402. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4403. result.x = x;
  4404. result.y = y;
  4405. result.z = z;
  4406. result.w = w;
  4407. };
  4408. /**
  4409. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4410. * @returns the new vector
  4411. */
  4412. Vector4.Zero = function () {
  4413. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4414. };
  4415. /**
  4416. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4417. * @returns the new vector
  4418. */
  4419. Vector4.One = function () {
  4420. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4421. };
  4422. /**
  4423. * Returns a new normalized Vector4 from the given one.
  4424. * @param vector the vector to normalize
  4425. * @returns the vector
  4426. */
  4427. Vector4.Normalize = function (vector) {
  4428. var result = Vector4.Zero();
  4429. Vector4.NormalizeToRef(vector, result);
  4430. return result;
  4431. };
  4432. /**
  4433. * Updates the given vector "result" from the normalization of the given one.
  4434. * @param vector the vector to normalize
  4435. * @param result the vector to store the result in
  4436. */
  4437. Vector4.NormalizeToRef = function (vector, result) {
  4438. result.copyFrom(vector);
  4439. result.normalize();
  4440. };
  4441. /**
  4442. * Returns a vector with the minimum values from the left and right vectors
  4443. * @param left left vector to minimize
  4444. * @param right right vector to minimize
  4445. * @returns a new vector with the minimum of the left and right vector values
  4446. */
  4447. Vector4.Minimize = function (left, right) {
  4448. var min = left.clone();
  4449. min.minimizeInPlace(right);
  4450. return min;
  4451. };
  4452. /**
  4453. * Returns a vector with the maximum values from the left and right vectors
  4454. * @param left left vector to maximize
  4455. * @param right right vector to maximize
  4456. * @returns a new vector with the maximum of the left and right vector values
  4457. */
  4458. Vector4.Maximize = function (left, right) {
  4459. var max = left.clone();
  4460. max.maximizeInPlace(right);
  4461. return max;
  4462. };
  4463. /**
  4464. * Returns the distance (float) between the vectors "value1" and "value2".
  4465. * @param value1 value to calulate the distance between
  4466. * @param value2 value to calulate the distance between
  4467. * @return the distance between the two vectors
  4468. */
  4469. Vector4.Distance = function (value1, value2) {
  4470. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4471. };
  4472. /**
  4473. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4474. * @param value1 value to calulate the distance between
  4475. * @param value2 value to calulate the distance between
  4476. * @return the distance between the two vectors squared
  4477. */
  4478. Vector4.DistanceSquared = function (value1, value2) {
  4479. var x = value1.x - value2.x;
  4480. var y = value1.y - value2.y;
  4481. var z = value1.z - value2.z;
  4482. var w = value1.w - value2.w;
  4483. return (x * x) + (y * y) + (z * z) + (w * w);
  4484. };
  4485. /**
  4486. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4487. * @param value1 value to calulate the center between
  4488. * @param value2 value to calulate the center between
  4489. * @return the center between the two vectors
  4490. */
  4491. Vector4.Center = function (value1, value2) {
  4492. var center = value1.add(value2);
  4493. center.scaleInPlace(0.5);
  4494. return center;
  4495. };
  4496. /**
  4497. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4498. * This methods computes transformed normalized direction vectors only.
  4499. * @param vector the vector to transform
  4500. * @param transformation the transformation matrix to apply
  4501. * @returns the new vector
  4502. */
  4503. Vector4.TransformNormal = function (vector, transformation) {
  4504. var result = Vector4.Zero();
  4505. Vector4.TransformNormalToRef(vector, transformation, result);
  4506. return result;
  4507. };
  4508. /**
  4509. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4510. * This methods computes transformed normalized direction vectors only.
  4511. * @param vector the vector to transform
  4512. * @param transformation the transformation matrix to apply
  4513. * @param result the vector to store the result in
  4514. */
  4515. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4516. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4517. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4518. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4519. result.x = x;
  4520. result.y = y;
  4521. result.z = z;
  4522. result.w = vector.w;
  4523. };
  4524. /**
  4525. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4526. * This methods computes transformed normalized direction vectors only.
  4527. * @param x value to transform
  4528. * @param y value to transform
  4529. * @param z value to transform
  4530. * @param w value to transform
  4531. * @param transformation the transformation matrix to apply
  4532. * @param result the vector to store the results in
  4533. */
  4534. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4535. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4536. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4537. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4538. result.w = w;
  4539. };
  4540. return Vector4;
  4541. }());
  4542. BABYLON.Vector4 = Vector4;
  4543. /**
  4544. * Size containing widht and height
  4545. */
  4546. var Size = /** @class */ (function () {
  4547. /**
  4548. * Creates a Size object from the given width and height (floats).
  4549. * @param width width of the new size
  4550. * @param height height of the new size
  4551. */
  4552. function Size(width, height) {
  4553. this.width = width;
  4554. this.height = height;
  4555. }
  4556. /**
  4557. * Returns a string with the Size width and height
  4558. * @returns a string with the Size width and height
  4559. */
  4560. Size.prototype.toString = function () {
  4561. return "{W: " + this.width + ", H: " + this.height + "}";
  4562. };
  4563. /**
  4564. * "Size"
  4565. * @returns the string "Size"
  4566. */
  4567. Size.prototype.getClassName = function () {
  4568. return "Size";
  4569. };
  4570. /**
  4571. * Returns the Size hash code.
  4572. * @returns a hash code for a unique width and height
  4573. */
  4574. Size.prototype.getHashCode = function () {
  4575. var hash = this.width || 0;
  4576. hash = (hash * 397) ^ (this.height || 0);
  4577. return hash;
  4578. };
  4579. /**
  4580. * Updates the current size from the given one.
  4581. * @param src the given size
  4582. */
  4583. Size.prototype.copyFrom = function (src) {
  4584. this.width = src.width;
  4585. this.height = src.height;
  4586. };
  4587. /**
  4588. * Updates in place the current Size from the given floats.
  4589. * @param width width of the new size
  4590. * @param height height of the new size
  4591. * @returns the updated Size.
  4592. */
  4593. Size.prototype.copyFromFloats = function (width, height) {
  4594. this.width = width;
  4595. this.height = height;
  4596. return this;
  4597. };
  4598. /**
  4599. * Updates in place the current Size from the given floats.
  4600. * @param width width to set
  4601. * @param height height to set
  4602. * @returns the updated Size.
  4603. */
  4604. Size.prototype.set = function (width, height) {
  4605. return this.copyFromFloats(width, height);
  4606. };
  4607. /**
  4608. * Multiplies the width and height by numbers
  4609. * @param w factor to multiple the width by
  4610. * @param h factor to multiple the height by
  4611. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4612. */
  4613. Size.prototype.multiplyByFloats = function (w, h) {
  4614. return new Size(this.width * w, this.height * h);
  4615. };
  4616. /**
  4617. * Clones the size
  4618. * @returns a new Size copied from the given one.
  4619. */
  4620. Size.prototype.clone = function () {
  4621. return new Size(this.width, this.height);
  4622. };
  4623. /**
  4624. * True if the current Size and the given one width and height are strictly equal.
  4625. * @param other the other size to compare against
  4626. * @returns True if the current Size and the given one width and height are strictly equal.
  4627. */
  4628. Size.prototype.equals = function (other) {
  4629. if (!other) {
  4630. return false;
  4631. }
  4632. return (this.width === other.width) && (this.height === other.height);
  4633. };
  4634. Object.defineProperty(Size.prototype, "surface", {
  4635. /**
  4636. * The surface of the Size : width * height (float).
  4637. */
  4638. get: function () {
  4639. return this.width * this.height;
  4640. },
  4641. enumerable: true,
  4642. configurable: true
  4643. });
  4644. /**
  4645. * Create a new size of zero
  4646. * @returns a new Size set to (0.0, 0.0)
  4647. */
  4648. Size.Zero = function () {
  4649. return new Size(0.0, 0.0);
  4650. };
  4651. /**
  4652. * Sums the width and height of two sizes
  4653. * @param otherSize size to add to this size
  4654. * @returns a new Size set as the addition result of the current Size and the given one.
  4655. */
  4656. Size.prototype.add = function (otherSize) {
  4657. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4658. return r;
  4659. };
  4660. /**
  4661. * Subtracts the width and height of two
  4662. * @param otherSize size to subtract to this size
  4663. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4664. */
  4665. Size.prototype.subtract = function (otherSize) {
  4666. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4667. return r;
  4668. };
  4669. /**
  4670. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4671. * @param start starting size to lerp between
  4672. * @param end end size to lerp between
  4673. * @param amount amount to lerp between the start and end values
  4674. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4675. */
  4676. Size.Lerp = function (start, end, amount) {
  4677. var w = start.width + ((end.width - start.width) * amount);
  4678. var h = start.height + ((end.height - start.height) * amount);
  4679. return new Size(w, h);
  4680. };
  4681. return Size;
  4682. }());
  4683. BABYLON.Size = Size;
  4684. /**
  4685. * Class used to store quaternion data
  4686. * @see https://en.wikipedia.org/wiki/Quaternion
  4687. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4688. */
  4689. var Quaternion = /** @class */ (function () {
  4690. /**
  4691. * Creates a new Quaternion from the given floats
  4692. * @param x defines the first component (0 by default)
  4693. * @param y defines the second component (0 by default)
  4694. * @param z defines the third component (0 by default)
  4695. * @param w defines the fourth component (1.0 by default)
  4696. */
  4697. function Quaternion(
  4698. /** defines the first component (0 by default) */
  4699. x,
  4700. /** defines the second component (0 by default) */
  4701. y,
  4702. /** defines the third component (0 by default) */
  4703. z,
  4704. /** defines the fourth component (1.0 by default) */
  4705. w) {
  4706. if (x === void 0) { x = 0.0; }
  4707. if (y === void 0) { y = 0.0; }
  4708. if (z === void 0) { z = 0.0; }
  4709. if (w === void 0) { w = 1.0; }
  4710. this.x = x;
  4711. this.y = y;
  4712. this.z = z;
  4713. this.w = w;
  4714. }
  4715. /**
  4716. * Gets a string representation for the current quaternion
  4717. * @returns a string with the Quaternion coordinates
  4718. */
  4719. Quaternion.prototype.toString = function () {
  4720. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4721. };
  4722. /**
  4723. * Gets the class name of the quaternion
  4724. * @returns the string "Quaternion"
  4725. */
  4726. Quaternion.prototype.getClassName = function () {
  4727. return "Quaternion";
  4728. };
  4729. /**
  4730. * Gets a hash code for this quaternion
  4731. * @returns the quaternion hash code
  4732. */
  4733. Quaternion.prototype.getHashCode = function () {
  4734. var hash = this.x || 0;
  4735. hash = (hash * 397) ^ (this.y || 0);
  4736. hash = (hash * 397) ^ (this.z || 0);
  4737. hash = (hash * 397) ^ (this.w || 0);
  4738. return hash;
  4739. };
  4740. /**
  4741. * Copy the quaternion to an array
  4742. * @returns a new array populated with 4 elements from the quaternion coordinates
  4743. */
  4744. Quaternion.prototype.asArray = function () {
  4745. return [this.x, this.y, this.z, this.w];
  4746. };
  4747. /**
  4748. * Check if two quaternions are equals
  4749. * @param otherQuaternion defines the second operand
  4750. * @return true if the current quaternion and the given one coordinates are strictly equals
  4751. */
  4752. Quaternion.prototype.equals = function (otherQuaternion) {
  4753. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4754. };
  4755. /**
  4756. * Clone the current quaternion
  4757. * @returns a new quaternion copied from the current one
  4758. */
  4759. Quaternion.prototype.clone = function () {
  4760. return new Quaternion(this.x, this.y, this.z, this.w);
  4761. };
  4762. /**
  4763. * Copy a quaternion to the current one
  4764. * @param other defines the other quaternion
  4765. * @returns the updated current quaternion
  4766. */
  4767. Quaternion.prototype.copyFrom = function (other) {
  4768. this.x = other.x;
  4769. this.y = other.y;
  4770. this.z = other.z;
  4771. this.w = other.w;
  4772. return this;
  4773. };
  4774. /**
  4775. * Updates the current quaternion with the given float coordinates
  4776. * @param x defines the x coordinate
  4777. * @param y defines the y coordinate
  4778. * @param z defines the z coordinate
  4779. * @param w defines the w coordinate
  4780. * @returns the updated current quaternion
  4781. */
  4782. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4783. this.x = x;
  4784. this.y = y;
  4785. this.z = z;
  4786. this.w = w;
  4787. return this;
  4788. };
  4789. /**
  4790. * Updates the current quaternion from the given float coordinates
  4791. * @param x defines the x coordinate
  4792. * @param y defines the y coordinate
  4793. * @param z defines the z coordinate
  4794. * @param w defines the w coordinate
  4795. * @returns the updated current quaternion
  4796. */
  4797. Quaternion.prototype.set = function (x, y, z, w) {
  4798. return this.copyFromFloats(x, y, z, w);
  4799. };
  4800. /**
  4801. * Adds two quaternions
  4802. * @param other defines the second operand
  4803. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4804. */
  4805. Quaternion.prototype.add = function (other) {
  4806. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4807. };
  4808. /**
  4809. * Add a quaternion to the current one
  4810. * @param other defines the quaternion to add
  4811. * @returns the current quaternion
  4812. */
  4813. Quaternion.prototype.addInPlace = function (other) {
  4814. this.x += other.x;
  4815. this.y += other.y;
  4816. this.z += other.z;
  4817. this.w += other.w;
  4818. return this;
  4819. };
  4820. /**
  4821. * Subtract two quaternions
  4822. * @param other defines the second operand
  4823. * @returns a new quaternion as the subtraction result of the given one from the current one
  4824. */
  4825. Quaternion.prototype.subtract = function (other) {
  4826. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4827. };
  4828. /**
  4829. * Multiplies the current quaternion by a scale factor
  4830. * @param value defines the scale factor
  4831. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4832. */
  4833. Quaternion.prototype.scale = function (value) {
  4834. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4835. };
  4836. /**
  4837. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4838. * @param scale defines the scale factor
  4839. * @param result defines the Quaternion object where to store the result
  4840. * @returns the unmodified current quaternion
  4841. */
  4842. Quaternion.prototype.scaleToRef = function (scale, result) {
  4843. result.x = this.x * scale;
  4844. result.y = this.y * scale;
  4845. result.z = this.z * scale;
  4846. result.w = this.w * scale;
  4847. return this;
  4848. };
  4849. /**
  4850. * Multiplies in place the current quaternion by a scale factor
  4851. * @param value defines the scale factor
  4852. * @returns the current modified quaternion
  4853. */
  4854. Quaternion.prototype.scaleInPlace = function (value) {
  4855. this.x *= value;
  4856. this.y *= value;
  4857. this.z *= value;
  4858. this.w *= value;
  4859. return this;
  4860. };
  4861. /**
  4862. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4863. * @param scale defines the scale factor
  4864. * @param result defines the Quaternion object where to store the result
  4865. * @returns the unmodified current quaternion
  4866. */
  4867. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4868. result.x += this.x * scale;
  4869. result.y += this.y * scale;
  4870. result.z += this.z * scale;
  4871. result.w += this.w * scale;
  4872. return this;
  4873. };
  4874. /**
  4875. * Multiplies two quaternions
  4876. * @param q1 defines the second operand
  4877. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4878. */
  4879. Quaternion.prototype.multiply = function (q1) {
  4880. var result = new Quaternion(0, 0, 0, 1.0);
  4881. this.multiplyToRef(q1, result);
  4882. return result;
  4883. };
  4884. /**
  4885. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4886. * @param q1 defines the second operand
  4887. * @param result defines the target quaternion
  4888. * @returns the current quaternion
  4889. */
  4890. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4891. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4892. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4893. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4894. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4895. result.copyFromFloats(x, y, z, w);
  4896. return this;
  4897. };
  4898. /**
  4899. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4900. * @param q1 defines the second operand
  4901. * @returns the currentupdated quaternion
  4902. */
  4903. Quaternion.prototype.multiplyInPlace = function (q1) {
  4904. this.multiplyToRef(q1, this);
  4905. return this;
  4906. };
  4907. /**
  4908. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4909. * @param ref defines the target quaternion
  4910. * @returns the current quaternion
  4911. */
  4912. Quaternion.prototype.conjugateToRef = function (ref) {
  4913. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4914. return this;
  4915. };
  4916. /**
  4917. * Conjugates in place (1-q) the current quaternion
  4918. * @returns the current updated quaternion
  4919. */
  4920. Quaternion.prototype.conjugateInPlace = function () {
  4921. this.x *= -1;
  4922. this.y *= -1;
  4923. this.z *= -1;
  4924. return this;
  4925. };
  4926. /**
  4927. * Conjugates in place (1-q) the current quaternion
  4928. * @returns a new quaternion
  4929. */
  4930. Quaternion.prototype.conjugate = function () {
  4931. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4932. return result;
  4933. };
  4934. /**
  4935. * Gets length of current quaternion
  4936. * @returns the quaternion length (float)
  4937. */
  4938. Quaternion.prototype.length = function () {
  4939. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4940. };
  4941. /**
  4942. * Normalize in place the current quaternion
  4943. * @returns the current updated quaternion
  4944. */
  4945. Quaternion.prototype.normalize = function () {
  4946. var length = 1.0 / this.length();
  4947. this.x *= length;
  4948. this.y *= length;
  4949. this.z *= length;
  4950. this.w *= length;
  4951. return this;
  4952. };
  4953. /**
  4954. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4955. * @param order is a reserved parameter and is ignore for now
  4956. * @returns a new Vector3 containing the Euler angles
  4957. */
  4958. Quaternion.prototype.toEulerAngles = function (order) {
  4959. if (order === void 0) { order = "YZX"; }
  4960. var result = Vector3.Zero();
  4961. this.toEulerAnglesToRef(result, order);
  4962. return result;
  4963. };
  4964. /**
  4965. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4966. * @param result defines the vector which will be filled with the Euler angles
  4967. * @param order is a reserved parameter and is ignore for now
  4968. * @returns the current unchanged quaternion
  4969. */
  4970. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4971. if (order === void 0) { order = "YZX"; }
  4972. var qz = this.z;
  4973. var qx = this.x;
  4974. var qy = this.y;
  4975. var qw = this.w;
  4976. var sqw = qw * qw;
  4977. var sqz = qz * qz;
  4978. var sqx = qx * qx;
  4979. var sqy = qy * qy;
  4980. var zAxisY = qy * qz - qx * qw;
  4981. var limit = .4999999;
  4982. if (zAxisY < -limit) {
  4983. result.y = 2 * Math.atan2(qy, qw);
  4984. result.x = Math.PI / 2;
  4985. result.z = 0;
  4986. }
  4987. else if (zAxisY > limit) {
  4988. result.y = 2 * Math.atan2(qy, qw);
  4989. result.x = -Math.PI / 2;
  4990. result.z = 0;
  4991. }
  4992. else {
  4993. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4994. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4995. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4996. }
  4997. return this;
  4998. };
  4999. /**
  5000. * Updates the given rotation matrix with the current quaternion values
  5001. * @param result defines the target matrix
  5002. * @returns the current unchanged quaternion
  5003. */
  5004. Quaternion.prototype.toRotationMatrix = function (result) {
  5005. var xx = this.x * this.x;
  5006. var yy = this.y * this.y;
  5007. var zz = this.z * this.z;
  5008. var xy = this.x * this.y;
  5009. var zw = this.z * this.w;
  5010. var zx = this.z * this.x;
  5011. var yw = this.y * this.w;
  5012. var yz = this.y * this.z;
  5013. var xw = this.x * this.w;
  5014. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5015. result.m[1] = 2.0 * (xy + zw);
  5016. result.m[2] = 2.0 * (zx - yw);
  5017. result.m[3] = 0;
  5018. result.m[4] = 2.0 * (xy - zw);
  5019. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5020. result.m[6] = 2.0 * (yz + xw);
  5021. result.m[7] = 0;
  5022. result.m[8] = 2.0 * (zx + yw);
  5023. result.m[9] = 2.0 * (yz - xw);
  5024. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5025. result.m[11] = 0;
  5026. result.m[12] = 0;
  5027. result.m[13] = 0;
  5028. result.m[14] = 0;
  5029. result.m[15] = 1.0;
  5030. result._markAsUpdated();
  5031. return this;
  5032. };
  5033. /**
  5034. * Updates the current quaternion from the given rotation matrix values
  5035. * @param matrix defines the source matrix
  5036. * @returns the current updated quaternion
  5037. */
  5038. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5039. Quaternion.FromRotationMatrixToRef(matrix, this);
  5040. return this;
  5041. };
  5042. // Statics
  5043. /**
  5044. * Creates a new quaternion from a rotation matrix
  5045. * @param matrix defines the source matrix
  5046. * @returns a new quaternion created from the given rotation matrix values
  5047. */
  5048. Quaternion.FromRotationMatrix = function (matrix) {
  5049. var result = new Quaternion();
  5050. Quaternion.FromRotationMatrixToRef(matrix, result);
  5051. return result;
  5052. };
  5053. /**
  5054. * Updates the given quaternion with the given rotation matrix values
  5055. * @param matrix defines the source matrix
  5056. * @param result defines the target quaternion
  5057. */
  5058. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5059. var data = matrix.m;
  5060. var m11 = data[0], m12 = data[4], m13 = data[8];
  5061. var m21 = data[1], m22 = data[5], m23 = data[9];
  5062. var m31 = data[2], m32 = data[6], m33 = data[10];
  5063. var trace = m11 + m22 + m33;
  5064. var s;
  5065. if (trace > 0) {
  5066. s = 0.5 / Math.sqrt(trace + 1.0);
  5067. result.w = 0.25 / s;
  5068. result.x = (m32 - m23) * s;
  5069. result.y = (m13 - m31) * s;
  5070. result.z = (m21 - m12) * s;
  5071. }
  5072. else if (m11 > m22 && m11 > m33) {
  5073. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5074. result.w = (m32 - m23) / s;
  5075. result.x = 0.25 * s;
  5076. result.y = (m12 + m21) / s;
  5077. result.z = (m13 + m31) / s;
  5078. }
  5079. else if (m22 > m33) {
  5080. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5081. result.w = (m13 - m31) / s;
  5082. result.x = (m12 + m21) / s;
  5083. result.y = 0.25 * s;
  5084. result.z = (m23 + m32) / s;
  5085. }
  5086. else {
  5087. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5088. result.w = (m21 - m12) / s;
  5089. result.x = (m13 + m31) / s;
  5090. result.y = (m23 + m32) / s;
  5091. result.z = 0.25 * s;
  5092. }
  5093. };
  5094. /**
  5095. * Returns the dot product (float) between the quaternions "left" and "right"
  5096. * @param left defines the left operand
  5097. * @param right defines the right operand
  5098. * @returns the dot product
  5099. */
  5100. Quaternion.Dot = function (left, right) {
  5101. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5102. };
  5103. /**
  5104. * Checks if the two quaternions are close to each other
  5105. * @param quat0 defines the first quaternion to check
  5106. * @param quat1 defines the second quaternion to check
  5107. * @returns true if the two quaternions are close to each other
  5108. */
  5109. Quaternion.AreClose = function (quat0, quat1) {
  5110. var dot = Quaternion.Dot(quat0, quat1);
  5111. return dot >= 0;
  5112. };
  5113. /**
  5114. * Creates an empty quaternion
  5115. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5116. */
  5117. Quaternion.Zero = function () {
  5118. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5119. };
  5120. /**
  5121. * Inverse a given quaternion
  5122. * @param q defines the source quaternion
  5123. * @returns a new quaternion as the inverted current quaternion
  5124. */
  5125. Quaternion.Inverse = function (q) {
  5126. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5127. };
  5128. /**
  5129. * Creates an identity quaternion
  5130. * @returns the identity quaternion
  5131. */
  5132. Quaternion.Identity = function () {
  5133. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5134. };
  5135. /**
  5136. * Gets a boolean indicating if the given quaternion is identity
  5137. * @param quaternion defines the quaternion to check
  5138. * @returns true if the quaternion is identity
  5139. */
  5140. Quaternion.IsIdentity = function (quaternion) {
  5141. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5142. };
  5143. /**
  5144. * Creates a quaternion from a rotation around an axis
  5145. * @param axis defines the axis to use
  5146. * @param angle defines the angle to use
  5147. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5148. */
  5149. Quaternion.RotationAxis = function (axis, angle) {
  5150. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5151. };
  5152. /**
  5153. * Creates a rotation around an axis and stores it into the given quaternion
  5154. * @param axis defines the axis to use
  5155. * @param angle defines the angle to use
  5156. * @param result defines the target quaternion
  5157. * @returns the target quaternion
  5158. */
  5159. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5160. var sin = Math.sin(angle / 2);
  5161. axis.normalize();
  5162. result.w = Math.cos(angle / 2);
  5163. result.x = axis.x * sin;
  5164. result.y = axis.y * sin;
  5165. result.z = axis.z * sin;
  5166. return result;
  5167. };
  5168. /**
  5169. * Creates a new quaternion from data stored into an array
  5170. * @param array defines the data source
  5171. * @param offset defines the offset in the source array where the data starts
  5172. * @returns a new quaternion
  5173. */
  5174. Quaternion.FromArray = function (array, offset) {
  5175. if (!offset) {
  5176. offset = 0;
  5177. }
  5178. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5179. };
  5180. /**
  5181. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5182. * @param yaw defines the rotation around Y axis
  5183. * @param pitch defines the rotation around X axis
  5184. * @param roll defines the rotation around Z axis
  5185. * @returns the new quaternion
  5186. */
  5187. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5188. var q = new Quaternion();
  5189. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5190. return q;
  5191. };
  5192. /**
  5193. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5194. * @param yaw defines the rotation around Y axis
  5195. * @param pitch defines the rotation around X axis
  5196. * @param roll defines the rotation around Z axis
  5197. * @param result defines the target quaternion
  5198. */
  5199. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5200. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5201. var halfRoll = roll * 0.5;
  5202. var halfPitch = pitch * 0.5;
  5203. var halfYaw = yaw * 0.5;
  5204. var sinRoll = Math.sin(halfRoll);
  5205. var cosRoll = Math.cos(halfRoll);
  5206. var sinPitch = Math.sin(halfPitch);
  5207. var cosPitch = Math.cos(halfPitch);
  5208. var sinYaw = Math.sin(halfYaw);
  5209. var cosYaw = Math.cos(halfYaw);
  5210. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5211. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5212. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5213. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5214. };
  5215. /**
  5216. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5217. * @param alpha defines the rotation around first axis
  5218. * @param beta defines the rotation around second axis
  5219. * @param gamma defines the rotation around third axis
  5220. * @returns the new quaternion
  5221. */
  5222. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5223. var result = new Quaternion();
  5224. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5225. return result;
  5226. };
  5227. /**
  5228. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5229. * @param alpha defines the rotation around first axis
  5230. * @param beta defines the rotation around second axis
  5231. * @param gamma defines the rotation around third axis
  5232. * @param result defines the target quaternion
  5233. */
  5234. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5235. // Produces a quaternion from Euler angles in the z-x-z orientation
  5236. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5237. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5238. var halfBeta = beta * 0.5;
  5239. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5240. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5241. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5242. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5243. };
  5244. /**
  5245. * 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)
  5246. * @param axis1 defines the first axis
  5247. * @param axis2 defines the second axis
  5248. * @param axis3 defines the third axis
  5249. * @returns the new quaternion
  5250. */
  5251. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5252. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5253. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5254. return quat;
  5255. };
  5256. /**
  5257. * 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
  5258. * @param axis1 defines the first axis
  5259. * @param axis2 defines the second axis
  5260. * @param axis3 defines the third axis
  5261. * @param ref defines the target quaternion
  5262. */
  5263. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5264. var rotMat = MathTmp.Matrix[0];
  5265. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5266. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5267. };
  5268. /**
  5269. * Interpolates between two quaternions
  5270. * @param left defines first quaternion
  5271. * @param right defines second quaternion
  5272. * @param amount defines the gradient to use
  5273. * @returns the new interpolated quaternion
  5274. */
  5275. Quaternion.Slerp = function (left, right, amount) {
  5276. var result = Quaternion.Identity();
  5277. Quaternion.SlerpToRef(left, right, amount, result);
  5278. return result;
  5279. };
  5280. /**
  5281. * Interpolates between two quaternions and stores it into a target quaternion
  5282. * @param left defines first quaternion
  5283. * @param right defines second quaternion
  5284. * @param amount defines the gradient to use
  5285. * @param result defines the target quaternion
  5286. */
  5287. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5288. var num2;
  5289. var num3;
  5290. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5291. var flag = false;
  5292. if (num4 < 0) {
  5293. flag = true;
  5294. num4 = -num4;
  5295. }
  5296. if (num4 > 0.999999) {
  5297. num3 = 1 - amount;
  5298. num2 = flag ? -amount : amount;
  5299. }
  5300. else {
  5301. var num5 = Math.acos(num4);
  5302. var num6 = (1.0 / Math.sin(num5));
  5303. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5304. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5305. }
  5306. result.x = (num3 * left.x) + (num2 * right.x);
  5307. result.y = (num3 * left.y) + (num2 * right.y);
  5308. result.z = (num3 * left.z) + (num2 * right.z);
  5309. result.w = (num3 * left.w) + (num2 * right.w);
  5310. };
  5311. /**
  5312. * Interpolate between two quaternions using Hermite interpolation
  5313. * @param value1 defines first quaternion
  5314. * @param tangent1 defines the incoming tangent
  5315. * @param value2 defines second quaternion
  5316. * @param tangent2 defines the outgoing tangent
  5317. * @param amount defines the target quaternion
  5318. * @returns the new interpolated quaternion
  5319. */
  5320. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5321. var squared = amount * amount;
  5322. var cubed = amount * squared;
  5323. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5324. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5325. var part3 = (cubed - (2.0 * squared)) + amount;
  5326. var part4 = cubed - squared;
  5327. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5328. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5329. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5330. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5331. return new Quaternion(x, y, z, w);
  5332. };
  5333. return Quaternion;
  5334. }());
  5335. BABYLON.Quaternion = Quaternion;
  5336. /**
  5337. * Class used to store matrix data (4x4)
  5338. */
  5339. var Matrix = /** @class */ (function () {
  5340. /**
  5341. * Creates an empty matrix (filled with zeros)
  5342. */
  5343. function Matrix() {
  5344. this._isIdentity = false;
  5345. this._isIdentityDirty = true;
  5346. /**
  5347. * Gets or sets the internal data of the matrix
  5348. */
  5349. this.m = new Float32Array(16);
  5350. this._markAsUpdated();
  5351. }
  5352. /** @hidden */
  5353. Matrix.prototype._markAsUpdated = function () {
  5354. this.updateFlag = Matrix._updateFlagSeed++;
  5355. this._isIdentityDirty = true;
  5356. };
  5357. // Properties
  5358. /**
  5359. * Check if the current matrix is indentity
  5360. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5361. * @returns true is the matrix is the identity matrix
  5362. */
  5363. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5364. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5365. if (this._isIdentityDirty) {
  5366. this._isIdentityDirty = false;
  5367. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5368. this._isIdentity = false;
  5369. }
  5370. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5371. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5372. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5373. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5374. this._isIdentity = false;
  5375. }
  5376. else {
  5377. this._isIdentity = true;
  5378. }
  5379. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5380. this._isIdentity = false;
  5381. }
  5382. }
  5383. return this._isIdentity;
  5384. };
  5385. /**
  5386. * Gets the determinant of the matrix
  5387. * @returns the matrix determinant
  5388. */
  5389. Matrix.prototype.determinant = function () {
  5390. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5391. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5392. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5393. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5394. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5395. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5396. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5397. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5398. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5399. };
  5400. // Methods
  5401. /**
  5402. * Returns the matrix as a Float32Array
  5403. * @returns the matrix underlying array
  5404. */
  5405. Matrix.prototype.toArray = function () {
  5406. return this.m;
  5407. };
  5408. /**
  5409. * Returns the matrix as a Float32Array
  5410. * @returns the matrix underlying array.
  5411. */
  5412. Matrix.prototype.asArray = function () {
  5413. return this.toArray();
  5414. };
  5415. /**
  5416. * Inverts the current matrix in place
  5417. * @returns the current inverted matrix
  5418. */
  5419. Matrix.prototype.invert = function () {
  5420. this.invertToRef(this);
  5421. return this;
  5422. };
  5423. /**
  5424. * Sets all the matrix elements to zero
  5425. * @returns the current matrix
  5426. */
  5427. Matrix.prototype.reset = function () {
  5428. for (var index = 0; index < 16; index++) {
  5429. this.m[index] = 0.0;
  5430. }
  5431. this._markAsUpdated();
  5432. return this;
  5433. };
  5434. /**
  5435. * Adds the current matrix with a second one
  5436. * @param other defines the matrix to add
  5437. * @returns a new matrix as the addition of the current matrix and the given one
  5438. */
  5439. Matrix.prototype.add = function (other) {
  5440. var result = new Matrix();
  5441. this.addToRef(other, result);
  5442. return result;
  5443. };
  5444. /**
  5445. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5446. * @param other defines the matrix to add
  5447. * @param result defines the target matrix
  5448. * @returns the current matrix
  5449. */
  5450. Matrix.prototype.addToRef = function (other, result) {
  5451. for (var index = 0; index < 16; index++) {
  5452. result.m[index] = this.m[index] + other.m[index];
  5453. }
  5454. result._markAsUpdated();
  5455. return this;
  5456. };
  5457. /**
  5458. * Adds in place the given matrix to the current matrix
  5459. * @param other defines the second operand
  5460. * @returns the current updated matrix
  5461. */
  5462. Matrix.prototype.addToSelf = function (other) {
  5463. for (var index = 0; index < 16; index++) {
  5464. this.m[index] += other.m[index];
  5465. }
  5466. this._markAsUpdated();
  5467. return this;
  5468. };
  5469. /**
  5470. * Sets the given matrix to the current inverted Matrix
  5471. * @param other defines the target matrix
  5472. * @returns the unmodified current matrix
  5473. */
  5474. Matrix.prototype.invertToRef = function (other) {
  5475. var l1 = this.m[0];
  5476. var l2 = this.m[1];
  5477. var l3 = this.m[2];
  5478. var l4 = this.m[3];
  5479. var l5 = this.m[4];
  5480. var l6 = this.m[5];
  5481. var l7 = this.m[6];
  5482. var l8 = this.m[7];
  5483. var l9 = this.m[8];
  5484. var l10 = this.m[9];
  5485. var l11 = this.m[10];
  5486. var l12 = this.m[11];
  5487. var l13 = this.m[12];
  5488. var l14 = this.m[13];
  5489. var l15 = this.m[14];
  5490. var l16 = this.m[15];
  5491. var l17 = (l11 * l16) - (l12 * l15);
  5492. var l18 = (l10 * l16) - (l12 * l14);
  5493. var l19 = (l10 * l15) - (l11 * l14);
  5494. var l20 = (l9 * l16) - (l12 * l13);
  5495. var l21 = (l9 * l15) - (l11 * l13);
  5496. var l22 = (l9 * l14) - (l10 * l13);
  5497. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5498. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5499. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5500. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5501. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5502. var l28 = (l7 * l16) - (l8 * l15);
  5503. var l29 = (l6 * l16) - (l8 * l14);
  5504. var l30 = (l6 * l15) - (l7 * l14);
  5505. var l31 = (l5 * l16) - (l8 * l13);
  5506. var l32 = (l5 * l15) - (l7 * l13);
  5507. var l33 = (l5 * l14) - (l6 * l13);
  5508. var l34 = (l7 * l12) - (l8 * l11);
  5509. var l35 = (l6 * l12) - (l8 * l10);
  5510. var l36 = (l6 * l11) - (l7 * l10);
  5511. var l37 = (l5 * l12) - (l8 * l9);
  5512. var l38 = (l5 * l11) - (l7 * l9);
  5513. var l39 = (l5 * l10) - (l6 * l9);
  5514. other.m[0] = l23 * l27;
  5515. other.m[4] = l24 * l27;
  5516. other.m[8] = l25 * l27;
  5517. other.m[12] = l26 * l27;
  5518. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5519. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5520. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5521. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5522. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5523. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5524. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5525. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5526. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5527. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5528. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5529. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5530. other._markAsUpdated();
  5531. return this;
  5532. };
  5533. /**
  5534. * Inserts the translation vector (using 3 floats) in the current matrix
  5535. * @param x defines the 1st component of the translation
  5536. * @param y defines the 2nd component of the translation
  5537. * @param z defines the 3rd component of the translation
  5538. * @returns the current updated matrix
  5539. */
  5540. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5541. this.m[12] = x;
  5542. this.m[13] = y;
  5543. this.m[14] = z;
  5544. this._markAsUpdated();
  5545. return this;
  5546. };
  5547. /**
  5548. * Inserts the translation vector in the current matrix
  5549. * @param vector3 defines the translation to insert
  5550. * @returns the current updated matrix
  5551. */
  5552. Matrix.prototype.setTranslation = function (vector3) {
  5553. this.m[12] = vector3.x;
  5554. this.m[13] = vector3.y;
  5555. this.m[14] = vector3.z;
  5556. this._markAsUpdated();
  5557. return this;
  5558. };
  5559. /**
  5560. * Gets the translation value of the current matrix
  5561. * @returns a new Vector3 as the extracted translation from the matrix
  5562. */
  5563. Matrix.prototype.getTranslation = function () {
  5564. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5565. };
  5566. /**
  5567. * Fill a Vector3 with the extracted translation from the matrix
  5568. * @param result defines the Vector3 where to store the translation
  5569. * @returns the current matrix
  5570. */
  5571. Matrix.prototype.getTranslationToRef = function (result) {
  5572. result.x = this.m[12];
  5573. result.y = this.m[13];
  5574. result.z = this.m[14];
  5575. return this;
  5576. };
  5577. /**
  5578. * Remove rotation and scaling part from the matrix
  5579. * @returns the updated matrix
  5580. */
  5581. Matrix.prototype.removeRotationAndScaling = function () {
  5582. this.setRowFromFloats(0, 1, 0, 0, 0);
  5583. this.setRowFromFloats(1, 0, 1, 0, 0);
  5584. this.setRowFromFloats(2, 0, 0, 1, 0);
  5585. return this;
  5586. };
  5587. /**
  5588. * Multiply two matrices
  5589. * @param other defines the second operand
  5590. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5591. */
  5592. Matrix.prototype.multiply = function (other) {
  5593. var result = new Matrix();
  5594. this.multiplyToRef(other, result);
  5595. return result;
  5596. };
  5597. /**
  5598. * Copy the current matrix from the given one
  5599. * @param other defines the source matrix
  5600. * @returns the current updated matrix
  5601. */
  5602. Matrix.prototype.copyFrom = function (other) {
  5603. for (var index = 0; index < 16; index++) {
  5604. this.m[index] = other.m[index];
  5605. }
  5606. this._markAsUpdated();
  5607. return this;
  5608. };
  5609. /**
  5610. * Populates the given array from the starting index with the current matrix values
  5611. * @param array defines the target array
  5612. * @param offset defines the offset in the target array where to start storing values
  5613. * @returns the current matrix
  5614. */
  5615. Matrix.prototype.copyToArray = function (array, offset) {
  5616. if (offset === void 0) { offset = 0; }
  5617. for (var index = 0; index < 16; index++) {
  5618. array[offset + index] = this.m[index];
  5619. }
  5620. return this;
  5621. };
  5622. /**
  5623. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5624. * @param other defines the second operand
  5625. * @param result defines the matrix where to store the multiplication
  5626. * @returns the current matrix
  5627. */
  5628. Matrix.prototype.multiplyToRef = function (other, result) {
  5629. this.multiplyToArray(other, result.m, 0);
  5630. result._markAsUpdated();
  5631. return this;
  5632. };
  5633. /**
  5634. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5635. * @param other defines the second operand
  5636. * @param result defines the array where to store the multiplication
  5637. * @param offset defines the offset in the target array where to start storing values
  5638. * @returns the current matrix
  5639. */
  5640. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5641. var tm0 = this.m[0];
  5642. var tm1 = this.m[1];
  5643. var tm2 = this.m[2];
  5644. var tm3 = this.m[3];
  5645. var tm4 = this.m[4];
  5646. var tm5 = this.m[5];
  5647. var tm6 = this.m[6];
  5648. var tm7 = this.m[7];
  5649. var tm8 = this.m[8];
  5650. var tm9 = this.m[9];
  5651. var tm10 = this.m[10];
  5652. var tm11 = this.m[11];
  5653. var tm12 = this.m[12];
  5654. var tm13 = this.m[13];
  5655. var tm14 = this.m[14];
  5656. var tm15 = this.m[15];
  5657. var om0 = other.m[0];
  5658. var om1 = other.m[1];
  5659. var om2 = other.m[2];
  5660. var om3 = other.m[3];
  5661. var om4 = other.m[4];
  5662. var om5 = other.m[5];
  5663. var om6 = other.m[6];
  5664. var om7 = other.m[7];
  5665. var om8 = other.m[8];
  5666. var om9 = other.m[9];
  5667. var om10 = other.m[10];
  5668. var om11 = other.m[11];
  5669. var om12 = other.m[12];
  5670. var om13 = other.m[13];
  5671. var om14 = other.m[14];
  5672. var om15 = other.m[15];
  5673. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5674. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5675. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5676. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5677. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5678. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5679. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5680. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5681. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5682. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5683. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5684. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5685. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5686. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5687. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5688. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5689. return this;
  5690. };
  5691. /**
  5692. * Check equality between this matrix and a second one
  5693. * @param value defines the second matrix to compare
  5694. * @returns true is the current matrix and the given one values are strictly equal
  5695. */
  5696. Matrix.prototype.equals = function (value) {
  5697. return value &&
  5698. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5699. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5700. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5701. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5702. };
  5703. /**
  5704. * Clone the current matrix
  5705. * @returns a new matrix from the current matrix
  5706. */
  5707. Matrix.prototype.clone = function () {
  5708. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  5709. };
  5710. /**
  5711. * Returns the name of the current matrix class
  5712. * @returns the string "Matrix"
  5713. */
  5714. Matrix.prototype.getClassName = function () {
  5715. return "Matrix";
  5716. };
  5717. /**
  5718. * Gets the hash code of the current matrix
  5719. * @returns the hash code
  5720. */
  5721. Matrix.prototype.getHashCode = function () {
  5722. var hash = this.m[0] || 0;
  5723. for (var i = 1; i < 16; i++) {
  5724. hash = (hash * 397) ^ (this.m[i] || 0);
  5725. }
  5726. return hash;
  5727. };
  5728. /**
  5729. * Decomposes the current Matrix into a translation, rotation and scaling components
  5730. * @param scale defines the scale vector3 given as a reference to update
  5731. * @param rotation defines the rotation quaternion given as a reference to update
  5732. * @param translation defines the translation vector3 given as a reference to update
  5733. * @returns true if operation was successful
  5734. */
  5735. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5736. if (translation) {
  5737. translation.x = this.m[12];
  5738. translation.y = this.m[13];
  5739. translation.z = this.m[14];
  5740. }
  5741. scale = scale || MathTmp.Vector3[0];
  5742. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5743. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5744. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5745. if (this.determinant() <= 0) {
  5746. scale.y *= -1;
  5747. }
  5748. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5749. if (rotation) {
  5750. rotation.x = 0;
  5751. rotation.y = 0;
  5752. rotation.z = 0;
  5753. rotation.w = 1;
  5754. }
  5755. return false;
  5756. }
  5757. if (rotation) {
  5758. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  5759. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5760. }
  5761. return true;
  5762. };
  5763. /**
  5764. * Gets specific row of the matrix
  5765. * @param index defines the number of the row to get
  5766. * @returns the index-th row of the current matrix as a new Vector4
  5767. */
  5768. Matrix.prototype.getRow = function (index) {
  5769. if (index < 0 || index > 3) {
  5770. return null;
  5771. }
  5772. var i = index * 4;
  5773. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5774. };
  5775. /**
  5776. * Sets the index-th row of the current matrix to the vector4 values
  5777. * @param index defines the number of the row to set
  5778. * @param row defines the target vector4
  5779. * @returns the updated current matrix
  5780. */
  5781. Matrix.prototype.setRow = function (index, row) {
  5782. if (index < 0 || index > 3) {
  5783. return this;
  5784. }
  5785. var i = index * 4;
  5786. this.m[i + 0] = row.x;
  5787. this.m[i + 1] = row.y;
  5788. this.m[i + 2] = row.z;
  5789. this.m[i + 3] = row.w;
  5790. this._markAsUpdated();
  5791. return this;
  5792. };
  5793. /**
  5794. * Compute the transpose of the matrix
  5795. * @returns the new transposed matrix
  5796. */
  5797. Matrix.prototype.transpose = function () {
  5798. return Matrix.Transpose(this);
  5799. };
  5800. /**
  5801. * Compute the transpose of the matrix and store it in a given matrix
  5802. * @param result defines the target matrix
  5803. * @returns the current matrix
  5804. */
  5805. Matrix.prototype.transposeToRef = function (result) {
  5806. Matrix.TransposeToRef(this, result);
  5807. return this;
  5808. };
  5809. /**
  5810. * Sets the index-th row of the current matrix with the given 4 x float values
  5811. * @param index defines the row index
  5812. * @param x defines the x component to set
  5813. * @param y defines the y component to set
  5814. * @param z defines the z component to set
  5815. * @param w defines the w component to set
  5816. * @returns the updated current matrix
  5817. */
  5818. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5819. if (index < 0 || index > 3) {
  5820. return this;
  5821. }
  5822. var i = index * 4;
  5823. this.m[i + 0] = x;
  5824. this.m[i + 1] = y;
  5825. this.m[i + 2] = z;
  5826. this.m[i + 3] = w;
  5827. this._markAsUpdated();
  5828. return this;
  5829. };
  5830. /**
  5831. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5832. * @param scale defines the scale factor
  5833. * @returns a new matrix
  5834. */
  5835. Matrix.prototype.scale = function (scale) {
  5836. var result = new Matrix();
  5837. this.scaleToRef(scale, result);
  5838. return result;
  5839. };
  5840. /**
  5841. * Scale the current matrix values by a factor to a given result matrix
  5842. * @param scale defines the scale factor
  5843. * @param result defines the matrix to store the result
  5844. * @returns the current matrix
  5845. */
  5846. Matrix.prototype.scaleToRef = function (scale, result) {
  5847. for (var index = 0; index < 16; index++) {
  5848. result.m[index] = this.m[index] * scale;
  5849. }
  5850. result._markAsUpdated();
  5851. return this;
  5852. };
  5853. /**
  5854. * Scale the current matrix values by a factor and add the result to a given matrix
  5855. * @param scale defines the scale factor
  5856. * @param result defines the Matrix to store the result
  5857. * @returns the current matrix
  5858. */
  5859. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5860. for (var index = 0; index < 16; index++) {
  5861. result.m[index] += this.m[index] * scale;
  5862. }
  5863. result._markAsUpdated();
  5864. return this;
  5865. };
  5866. /**
  5867. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5868. * @param ref matrix to store the result
  5869. */
  5870. Matrix.prototype.toNormalMatrix = function (ref) {
  5871. this.invertToRef(ref);
  5872. ref.transpose();
  5873. var m = ref.m;
  5874. Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref);
  5875. };
  5876. /**
  5877. * Gets only rotation part of the current matrix
  5878. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5879. */
  5880. Matrix.prototype.getRotationMatrix = function () {
  5881. var result = Matrix.Identity();
  5882. this.getRotationMatrixToRef(result);
  5883. return result;
  5884. };
  5885. /**
  5886. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5887. * @param result defines the target matrix to store data to
  5888. * @returns the current matrix
  5889. */
  5890. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5891. var m = this.m;
  5892. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5893. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5894. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5895. if (this.determinant() <= 0) {
  5896. sy *= -1;
  5897. }
  5898. if (sx === 0 || sy === 0 || sz === 0) {
  5899. Matrix.IdentityToRef(result);
  5900. }
  5901. else {
  5902. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  5903. }
  5904. return this;
  5905. };
  5906. // Statics
  5907. /**
  5908. * Creates a matrix from an array
  5909. * @param array defines the source array
  5910. * @param offset defines an offset in the source array
  5911. * @returns a new Matrix set from the starting index of the given array
  5912. */
  5913. Matrix.FromArray = function (array, offset) {
  5914. var result = new Matrix();
  5915. if (!offset) {
  5916. offset = 0;
  5917. }
  5918. Matrix.FromArrayToRef(array, offset, result);
  5919. return result;
  5920. };
  5921. /**
  5922. * Copy the content of an array into a given matrix
  5923. * @param array defines the source array
  5924. * @param offset defines an offset in the source array
  5925. * @param result defines the target matrix
  5926. */
  5927. Matrix.FromArrayToRef = function (array, offset, result) {
  5928. for (var index = 0; index < 16; index++) {
  5929. result.m[index] = array[index + offset];
  5930. }
  5931. result._markAsUpdated();
  5932. };
  5933. /**
  5934. * Stores an array into a matrix after having multiplied each component by a given factor
  5935. * @param array defines the source array
  5936. * @param offset defines the offset in the source array
  5937. * @param scale defines the scaling factor
  5938. * @param result defines the target matrix
  5939. */
  5940. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5941. for (var index = 0; index < 16; index++) {
  5942. result.m[index] = array[index + offset] * scale;
  5943. }
  5944. result._markAsUpdated();
  5945. };
  5946. /**
  5947. * Stores a list of values (16) inside a given matrix
  5948. * @param initialM11 defines 1st value of 1st row
  5949. * @param initialM12 defines 2nd value of 1st row
  5950. * @param initialM13 defines 3rd value of 1st row
  5951. * @param initialM14 defines 4th value of 1st row
  5952. * @param initialM21 defines 1st value of 2nd row
  5953. * @param initialM22 defines 2nd value of 2nd row
  5954. * @param initialM23 defines 3rd value of 2nd row
  5955. * @param initialM24 defines 4th value of 2nd row
  5956. * @param initialM31 defines 1st value of 3rd row
  5957. * @param initialM32 defines 2nd value of 3rd row
  5958. * @param initialM33 defines 3rd value of 3rd row
  5959. * @param initialM34 defines 4th value of 3rd row
  5960. * @param initialM41 defines 1st value of 4th row
  5961. * @param initialM42 defines 2nd value of 4th row
  5962. * @param initialM43 defines 3rd value of 4th row
  5963. * @param initialM44 defines 4th value of 4th row
  5964. * @param result defines the target matrix
  5965. */
  5966. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5967. result.m[0] = initialM11;
  5968. result.m[1] = initialM12;
  5969. result.m[2] = initialM13;
  5970. result.m[3] = initialM14;
  5971. result.m[4] = initialM21;
  5972. result.m[5] = initialM22;
  5973. result.m[6] = initialM23;
  5974. result.m[7] = initialM24;
  5975. result.m[8] = initialM31;
  5976. result.m[9] = initialM32;
  5977. result.m[10] = initialM33;
  5978. result.m[11] = initialM34;
  5979. result.m[12] = initialM41;
  5980. result.m[13] = initialM42;
  5981. result.m[14] = initialM43;
  5982. result.m[15] = initialM44;
  5983. result._markAsUpdated();
  5984. };
  5985. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5986. /**
  5987. * Gets an identity matrix that must not be updated
  5988. */
  5989. get: function () {
  5990. return Matrix._identityReadOnly;
  5991. },
  5992. enumerable: true,
  5993. configurable: true
  5994. });
  5995. /**
  5996. * Creates new matrix from a list of values (16)
  5997. * @param initialM11 defines 1st value of 1st row
  5998. * @param initialM12 defines 2nd value of 1st row
  5999. * @param initialM13 defines 3rd value of 1st row
  6000. * @param initialM14 defines 4th value of 1st row
  6001. * @param initialM21 defines 1st value of 2nd row
  6002. * @param initialM22 defines 2nd value of 2nd row
  6003. * @param initialM23 defines 3rd value of 2nd row
  6004. * @param initialM24 defines 4th value of 2nd row
  6005. * @param initialM31 defines 1st value of 3rd row
  6006. * @param initialM32 defines 2nd value of 3rd row
  6007. * @param initialM33 defines 3rd value of 3rd row
  6008. * @param initialM34 defines 4th value of 3rd row
  6009. * @param initialM41 defines 1st value of 4th row
  6010. * @param initialM42 defines 2nd value of 4th row
  6011. * @param initialM43 defines 3rd value of 4th row
  6012. * @param initialM44 defines 4th value of 4th row
  6013. * @returns the new matrix
  6014. */
  6015. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6016. var result = new Matrix();
  6017. result.m[0] = initialM11;
  6018. result.m[1] = initialM12;
  6019. result.m[2] = initialM13;
  6020. result.m[3] = initialM14;
  6021. result.m[4] = initialM21;
  6022. result.m[5] = initialM22;
  6023. result.m[6] = initialM23;
  6024. result.m[7] = initialM24;
  6025. result.m[8] = initialM31;
  6026. result.m[9] = initialM32;
  6027. result.m[10] = initialM33;
  6028. result.m[11] = initialM34;
  6029. result.m[12] = initialM41;
  6030. result.m[13] = initialM42;
  6031. result.m[14] = initialM43;
  6032. result.m[15] = initialM44;
  6033. return result;
  6034. };
  6035. /**
  6036. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6037. * @param scale defines the scale vector3
  6038. * @param rotation defines the rotation quaternion
  6039. * @param translation defines the translation vector3
  6040. * @returns a new matrix
  6041. */
  6042. Matrix.Compose = function (scale, rotation, translation) {
  6043. var result = Matrix.Identity();
  6044. Matrix.ComposeToRef(scale, rotation, translation, result);
  6045. return result;
  6046. };
  6047. /**
  6048. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6049. * @param scale defines the scale vector3
  6050. * @param rotation defines the rotation quaternion
  6051. * @param translation defines the translation vector3
  6052. * @param result defines the target matrix
  6053. */
  6054. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6055. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6056. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6057. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6058. result.setTranslation(translation);
  6059. };
  6060. /**
  6061. * Creates a new identity matrix
  6062. * @returns a new identity matrix
  6063. */
  6064. Matrix.Identity = function () {
  6065. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  6066. };
  6067. /**
  6068. * Creates a new identity matrix and stores the result in a given matrix
  6069. * @param result defines the target matrix
  6070. */
  6071. Matrix.IdentityToRef = function (result) {
  6072. 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);
  6073. };
  6074. /**
  6075. * Creates a new zero matrix
  6076. * @returns a new zero matrix
  6077. */
  6078. Matrix.Zero = function () {
  6079. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  6080. };
  6081. /**
  6082. * Creates a new rotation matrix for "angle" radians around the X axis
  6083. * @param angle defines the angle (in radians) to use
  6084. * @return the new matrix
  6085. */
  6086. Matrix.RotationX = function (angle) {
  6087. var result = new Matrix();
  6088. Matrix.RotationXToRef(angle, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * Creates a new matrix as the invert of a given matrix
  6093. * @param source defines the source matrix
  6094. * @returns the new matrix
  6095. */
  6096. Matrix.Invert = function (source) {
  6097. var result = new Matrix();
  6098. source.invertToRef(result);
  6099. return result;
  6100. };
  6101. /**
  6102. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6103. * @param angle defines the angle (in radians) to use
  6104. * @param result defines the target matrix
  6105. */
  6106. Matrix.RotationXToRef = function (angle, result) {
  6107. var s = Math.sin(angle);
  6108. var c = Math.cos(angle);
  6109. result.m[0] = 1.0;
  6110. result.m[15] = 1.0;
  6111. result.m[5] = c;
  6112. result.m[10] = c;
  6113. result.m[9] = -s;
  6114. result.m[6] = s;
  6115. result.m[1] = 0.0;
  6116. result.m[2] = 0.0;
  6117. result.m[3] = 0.0;
  6118. result.m[4] = 0.0;
  6119. result.m[7] = 0.0;
  6120. result.m[8] = 0.0;
  6121. result.m[11] = 0.0;
  6122. result.m[12] = 0.0;
  6123. result.m[13] = 0.0;
  6124. result.m[14] = 0.0;
  6125. result._markAsUpdated();
  6126. };
  6127. /**
  6128. * Creates a new rotation matrix for "angle" radians around the Y axis
  6129. * @param angle defines the angle (in radians) to use
  6130. * @return the new matrix
  6131. */
  6132. Matrix.RotationY = function (angle) {
  6133. var result = new Matrix();
  6134. Matrix.RotationYToRef(angle, result);
  6135. return result;
  6136. };
  6137. /**
  6138. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6139. * @param angle defines the angle (in radians) to use
  6140. * @param result defines the target matrix
  6141. */
  6142. Matrix.RotationYToRef = function (angle, result) {
  6143. var s = Math.sin(angle);
  6144. var c = Math.cos(angle);
  6145. result.m[5] = 1.0;
  6146. result.m[15] = 1.0;
  6147. result.m[0] = c;
  6148. result.m[2] = -s;
  6149. result.m[8] = s;
  6150. result.m[10] = c;
  6151. result.m[1] = 0.0;
  6152. result.m[3] = 0.0;
  6153. result.m[4] = 0.0;
  6154. result.m[6] = 0.0;
  6155. result.m[7] = 0.0;
  6156. result.m[9] = 0.0;
  6157. result.m[11] = 0.0;
  6158. result.m[12] = 0.0;
  6159. result.m[13] = 0.0;
  6160. result.m[14] = 0.0;
  6161. result._markAsUpdated();
  6162. };
  6163. /**
  6164. * Creates a new rotation matrix for "angle" radians around the Z axis
  6165. * @param angle defines the angle (in radians) to use
  6166. * @return the new matrix
  6167. */
  6168. Matrix.RotationZ = function (angle) {
  6169. var result = new Matrix();
  6170. Matrix.RotationZToRef(angle, result);
  6171. return result;
  6172. };
  6173. /**
  6174. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6175. * @param angle defines the angle (in radians) to use
  6176. * @param result defines the target matrix
  6177. */
  6178. Matrix.RotationZToRef = function (angle, result) {
  6179. var s = Math.sin(angle);
  6180. var c = Math.cos(angle);
  6181. result.m[10] = 1.0;
  6182. result.m[15] = 1.0;
  6183. result.m[0] = c;
  6184. result.m[1] = s;
  6185. result.m[4] = -s;
  6186. result.m[5] = c;
  6187. result.m[2] = 0.0;
  6188. result.m[3] = 0.0;
  6189. result.m[6] = 0.0;
  6190. result.m[7] = 0.0;
  6191. result.m[8] = 0.0;
  6192. result.m[9] = 0.0;
  6193. result.m[11] = 0.0;
  6194. result.m[12] = 0.0;
  6195. result.m[13] = 0.0;
  6196. result.m[14] = 0.0;
  6197. result._markAsUpdated();
  6198. };
  6199. /**
  6200. * Creates a new rotation matrix for "angle" radians around the given axis
  6201. * @param axis defines the axis to use
  6202. * @param angle defines the angle (in radians) to use
  6203. * @return the new matrix
  6204. */
  6205. Matrix.RotationAxis = function (axis, angle) {
  6206. var result = Matrix.Zero();
  6207. Matrix.RotationAxisToRef(axis, angle, result);
  6208. return result;
  6209. };
  6210. /**
  6211. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6212. * @param axis defines the axis to use
  6213. * @param angle defines the angle (in radians) to use
  6214. * @param result defines the target matrix
  6215. */
  6216. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6217. var s = Math.sin(-angle);
  6218. var c = Math.cos(-angle);
  6219. var c1 = 1 - c;
  6220. axis.normalize();
  6221. result.m[0] = (axis.x * axis.x) * c1 + c;
  6222. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6223. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6224. result.m[3] = 0.0;
  6225. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6226. result.m[5] = (axis.y * axis.y) * c1 + c;
  6227. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6228. result.m[7] = 0.0;
  6229. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6230. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6231. result.m[10] = (axis.z * axis.z) * c1 + c;
  6232. result.m[11] = 0.0;
  6233. result.m[15] = 1.0;
  6234. result._markAsUpdated();
  6235. };
  6236. /**
  6237. * Creates a rotation matrix
  6238. * @param yaw defines the yaw angle in radians (Y axis)
  6239. * @param pitch defines the pitch angle in radians (X axis)
  6240. * @param roll defines the roll angle in radians (X axis)
  6241. * @returns the new rotation matrix
  6242. */
  6243. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6244. var result = new Matrix();
  6245. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6246. return result;
  6247. };
  6248. /**
  6249. * Creates a rotation matrix and stores it in a given matrix
  6250. * @param yaw defines the yaw angle in radians (Y axis)
  6251. * @param pitch defines the pitch angle in radians (X axis)
  6252. * @param roll defines the roll angle in radians (X axis)
  6253. * @param result defines the target matrix
  6254. */
  6255. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6256. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6257. this._tempQuaternion.toRotationMatrix(result);
  6258. };
  6259. /**
  6260. * Creates a scaling matrix
  6261. * @param x defines the scale factor on X axis
  6262. * @param y defines the scale factor on Y axis
  6263. * @param z defines the scale factor on Z axis
  6264. * @returns the new matrix
  6265. */
  6266. Matrix.Scaling = function (x, y, z) {
  6267. var result = Matrix.Zero();
  6268. Matrix.ScalingToRef(x, y, z, result);
  6269. return result;
  6270. };
  6271. /**
  6272. * Creates a scaling matrix and stores it in a given matrix
  6273. * @param x defines the scale factor on X axis
  6274. * @param y defines the scale factor on Y axis
  6275. * @param z defines the scale factor on Z axis
  6276. * @param result defines the target matrix
  6277. */
  6278. Matrix.ScalingToRef = function (x, y, z, result) {
  6279. result.m[0] = x;
  6280. result.m[1] = 0.0;
  6281. result.m[2] = 0.0;
  6282. result.m[3] = 0.0;
  6283. result.m[4] = 0.0;
  6284. result.m[5] = y;
  6285. result.m[6] = 0.0;
  6286. result.m[7] = 0.0;
  6287. result.m[8] = 0.0;
  6288. result.m[9] = 0.0;
  6289. result.m[10] = z;
  6290. result.m[11] = 0.0;
  6291. result.m[12] = 0.0;
  6292. result.m[13] = 0.0;
  6293. result.m[14] = 0.0;
  6294. result.m[15] = 1.0;
  6295. result._markAsUpdated();
  6296. };
  6297. /**
  6298. * Creates a translation matrix
  6299. * @param x defines the translation on X axis
  6300. * @param y defines the translation on Y axis
  6301. * @param z defines the translationon Z axis
  6302. * @returns the new matrix
  6303. */
  6304. Matrix.Translation = function (x, y, z) {
  6305. var result = Matrix.Identity();
  6306. Matrix.TranslationToRef(x, y, z, result);
  6307. return result;
  6308. };
  6309. /**
  6310. * Creates a translation matrix and stores it in a given matrix
  6311. * @param x defines the translation on X axis
  6312. * @param y defines the translation on Y axis
  6313. * @param z defines the translationon Z axis
  6314. * @param result defines the target matrix
  6315. */
  6316. Matrix.TranslationToRef = function (x, y, z, result) {
  6317. 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);
  6318. };
  6319. /**
  6320. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6321. * @param startValue defines the start value
  6322. * @param endValue defines the end value
  6323. * @param gradient defines the gradient factor
  6324. * @returns the new matrix
  6325. */
  6326. Matrix.Lerp = function (startValue, endValue, gradient) {
  6327. var result = Matrix.Zero();
  6328. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6329. return result;
  6330. };
  6331. /**
  6332. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6333. * @param startValue defines the start value
  6334. * @param endValue defines the end value
  6335. * @param gradient defines the gradient factor
  6336. * @param result defines the Matrix object where to store data
  6337. */
  6338. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6339. for (var index = 0; index < 16; index++) {
  6340. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6341. }
  6342. result._markAsUpdated();
  6343. };
  6344. /**
  6345. * Builds a new matrix whose values are computed by:
  6346. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6347. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6348. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6349. * @param startValue defines the first matrix
  6350. * @param endValue defines the second matrix
  6351. * @param gradient defines the gradient between the two matrices
  6352. * @returns the new matrix
  6353. */
  6354. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6355. var result = Matrix.Zero();
  6356. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6357. return result;
  6358. };
  6359. /**
  6360. * Update a matrix to values which are computed by:
  6361. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6362. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6363. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6364. * @param startValue defines the first matrix
  6365. * @param endValue defines the second matrix
  6366. * @param gradient defines the gradient between the two matrices
  6367. * @param result defines the target matrix
  6368. */
  6369. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6370. var startScale = MathTmp.Vector3[0];
  6371. var startRotation = MathTmp.Quaternion[0];
  6372. var startTranslation = MathTmp.Vector3[1];
  6373. startValue.decompose(startScale, startRotation, startTranslation);
  6374. var endScale = MathTmp.Vector3[2];
  6375. var endRotation = MathTmp.Quaternion[1];
  6376. var endTranslation = MathTmp.Vector3[3];
  6377. endValue.decompose(endScale, endRotation, endTranslation);
  6378. var resultScale = MathTmp.Vector3[4];
  6379. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6380. var resultRotation = MathTmp.Quaternion[2];
  6381. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6382. var resultTranslation = MathTmp.Vector3[5];
  6383. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6384. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6385. };
  6386. /**
  6387. * 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"
  6388. * This function works in left handed mode
  6389. * @param eye defines the final position of the entity
  6390. * @param target defines where the entity should look at
  6391. * @param up defines the up vector for the entity
  6392. * @returns the new matrix
  6393. */
  6394. Matrix.LookAtLH = function (eye, target, up) {
  6395. var result = Matrix.Zero();
  6396. Matrix.LookAtLHToRef(eye, target, up, result);
  6397. return result;
  6398. };
  6399. /**
  6400. * 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".
  6401. * This function works in left handed mode
  6402. * @param eye defines the final position of the entity
  6403. * @param target defines where the entity should look at
  6404. * @param up defines the up vector for the entity
  6405. * @param result defines the target matrix
  6406. */
  6407. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6408. // Z axis
  6409. target.subtractToRef(eye, this._zAxis);
  6410. this._zAxis.normalize();
  6411. // X axis
  6412. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6413. if (this._xAxis.lengthSquared() === 0) {
  6414. this._xAxis.x = 1.0;
  6415. }
  6416. else {
  6417. this._xAxis.normalize();
  6418. }
  6419. // Y axis
  6420. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6421. this._yAxis.normalize();
  6422. // Eye angles
  6423. var ex = -Vector3.Dot(this._xAxis, eye);
  6424. var ey = -Vector3.Dot(this._yAxis, eye);
  6425. var ez = -Vector3.Dot(this._zAxis, eye);
  6426. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6427. };
  6428. /**
  6429. * 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"
  6430. * This function works in right handed mode
  6431. * @param eye defines the final position of the entity
  6432. * @param target defines where the entity should look at
  6433. * @param up defines the up vector for the entity
  6434. * @returns the new matrix
  6435. */
  6436. Matrix.LookAtRH = function (eye, target, up) {
  6437. var result = Matrix.Zero();
  6438. Matrix.LookAtRHToRef(eye, target, up, result);
  6439. return result;
  6440. };
  6441. /**
  6442. * 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".
  6443. * This function works in right handed mode
  6444. * @param eye defines the final position of the entity
  6445. * @param target defines where the entity should look at
  6446. * @param up defines the up vector for the entity
  6447. * @param result defines the target matrix
  6448. */
  6449. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6450. // Z axis
  6451. eye.subtractToRef(target, this._zAxis);
  6452. this._zAxis.normalize();
  6453. // X axis
  6454. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6455. if (this._xAxis.lengthSquared() === 0) {
  6456. this._xAxis.x = 1.0;
  6457. }
  6458. else {
  6459. this._xAxis.normalize();
  6460. }
  6461. // Y axis
  6462. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6463. this._yAxis.normalize();
  6464. // Eye angles
  6465. var ex = -Vector3.Dot(this._xAxis, eye);
  6466. var ey = -Vector3.Dot(this._yAxis, eye);
  6467. var ez = -Vector3.Dot(this._zAxis, eye);
  6468. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  6469. };
  6470. /**
  6471. * Create a left-handed orthographic projection matrix
  6472. * @param width defines the viewport width
  6473. * @param height defines the viewport height
  6474. * @param znear defines the near clip plane
  6475. * @param zfar defines the far clip plane
  6476. * @returns a new matrix as a left-handed orthographic projection matrix
  6477. */
  6478. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6479. var matrix = Matrix.Zero();
  6480. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6481. return matrix;
  6482. };
  6483. /**
  6484. * Store a left-handed orthographic projection to a given matrix
  6485. * @param width defines the viewport width
  6486. * @param height defines the viewport height
  6487. * @param znear defines the near clip plane
  6488. * @param zfar defines the far clip plane
  6489. * @param result defines the target matrix
  6490. */
  6491. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6492. var n = znear;
  6493. var f = zfar;
  6494. var a = 2.0 / width;
  6495. var b = 2.0 / height;
  6496. var c = 2.0 / (f - n);
  6497. var d = -(f + n) / (f - n);
  6498. 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);
  6499. };
  6500. /**
  6501. * Create a left-handed orthographic projection matrix
  6502. * @param left defines the viewport left coordinate
  6503. * @param right defines the viewport right coordinate
  6504. * @param bottom defines the viewport bottom coordinate
  6505. * @param top defines the viewport top coordinate
  6506. * @param znear defines the near clip plane
  6507. * @param zfar defines the far clip plane
  6508. * @returns a new matrix as a left-handed orthographic projection matrix
  6509. */
  6510. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6511. var matrix = Matrix.Zero();
  6512. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6513. return matrix;
  6514. };
  6515. /**
  6516. * Stores a left-handed orthographic projection into a given matrix
  6517. * @param left defines the viewport left coordinate
  6518. * @param right defines the viewport right coordinate
  6519. * @param bottom defines the viewport bottom coordinate
  6520. * @param top defines the viewport top coordinate
  6521. * @param znear defines the near clip plane
  6522. * @param zfar defines the far clip plane
  6523. * @param result defines the target matrix
  6524. */
  6525. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6526. var n = znear;
  6527. var f = zfar;
  6528. var a = 2.0 / (right - left);
  6529. var b = 2.0 / (top - bottom);
  6530. var c = 2.0 / (f - n);
  6531. var d = -(f + n) / (f - n);
  6532. var i0 = (left + right) / (left - right);
  6533. var i1 = (top + bottom) / (bottom - top);
  6534. 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);
  6535. };
  6536. /**
  6537. * Creates a right-handed orthographic projection matrix
  6538. * @param left defines the viewport left coordinate
  6539. * @param right defines the viewport right coordinate
  6540. * @param bottom defines the viewport bottom coordinate
  6541. * @param top defines the viewport top coordinate
  6542. * @param znear defines the near clip plane
  6543. * @param zfar defines the far clip plane
  6544. * @returns a new matrix as a right-handed orthographic projection matrix
  6545. */
  6546. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6547. var matrix = Matrix.Zero();
  6548. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6549. return matrix;
  6550. };
  6551. /**
  6552. * Stores a right-handed orthographic projection into a given matrix
  6553. * @param left defines the viewport left coordinate
  6554. * @param right defines the viewport right coordinate
  6555. * @param bottom defines the viewport bottom coordinate
  6556. * @param top defines the viewport top coordinate
  6557. * @param znear defines the near clip plane
  6558. * @param zfar defines the far clip plane
  6559. * @param result defines the target matrix
  6560. */
  6561. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6562. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6563. result.m[10] *= -1.0;
  6564. };
  6565. /**
  6566. * Creates a left-handed perspective projection matrix
  6567. * @param width defines the viewport width
  6568. * @param height defines the viewport height
  6569. * @param znear defines the near clip plane
  6570. * @param zfar defines the far clip plane
  6571. * @returns a new matrix as a left-handed perspective projection matrix
  6572. */
  6573. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6574. var matrix = Matrix.Zero();
  6575. var n = znear;
  6576. var f = zfar;
  6577. var a = 2.0 * n / width;
  6578. var b = 2.0 * n / height;
  6579. var c = (f + n) / (f - n);
  6580. var d = -2.0 * f * n / (f - n);
  6581. 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);
  6582. return matrix;
  6583. };
  6584. /**
  6585. * Creates a left-handed perspective projection matrix
  6586. * @param fov defines the horizontal field of view
  6587. * @param aspect defines the aspect ratio
  6588. * @param znear defines the near clip plane
  6589. * @param zfar defines the far clip plane
  6590. * @returns a new matrix as a left-handed perspective projection matrix
  6591. */
  6592. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6593. var matrix = Matrix.Zero();
  6594. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6595. return matrix;
  6596. };
  6597. /**
  6598. * Stores a left-handed perspective projection into a given matrix
  6599. * @param fov defines the horizontal field of view
  6600. * @param aspect defines the aspect ratio
  6601. * @param znear defines the near clip plane
  6602. * @param zfar defines the far clip plane
  6603. * @param result defines the target matrix
  6604. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6605. */
  6606. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6607. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6608. var n = znear;
  6609. var f = zfar;
  6610. var t = 1.0 / (Math.tan(fov * 0.5));
  6611. var a = isVerticalFovFixed ? (t / aspect) : t;
  6612. var b = isVerticalFovFixed ? t : (t * aspect);
  6613. var c = (f + n) / (f - n);
  6614. var d = -2.0 * f * n / (f - n);
  6615. 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);
  6616. };
  6617. /**
  6618. * Creates a right-handed perspective projection matrix
  6619. * @param fov defines the horizontal field of view
  6620. * @param aspect defines the aspect ratio
  6621. * @param znear defines the near clip plane
  6622. * @param zfar defines the far clip plane
  6623. * @returns a new matrix as a right-handed perspective projection matrix
  6624. */
  6625. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6626. var matrix = Matrix.Zero();
  6627. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6628. return matrix;
  6629. };
  6630. /**
  6631. * Stores a right-handed perspective projection into a given matrix
  6632. * @param fov defines the horizontal field of view
  6633. * @param aspect defines the aspect ratio
  6634. * @param znear defines the near clip plane
  6635. * @param zfar defines the far clip plane
  6636. * @param result defines the target matrix
  6637. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6638. */
  6639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6640. //alternatively this could be expressed as:
  6641. // m = PerspectiveFovLHToRef
  6642. // m[10] *= -1.0;
  6643. // m[11] *= -1.0;
  6644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6645. var n = znear;
  6646. var f = zfar;
  6647. var t = 1.0 / (Math.tan(fov * 0.5));
  6648. var a = isVerticalFovFixed ? (t / aspect) : t;
  6649. var b = isVerticalFovFixed ? t : (t * aspect);
  6650. var c = -(f + n) / (f - n);
  6651. var d = -2 * f * n / (f - n);
  6652. 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);
  6653. };
  6654. /**
  6655. * Stores a perspective projection for WebVR info a given matrix
  6656. * @param fov defines the field of view
  6657. * @param znear defines the near clip plane
  6658. * @param zfar defines the far clip plane
  6659. * @param result defines the target matrix
  6660. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6661. */
  6662. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6663. if (rightHanded === void 0) { rightHanded = false; }
  6664. var rightHandedFactor = rightHanded ? -1 : 1;
  6665. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6666. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6667. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6668. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6669. var xScale = 2.0 / (leftTan + rightTan);
  6670. var yScale = 2.0 / (upTan + downTan);
  6671. result.m[0] = xScale;
  6672. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6673. result.m[5] = yScale;
  6674. result.m[6] = result.m[7] = 0.0;
  6675. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6676. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6677. result.m[10] = -zfar / (znear - zfar);
  6678. result.m[11] = 1.0 * rightHandedFactor;
  6679. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6680. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6681. result._markAsUpdated();
  6682. };
  6683. /**
  6684. * Computes a complete transformation matrix
  6685. * @param viewport defines the viewport to use
  6686. * @param world defines the world matrix
  6687. * @param view defines the view matrix
  6688. * @param projection defines the projection matrix
  6689. * @param zmin defines the near clip plane
  6690. * @param zmax defines the far clip plane
  6691. * @returns the transformation matrix
  6692. */
  6693. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6694. var cw = viewport.width;
  6695. var ch = viewport.height;
  6696. var cx = viewport.x;
  6697. var cy = viewport.y;
  6698. 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);
  6699. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6700. };
  6701. /**
  6702. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6703. * @param matrix defines the matrix to use
  6704. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6705. */
  6706. Matrix.GetAsMatrix2x2 = function (matrix) {
  6707. return new Float32Array([
  6708. matrix.m[0], matrix.m[1],
  6709. matrix.m[4], matrix.m[5]
  6710. ]);
  6711. };
  6712. /**
  6713. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6714. * @param matrix defines the matrix to use
  6715. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6716. */
  6717. Matrix.GetAsMatrix3x3 = function (matrix) {
  6718. return new Float32Array([
  6719. matrix.m[0], matrix.m[1], matrix.m[2],
  6720. matrix.m[4], matrix.m[5], matrix.m[6],
  6721. matrix.m[8], matrix.m[9], matrix.m[10]
  6722. ]);
  6723. };
  6724. /**
  6725. * Compute the transpose of a given matrix
  6726. * @param matrix defines the matrix to transpose
  6727. * @returns the new matrix
  6728. */
  6729. Matrix.Transpose = function (matrix) {
  6730. var result = new Matrix();
  6731. Matrix.TransposeToRef(matrix, result);
  6732. return result;
  6733. };
  6734. /**
  6735. * Compute the transpose of a matrix and store it in a target matrix
  6736. * @param matrix defines the matrix to transpose
  6737. * @param result defines the target matrix
  6738. */
  6739. Matrix.TransposeToRef = function (matrix, result) {
  6740. result.m[0] = matrix.m[0];
  6741. result.m[1] = matrix.m[4];
  6742. result.m[2] = matrix.m[8];
  6743. result.m[3] = matrix.m[12];
  6744. result.m[4] = matrix.m[1];
  6745. result.m[5] = matrix.m[5];
  6746. result.m[6] = matrix.m[9];
  6747. result.m[7] = matrix.m[13];
  6748. result.m[8] = matrix.m[2];
  6749. result.m[9] = matrix.m[6];
  6750. result.m[10] = matrix.m[10];
  6751. result.m[11] = matrix.m[14];
  6752. result.m[12] = matrix.m[3];
  6753. result.m[13] = matrix.m[7];
  6754. result.m[14] = matrix.m[11];
  6755. result.m[15] = matrix.m[15];
  6756. };
  6757. /**
  6758. * Computes a reflection matrix from a plane
  6759. * @param plane defines the reflection plane
  6760. * @returns a new matrix
  6761. */
  6762. Matrix.Reflection = function (plane) {
  6763. var matrix = new Matrix();
  6764. Matrix.ReflectionToRef(plane, matrix);
  6765. return matrix;
  6766. };
  6767. /**
  6768. * Computes a reflection matrix from a plane
  6769. * @param plane defines the reflection plane
  6770. * @param result defines the target matrix
  6771. */
  6772. Matrix.ReflectionToRef = function (plane, result) {
  6773. plane.normalize();
  6774. var x = plane.normal.x;
  6775. var y = plane.normal.y;
  6776. var z = plane.normal.z;
  6777. var temp = -2 * x;
  6778. var temp2 = -2 * y;
  6779. var temp3 = -2 * z;
  6780. result.m[0] = (temp * x) + 1;
  6781. result.m[1] = temp2 * x;
  6782. result.m[2] = temp3 * x;
  6783. result.m[3] = 0.0;
  6784. result.m[4] = temp * y;
  6785. result.m[5] = (temp2 * y) + 1;
  6786. result.m[6] = temp3 * y;
  6787. result.m[7] = 0.0;
  6788. result.m[8] = temp * z;
  6789. result.m[9] = temp2 * z;
  6790. result.m[10] = (temp3 * z) + 1;
  6791. result.m[11] = 0.0;
  6792. result.m[12] = temp * plane.d;
  6793. result.m[13] = temp2 * plane.d;
  6794. result.m[14] = temp3 * plane.d;
  6795. result.m[15] = 1.0;
  6796. result._markAsUpdated();
  6797. };
  6798. /**
  6799. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6800. * @param xaxis defines the value of the 1st axis
  6801. * @param yaxis defines the value of the 2nd axis
  6802. * @param zaxis defines the value of the 3rd axis
  6803. * @param result defines the target matrix
  6804. */
  6805. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6806. result.m[0] = xaxis.x;
  6807. result.m[1] = xaxis.y;
  6808. result.m[2] = xaxis.z;
  6809. result.m[3] = 0.0;
  6810. result.m[4] = yaxis.x;
  6811. result.m[5] = yaxis.y;
  6812. result.m[6] = yaxis.z;
  6813. result.m[7] = 0.0;
  6814. result.m[8] = zaxis.x;
  6815. result.m[9] = zaxis.y;
  6816. result.m[10] = zaxis.z;
  6817. result.m[11] = 0.0;
  6818. result.m[12] = 0.0;
  6819. result.m[13] = 0.0;
  6820. result.m[14] = 0.0;
  6821. result.m[15] = 1.0;
  6822. result._markAsUpdated();
  6823. };
  6824. /**
  6825. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6826. * @param quat defines the quaternion to use
  6827. * @param result defines the target matrix
  6828. */
  6829. Matrix.FromQuaternionToRef = function (quat, result) {
  6830. var xx = quat.x * quat.x;
  6831. var yy = quat.y * quat.y;
  6832. var zz = quat.z * quat.z;
  6833. var xy = quat.x * quat.y;
  6834. var zw = quat.z * quat.w;
  6835. var zx = quat.z * quat.x;
  6836. var yw = quat.y * quat.w;
  6837. var yz = quat.y * quat.z;
  6838. var xw = quat.x * quat.w;
  6839. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6840. result.m[1] = 2.0 * (xy + zw);
  6841. result.m[2] = 2.0 * (zx - yw);
  6842. result.m[3] = 0.0;
  6843. result.m[4] = 2.0 * (xy - zw);
  6844. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6845. result.m[6] = 2.0 * (yz + xw);
  6846. result.m[7] = 0.0;
  6847. result.m[8] = 2.0 * (zx + yw);
  6848. result.m[9] = 2.0 * (yz - xw);
  6849. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6850. result.m[11] = 0.0;
  6851. result.m[12] = 0.0;
  6852. result.m[13] = 0.0;
  6853. result.m[14] = 0.0;
  6854. result.m[15] = 1.0;
  6855. result._markAsUpdated();
  6856. };
  6857. Matrix._tempQuaternion = new Quaternion();
  6858. Matrix._xAxis = Vector3.Zero();
  6859. Matrix._yAxis = Vector3.Zero();
  6860. Matrix._zAxis = Vector3.Zero();
  6861. Matrix._updateFlagSeed = 0;
  6862. Matrix._identityReadOnly = Matrix.Identity();
  6863. return Matrix;
  6864. }());
  6865. BABYLON.Matrix = Matrix;
  6866. /**
  6867. * Represens a plane by the equation ax + by + cz + d = 0
  6868. */
  6869. var Plane = /** @class */ (function () {
  6870. /**
  6871. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6872. * @param a a component of the plane
  6873. * @param b b component of the plane
  6874. * @param c c component of the plane
  6875. * @param d d component of the plane
  6876. */
  6877. function Plane(a, b, c, d) {
  6878. this.normal = new Vector3(a, b, c);
  6879. this.d = d;
  6880. }
  6881. /**
  6882. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6883. */
  6884. Plane.prototype.asArray = function () {
  6885. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6886. };
  6887. // Methods
  6888. /**
  6889. * @returns a new plane copied from the current Plane.
  6890. */
  6891. Plane.prototype.clone = function () {
  6892. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6893. };
  6894. /**
  6895. * @returns the string "Plane".
  6896. */
  6897. Plane.prototype.getClassName = function () {
  6898. return "Plane";
  6899. };
  6900. /**
  6901. * @returns the Plane hash code.
  6902. */
  6903. Plane.prototype.getHashCode = function () {
  6904. var hash = this.normal.getHashCode();
  6905. hash = (hash * 397) ^ (this.d || 0);
  6906. return hash;
  6907. };
  6908. /**
  6909. * Normalize the current Plane in place.
  6910. * @returns the updated Plane.
  6911. */
  6912. Plane.prototype.normalize = function () {
  6913. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6914. var magnitude = 0.0;
  6915. if (norm !== 0) {
  6916. magnitude = 1.0 / norm;
  6917. }
  6918. this.normal.x *= magnitude;
  6919. this.normal.y *= magnitude;
  6920. this.normal.z *= magnitude;
  6921. this.d *= magnitude;
  6922. return this;
  6923. };
  6924. /**
  6925. * Applies a transformation the plane and returns the result
  6926. * @param transformation the transformation matrix to be applied to the plane
  6927. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6928. */
  6929. Plane.prototype.transform = function (transformation) {
  6930. var transposedMatrix = Matrix.Transpose(transformation);
  6931. var x = this.normal.x;
  6932. var y = this.normal.y;
  6933. var z = this.normal.z;
  6934. var d = this.d;
  6935. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6936. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6937. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6938. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6939. return new Plane(normalX, normalY, normalZ, finalD);
  6940. };
  6941. /**
  6942. * Calcualtte the dot product between the point and the plane normal
  6943. * @param point point to calculate the dot product with
  6944. * @returns the dot product (float) of the point coordinates and the plane normal.
  6945. */
  6946. Plane.prototype.dotCoordinate = function (point) {
  6947. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6948. };
  6949. /**
  6950. * Updates the current Plane from the plane defined by the three given points.
  6951. * @param point1 one of the points used to contruct the plane
  6952. * @param point2 one of the points used to contruct the plane
  6953. * @param point3 one of the points used to contruct the plane
  6954. * @returns the updated Plane.
  6955. */
  6956. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6957. var x1 = point2.x - point1.x;
  6958. var y1 = point2.y - point1.y;
  6959. var z1 = point2.z - point1.z;
  6960. var x2 = point3.x - point1.x;
  6961. var y2 = point3.y - point1.y;
  6962. var z2 = point3.z - point1.z;
  6963. var yz = (y1 * z2) - (z1 * y2);
  6964. var xz = (z1 * x2) - (x1 * z2);
  6965. var xy = (x1 * y2) - (y1 * x2);
  6966. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6967. var invPyth;
  6968. if (pyth !== 0) {
  6969. invPyth = 1.0 / pyth;
  6970. }
  6971. else {
  6972. invPyth = 0.0;
  6973. }
  6974. this.normal.x = yz * invPyth;
  6975. this.normal.y = xz * invPyth;
  6976. this.normal.z = xy * invPyth;
  6977. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6978. return this;
  6979. };
  6980. /**
  6981. * Checks if the plane is facing a given direction
  6982. * @param direction the direction to check if the plane is facing
  6983. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  6984. * @returns True is the vector "direction" is the same side than the plane normal.
  6985. */
  6986. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6987. var dot = Vector3.Dot(this.normal, direction);
  6988. return (dot <= epsilon);
  6989. };
  6990. /**
  6991. * Calculates the distance to a point
  6992. * @param point point to calculate distance to
  6993. * @returns the signed distance (float) from the given point to the Plane.
  6994. */
  6995. Plane.prototype.signedDistanceTo = function (point) {
  6996. return Vector3.Dot(point, this.normal) + this.d;
  6997. };
  6998. // Statics
  6999. /**
  7000. * Creates a plane from an array
  7001. * @param array the array to create a plane from
  7002. * @returns a new Plane from the given array.
  7003. */
  7004. Plane.FromArray = function (array) {
  7005. return new Plane(array[0], array[1], array[2], array[3]);
  7006. };
  7007. /**
  7008. * Creates a plane from three points
  7009. * @param point1 point used to create the plane
  7010. * @param point2 point used to create the plane
  7011. * @param point3 point used to create the plane
  7012. * @returns a new Plane defined by the three given points.
  7013. */
  7014. Plane.FromPoints = function (point1, point2, point3) {
  7015. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7016. result.copyFromPoints(point1, point2, point3);
  7017. return result;
  7018. };
  7019. /**
  7020. * Creates a plane from an origin point and a normal
  7021. * @param origin origin of the plane to be constructed
  7022. * @param normal normal of the plane to be constructed
  7023. * @returns a new Plane the normal vector to this plane at the given origin point.
  7024. * Note : the vector "normal" is updated because normalized.
  7025. */
  7026. Plane.FromPositionAndNormal = function (origin, normal) {
  7027. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7028. normal.normalize();
  7029. result.normal = normal;
  7030. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7031. return result;
  7032. };
  7033. /**
  7034. * Calculates the distance from a plane and a point
  7035. * @param origin origin of the plane to be constructed
  7036. * @param normal normal of the plane to be constructed
  7037. * @param point point to calculate distance to
  7038. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7039. */
  7040. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7041. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7042. return Vector3.Dot(point, normal) + d;
  7043. };
  7044. return Plane;
  7045. }());
  7046. BABYLON.Plane = Plane;
  7047. /**
  7048. * Class used to represent a viewport on screen
  7049. */
  7050. var Viewport = /** @class */ (function () {
  7051. /**
  7052. * Creates a Viewport object located at (x, y) and sized (width, height)
  7053. * @param x defines viewport left coordinate
  7054. * @param y defines viewport top coordinate
  7055. * @param width defines the viewport width
  7056. * @param height defines the viewport height
  7057. */
  7058. function Viewport(
  7059. /** viewport left coordinate */
  7060. x,
  7061. /** viewport top coordinate */
  7062. y,
  7063. /**viewport width */
  7064. width,
  7065. /** viewport height */
  7066. height) {
  7067. this.x = x;
  7068. this.y = y;
  7069. this.width = width;
  7070. this.height = height;
  7071. }
  7072. /**
  7073. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7074. * @param renderWidthOrEngine defines either an engine or the rendering width
  7075. * @param renderHeight defines the rendering height
  7076. * @returns a new Viewport
  7077. */
  7078. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7079. if (renderWidthOrEngine.getRenderWidth) {
  7080. var engine = renderWidthOrEngine;
  7081. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7082. }
  7083. var renderWidth = renderWidthOrEngine;
  7084. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7085. };
  7086. /**
  7087. * Returns a new Viewport copied from the current one
  7088. * @returns a new Viewport
  7089. */
  7090. Viewport.prototype.clone = function () {
  7091. return new Viewport(this.x, this.y, this.width, this.height);
  7092. };
  7093. return Viewport;
  7094. }());
  7095. BABYLON.Viewport = Viewport;
  7096. /**
  7097. * Reprasents a camera frustum
  7098. */
  7099. var Frustum = /** @class */ (function () {
  7100. function Frustum() {
  7101. }
  7102. /**
  7103. * Gets the planes representing the frustum
  7104. * @param transform matrix to be applied to the returned planes
  7105. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7106. */
  7107. Frustum.GetPlanes = function (transform) {
  7108. var frustumPlanes = [];
  7109. for (var index = 0; index < 6; index++) {
  7110. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7111. }
  7112. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7113. return frustumPlanes;
  7114. };
  7115. /**
  7116. * Gets the near frustum plane transformed by the transform matrix
  7117. * @param transform transformation matrix to be applied to the resulting frustum plane
  7118. * @param frustumPlane the resuling frustum plane
  7119. */
  7120. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7121. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7122. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7123. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7124. frustumPlane.d = transform.m[15] + transform.m[14];
  7125. frustumPlane.normalize();
  7126. };
  7127. /**
  7128. * Gets the far frustum plane transformed by the transform matrix
  7129. * @param transform transformation matrix to be applied to the resulting frustum plane
  7130. * @param frustumPlane the resuling frustum plane
  7131. */
  7132. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7133. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7134. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7135. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7136. frustumPlane.d = transform.m[15] - transform.m[14];
  7137. frustumPlane.normalize();
  7138. };
  7139. /**
  7140. * Gets the left frustum plane transformed by the transform matrix
  7141. * @param transform transformation matrix to be applied to the resulting frustum plane
  7142. * @param frustumPlane the resuling frustum plane
  7143. */
  7144. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7145. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7146. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7147. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7148. frustumPlane.d = transform.m[15] + transform.m[12];
  7149. frustumPlane.normalize();
  7150. };
  7151. /**
  7152. * Gets the right frustum plane transformed by the transform matrix
  7153. * @param transform transformation matrix to be applied to the resulting frustum plane
  7154. * @param frustumPlane the resuling frustum plane
  7155. */
  7156. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7157. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7158. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7159. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7160. frustumPlane.d = transform.m[15] - transform.m[12];
  7161. frustumPlane.normalize();
  7162. };
  7163. /**
  7164. * Gets the top frustum plane transformed by the transform matrix
  7165. * @param transform transformation matrix to be applied to the resulting frustum plane
  7166. * @param frustumPlane the resuling frustum plane
  7167. */
  7168. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7169. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7170. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7171. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7172. frustumPlane.d = transform.m[15] - transform.m[13];
  7173. frustumPlane.normalize();
  7174. };
  7175. /**
  7176. * Gets the bottom frustum plane transformed by the transform matrix
  7177. * @param transform transformation matrix to be applied to the resulting frustum plane
  7178. * @param frustumPlane the resuling frustum plane
  7179. */
  7180. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7181. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7182. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7183. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7184. frustumPlane.d = transform.m[15] + transform.m[13];
  7185. frustumPlane.normalize();
  7186. };
  7187. /**
  7188. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7189. * @param transform transformation matrix to be applied to the resulting frustum planes
  7190. * @param frustumPlanes the resuling frustum planes
  7191. */
  7192. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7193. // Near
  7194. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7195. // Far
  7196. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7197. // Left
  7198. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7199. // Right
  7200. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7201. // Top
  7202. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7203. // Bottom
  7204. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7205. };
  7206. return Frustum;
  7207. }());
  7208. BABYLON.Frustum = Frustum;
  7209. /** Defines supported spaces */
  7210. var Space;
  7211. (function (Space) {
  7212. /** Local (object) space */
  7213. Space[Space["LOCAL"] = 0] = "LOCAL";
  7214. /** World space */
  7215. Space[Space["WORLD"] = 1] = "WORLD";
  7216. /** Bone space */
  7217. Space[Space["BONE"] = 2] = "BONE";
  7218. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7219. /** Defines the 3 main axes */
  7220. var Axis = /** @class */ (function () {
  7221. function Axis() {
  7222. }
  7223. /** X axis */
  7224. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7225. /** Y axis */
  7226. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7227. /** Z axis */
  7228. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7229. return Axis;
  7230. }());
  7231. BABYLON.Axis = Axis;
  7232. ;
  7233. /** Class used to represent a Bezier curve */
  7234. var BezierCurve = /** @class */ (function () {
  7235. function BezierCurve() {
  7236. }
  7237. /**
  7238. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7239. * @param t defines the time
  7240. * @param x1 defines the left coordinate on X axis
  7241. * @param y1 defines the left coordinate on Y axis
  7242. * @param x2 defines the right coordinate on X axis
  7243. * @param y2 defines the right coordinate on Y axis
  7244. * @returns the interpolated value
  7245. */
  7246. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7247. // Extract X (which is equal to time here)
  7248. var f0 = 1 - 3 * x2 + 3 * x1;
  7249. var f1 = 3 * x2 - 6 * x1;
  7250. var f2 = 3 * x1;
  7251. var refinedT = t;
  7252. for (var i = 0; i < 5; i++) {
  7253. var refinedT2 = refinedT * refinedT;
  7254. var refinedT3 = refinedT2 * refinedT;
  7255. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7256. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7257. refinedT -= (x - t) * slope;
  7258. refinedT = Math.min(1, Math.max(0, refinedT));
  7259. }
  7260. // Resolve cubic bezier for the given x
  7261. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7262. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7263. Math.pow(refinedT, 3);
  7264. };
  7265. return BezierCurve;
  7266. }());
  7267. BABYLON.BezierCurve = BezierCurve;
  7268. /**
  7269. * Defines potential orientation for back face culling
  7270. */
  7271. var Orientation;
  7272. (function (Orientation) {
  7273. /**
  7274. * Clockwise
  7275. */
  7276. Orientation[Orientation["CW"] = 0] = "CW";
  7277. /** Counter clockwise */
  7278. Orientation[Orientation["CCW"] = 1] = "CCW";
  7279. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7280. /**
  7281. * Defines angle representation
  7282. */
  7283. var Angle = /** @class */ (function () {
  7284. /**
  7285. * Creates an Angle object of "radians" radians (float).
  7286. */
  7287. function Angle(radians) {
  7288. this._radians = radians;
  7289. if (this._radians < 0.0)
  7290. this._radians += (2.0 * Math.PI);
  7291. }
  7292. /**
  7293. * Get value in degrees
  7294. * @returns the Angle value in degrees (float)
  7295. */
  7296. Angle.prototype.degrees = function () {
  7297. return this._radians * 180.0 / Math.PI;
  7298. };
  7299. /**
  7300. * Get value in radians
  7301. * @returns the Angle value in radians (float)
  7302. */
  7303. Angle.prototype.radians = function () {
  7304. return this._radians;
  7305. };
  7306. /**
  7307. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7308. * @param a defines first vector
  7309. * @param b defines second vector
  7310. * @returns a new Angle
  7311. */
  7312. Angle.BetweenTwoPoints = function (a, b) {
  7313. var delta = b.subtract(a);
  7314. var theta = Math.atan2(delta.y, delta.x);
  7315. return new Angle(theta);
  7316. };
  7317. /**
  7318. * Gets a new Angle object from the given float in radians
  7319. * @param radians defines the angle value in radians
  7320. * @returns a new Angle
  7321. */
  7322. Angle.FromRadians = function (radians) {
  7323. return new Angle(radians);
  7324. };
  7325. /**
  7326. * Gets a new Angle object from the given float in degrees
  7327. * @param degrees defines the angle value in degrees
  7328. * @returns a new Angle
  7329. */
  7330. Angle.FromDegrees = function (degrees) {
  7331. return new Angle(degrees * Math.PI / 180.0);
  7332. };
  7333. return Angle;
  7334. }());
  7335. BABYLON.Angle = Angle;
  7336. /**
  7337. * This represents an arc in a 2d space.
  7338. */
  7339. var Arc2 = /** @class */ (function () {
  7340. /**
  7341. * Creates an Arc object from the three given points : start, middle and end.
  7342. * @param startPoint Defines the start point of the arc
  7343. * @param midPoint Defines the midlle point of the arc
  7344. * @param endPoint Defines the end point of the arc
  7345. */
  7346. function Arc2(
  7347. /** Defines the start point of the arc */
  7348. startPoint,
  7349. /** Defines the mid point of the arc */
  7350. midPoint,
  7351. /** Defines the end point of the arc */
  7352. endPoint) {
  7353. this.startPoint = startPoint;
  7354. this.midPoint = midPoint;
  7355. this.endPoint = endPoint;
  7356. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7357. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7358. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7359. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7360. 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);
  7361. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7362. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7363. var a1 = this.startAngle.degrees();
  7364. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7365. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7366. // angles correction
  7367. if (a2 - a1 > +180.0)
  7368. a2 -= 360.0;
  7369. if (a2 - a1 < -180.0)
  7370. a2 += 360.0;
  7371. if (a3 - a2 > +180.0)
  7372. a3 -= 360.0;
  7373. if (a3 - a2 < -180.0)
  7374. a3 += 360.0;
  7375. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7376. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7377. }
  7378. return Arc2;
  7379. }());
  7380. BABYLON.Arc2 = Arc2;
  7381. /**
  7382. * Represents a 2D path made up of multiple 2D points
  7383. */
  7384. var Path2 = /** @class */ (function () {
  7385. /**
  7386. * Creates a Path2 object from the starting 2D coordinates x and y.
  7387. * @param x the starting points x value
  7388. * @param y the starting points y value
  7389. */
  7390. function Path2(x, y) {
  7391. this._points = new Array();
  7392. this._length = 0.0;
  7393. /**
  7394. * If the path start and end point are the same
  7395. */
  7396. this.closed = false;
  7397. this._points.push(new Vector2(x, y));
  7398. }
  7399. /**
  7400. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7401. * @param x the added points x value
  7402. * @param y the added points y value
  7403. * @returns the updated Path2.
  7404. */
  7405. Path2.prototype.addLineTo = function (x, y) {
  7406. if (this.closed) {
  7407. return this;
  7408. }
  7409. var newPoint = new Vector2(x, y);
  7410. var previousPoint = this._points[this._points.length - 1];
  7411. this._points.push(newPoint);
  7412. this._length += newPoint.subtract(previousPoint).length();
  7413. return this;
  7414. };
  7415. /**
  7416. * 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.
  7417. * @param midX middle point x value
  7418. * @param midY middle point y value
  7419. * @param endX end point x value
  7420. * @param endY end point y value
  7421. * @param numberOfSegments (default: 36)
  7422. * @returns the updated Path2.
  7423. */
  7424. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7425. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7426. if (this.closed) {
  7427. return this;
  7428. }
  7429. var startPoint = this._points[this._points.length - 1];
  7430. var midPoint = new Vector2(midX, midY);
  7431. var endPoint = new Vector2(endX, endY);
  7432. var arc = new Arc2(startPoint, midPoint, endPoint);
  7433. var increment = arc.angle.radians() / numberOfSegments;
  7434. if (arc.orientation === Orientation.CW)
  7435. increment *= -1;
  7436. var currentAngle = arc.startAngle.radians() + increment;
  7437. for (var i = 0; i < numberOfSegments; i++) {
  7438. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7439. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7440. this.addLineTo(x, y);
  7441. currentAngle += increment;
  7442. }
  7443. return this;
  7444. };
  7445. /**
  7446. * Closes the Path2.
  7447. * @returns the Path2.
  7448. */
  7449. Path2.prototype.close = function () {
  7450. this.closed = true;
  7451. return this;
  7452. };
  7453. /**
  7454. * Gets the sum of the distance between each sequential point in the path
  7455. * @returns the Path2 total length (float).
  7456. */
  7457. Path2.prototype.length = function () {
  7458. var result = this._length;
  7459. if (!this.closed) {
  7460. var lastPoint = this._points[this._points.length - 1];
  7461. var firstPoint = this._points[0];
  7462. result += (firstPoint.subtract(lastPoint).length());
  7463. }
  7464. return result;
  7465. };
  7466. /**
  7467. * Gets the points which construct the path
  7468. * @returns the Path2 internal array of points.
  7469. */
  7470. Path2.prototype.getPoints = function () {
  7471. return this._points;
  7472. };
  7473. /**
  7474. * Retreives the point at the distance aways from the starting point
  7475. * @param normalizedLengthPosition the length along the path to retreive the point from
  7476. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7477. */
  7478. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7479. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7480. return Vector2.Zero();
  7481. }
  7482. var lengthPosition = normalizedLengthPosition * this.length();
  7483. var previousOffset = 0;
  7484. for (var i = 0; i < this._points.length; i++) {
  7485. var j = (i + 1) % this._points.length;
  7486. var a = this._points[i];
  7487. var b = this._points[j];
  7488. var bToA = b.subtract(a);
  7489. var nextOffset = (bToA.length() + previousOffset);
  7490. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7491. var dir = bToA.normalize();
  7492. var localOffset = lengthPosition - previousOffset;
  7493. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7494. }
  7495. previousOffset = nextOffset;
  7496. }
  7497. return Vector2.Zero();
  7498. };
  7499. /**
  7500. * Creates a new path starting from an x and y position
  7501. * @param x starting x value
  7502. * @param y starting y value
  7503. * @returns a new Path2 starting at the coordinates (x, y).
  7504. */
  7505. Path2.StartingAt = function (x, y) {
  7506. return new Path2(x, y);
  7507. };
  7508. return Path2;
  7509. }());
  7510. BABYLON.Path2 = Path2;
  7511. /**
  7512. * Represents a 3D path made up of multiple 3D points
  7513. */
  7514. var Path3D = /** @class */ (function () {
  7515. /**
  7516. * new Path3D(path, normal, raw)
  7517. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7518. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7519. * @param path an array of Vector3, the curve axis of the Path3D
  7520. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7521. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7522. */
  7523. function Path3D(
  7524. /**
  7525. * an array of Vector3, the curve axis of the Path3D
  7526. */
  7527. path, firstNormal, raw) {
  7528. if (firstNormal === void 0) { firstNormal = null; }
  7529. this.path = path;
  7530. this._curve = new Array();
  7531. this._distances = new Array();
  7532. this._tangents = new Array();
  7533. this._normals = new Array();
  7534. this._binormals = new Array();
  7535. for (var p = 0; p < path.length; p++) {
  7536. this._curve[p] = path[p].clone(); // hard copy
  7537. }
  7538. this._raw = raw || false;
  7539. this._compute(firstNormal);
  7540. }
  7541. /**
  7542. * Returns the Path3D array of successive Vector3 designing its curve.
  7543. * @returns the Path3D array of successive Vector3 designing its curve.
  7544. */
  7545. Path3D.prototype.getCurve = function () {
  7546. return this._curve;
  7547. };
  7548. /**
  7549. * Returns an array populated with tangent vectors on each Path3D curve point.
  7550. * @returns an array populated with tangent vectors on each Path3D curve point.
  7551. */
  7552. Path3D.prototype.getTangents = function () {
  7553. return this._tangents;
  7554. };
  7555. /**
  7556. * Returns an array populated with normal vectors on each Path3D curve point.
  7557. * @returns an array populated with normal vectors on each Path3D curve point.
  7558. */
  7559. Path3D.prototype.getNormals = function () {
  7560. return this._normals;
  7561. };
  7562. /**
  7563. * Returns an array populated with binormal vectors on each Path3D curve point.
  7564. * @returns an array populated with binormal vectors on each Path3D curve point.
  7565. */
  7566. Path3D.prototype.getBinormals = function () {
  7567. return this._binormals;
  7568. };
  7569. /**
  7570. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7571. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7572. */
  7573. Path3D.prototype.getDistances = function () {
  7574. return this._distances;
  7575. };
  7576. /**
  7577. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7578. * @param path path which all values are copied into the curves points
  7579. * @param firstNormal which should be projected onto the curve
  7580. * @returns the same object updated.
  7581. */
  7582. Path3D.prototype.update = function (path, firstNormal) {
  7583. if (firstNormal === void 0) { firstNormal = null; }
  7584. for (var p = 0; p < path.length; p++) {
  7585. this._curve[p].x = path[p].x;
  7586. this._curve[p].y = path[p].y;
  7587. this._curve[p].z = path[p].z;
  7588. }
  7589. this._compute(firstNormal);
  7590. return this;
  7591. };
  7592. // private function compute() : computes tangents, normals and binormals
  7593. Path3D.prototype._compute = function (firstNormal) {
  7594. var l = this._curve.length;
  7595. // first and last tangents
  7596. this._tangents[0] = this._getFirstNonNullVector(0);
  7597. if (!this._raw) {
  7598. this._tangents[0].normalize();
  7599. }
  7600. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7601. if (!this._raw) {
  7602. this._tangents[l - 1].normalize();
  7603. }
  7604. // normals and binormals at first point : arbitrary vector with _normalVector()
  7605. var tg0 = this._tangents[0];
  7606. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7607. this._normals[0] = pp0;
  7608. if (!this._raw) {
  7609. this._normals[0].normalize();
  7610. }
  7611. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7612. if (!this._raw) {
  7613. this._binormals[0].normalize();
  7614. }
  7615. this._distances[0] = 0.0;
  7616. // normals and binormals : next points
  7617. var prev; // previous vector (segment)
  7618. var cur; // current vector (segment)
  7619. var curTang; // current tangent
  7620. // previous normal
  7621. var prevBinor; // previous binormal
  7622. for (var i = 1; i < l; i++) {
  7623. // tangents
  7624. prev = this._getLastNonNullVector(i);
  7625. if (i < l - 1) {
  7626. cur = this._getFirstNonNullVector(i);
  7627. this._tangents[i] = prev.add(cur);
  7628. this._tangents[i].normalize();
  7629. }
  7630. this._distances[i] = this._distances[i - 1] + prev.length();
  7631. // normals and binormals
  7632. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7633. curTang = this._tangents[i];
  7634. prevBinor = this._binormals[i - 1];
  7635. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7636. if (!this._raw) {
  7637. this._normals[i].normalize();
  7638. }
  7639. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7640. if (!this._raw) {
  7641. this._binormals[i].normalize();
  7642. }
  7643. }
  7644. };
  7645. // private function getFirstNonNullVector(index)
  7646. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7647. Path3D.prototype._getFirstNonNullVector = function (index) {
  7648. var i = 1;
  7649. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7650. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7651. i++;
  7652. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7653. }
  7654. return nNVector;
  7655. };
  7656. // private function getLastNonNullVector(index)
  7657. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7658. Path3D.prototype._getLastNonNullVector = function (index) {
  7659. var i = 1;
  7660. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7661. while (nLVector.length() === 0 && index > i + 1) {
  7662. i++;
  7663. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7664. }
  7665. return nLVector;
  7666. };
  7667. // private function normalVector(v0, vt, va) :
  7668. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7669. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7670. Path3D.prototype._normalVector = function (v0, vt, va) {
  7671. var normal0;
  7672. var tgl = vt.length();
  7673. if (tgl === 0.0) {
  7674. tgl = 1.0;
  7675. }
  7676. if (va === undefined || va === null) {
  7677. var point;
  7678. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7679. point = new Vector3(0.0, -1.0, 0.0);
  7680. }
  7681. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7682. point = new Vector3(1.0, 0.0, 0.0);
  7683. }
  7684. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7685. point = new Vector3(0.0, 0.0, 1.0);
  7686. }
  7687. else {
  7688. point = Vector3.Zero();
  7689. }
  7690. normal0 = Vector3.Cross(vt, point);
  7691. }
  7692. else {
  7693. normal0 = Vector3.Cross(vt, va);
  7694. Vector3.CrossToRef(normal0, vt, normal0);
  7695. }
  7696. normal0.normalize();
  7697. return normal0;
  7698. };
  7699. return Path3D;
  7700. }());
  7701. BABYLON.Path3D = Path3D;
  7702. /**
  7703. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7704. * A Curve3 is designed from a series of successive Vector3.
  7705. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7706. */
  7707. var Curve3 = /** @class */ (function () {
  7708. /**
  7709. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7710. * A Curve3 is designed from a series of successive Vector3.
  7711. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7712. * @param points points which make up the curve
  7713. */
  7714. function Curve3(points) {
  7715. this._length = 0.0;
  7716. this._points = points;
  7717. this._length = this._computeLength(points);
  7718. }
  7719. /**
  7720. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7721. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7722. * @param v1 (Vector3) the control point
  7723. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7724. * @param nbPoints (integer) the wanted number of points in the curve
  7725. * @returns the created Curve3
  7726. */
  7727. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7728. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7729. var bez = new Array();
  7730. var equation = function (t, val0, val1, val2) {
  7731. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7732. return res;
  7733. };
  7734. for (var i = 0; i <= nbPoints; i++) {
  7735. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  7736. }
  7737. return new Curve3(bez);
  7738. };
  7739. /**
  7740. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7741. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7742. * @param v1 (Vector3) the first control point
  7743. * @param v2 (Vector3) the second control point
  7744. * @param v3 (Vector3) the end point of the Cubic Bezier
  7745. * @param nbPoints (integer) the wanted number of points in the curve
  7746. * @returns the created Curve3
  7747. */
  7748. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7749. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7750. var bez = new Array();
  7751. var equation = function (t, val0, val1, val2, val3) {
  7752. 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;
  7753. return res;
  7754. };
  7755. for (var i = 0; i <= nbPoints; i++) {
  7756. 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)));
  7757. }
  7758. return new Curve3(bez);
  7759. };
  7760. /**
  7761. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7762. * @param p1 (Vector3) the origin point of the Hermite Spline
  7763. * @param t1 (Vector3) the tangent vector at the origin point
  7764. * @param p2 (Vector3) the end point of the Hermite Spline
  7765. * @param t2 (Vector3) the tangent vector at the end point
  7766. * @param nbPoints (integer) the wanted number of points in the curve
  7767. * @returns the created Curve3
  7768. */
  7769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7770. var hermite = new Array();
  7771. var step = 1.0 / nbPoints;
  7772. for (var i = 0; i <= nbPoints; i++) {
  7773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7774. }
  7775. return new Curve3(hermite);
  7776. };
  7777. /**
  7778. * Returns a Curve3 object along a CatmullRom Spline curve :
  7779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7780. * @param nbPoints (integer) the wanted number of points between each curve control points
  7781. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7782. * @returns the created Curve3
  7783. */
  7784. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7785. var catmullRom = new Array();
  7786. var step = 1.0 / nbPoints;
  7787. var amount = 0.0;
  7788. if (closed) {
  7789. var pointsCount = points.length;
  7790. for (var i = 0; i < pointsCount; i++) {
  7791. amount = 0;
  7792. for (var c = 0; c < nbPoints; c++) {
  7793. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7794. amount += step;
  7795. }
  7796. }
  7797. catmullRom.push(catmullRom[0]);
  7798. }
  7799. else {
  7800. var totalPoints = new Array();
  7801. totalPoints.push(points[0].clone());
  7802. Array.prototype.push.apply(totalPoints, points);
  7803. totalPoints.push(points[points.length - 1].clone());
  7804. for (var i = 0; i < totalPoints.length - 3; i++) {
  7805. amount = 0;
  7806. for (var c = 0; c < nbPoints; c++) {
  7807. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7808. amount += step;
  7809. }
  7810. }
  7811. i--;
  7812. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7813. }
  7814. return new Curve3(catmullRom);
  7815. };
  7816. /**
  7817. * @returns the Curve3 stored array of successive Vector3
  7818. */
  7819. Curve3.prototype.getPoints = function () {
  7820. return this._points;
  7821. };
  7822. /**
  7823. * @returns the computed length (float) of the curve.
  7824. */
  7825. Curve3.prototype.length = function () {
  7826. return this._length;
  7827. };
  7828. /**
  7829. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7830. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7831. * curveA and curveB keep unchanged.
  7832. * @param curve the curve to continue from this curve
  7833. * @returns the newly constructed curve
  7834. */
  7835. Curve3.prototype.continue = function (curve) {
  7836. var lastPoint = this._points[this._points.length - 1];
  7837. var continuedPoints = this._points.slice();
  7838. var curvePoints = curve.getPoints();
  7839. for (var i = 1; i < curvePoints.length; i++) {
  7840. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7841. }
  7842. var continuedCurve = new Curve3(continuedPoints);
  7843. return continuedCurve;
  7844. };
  7845. Curve3.prototype._computeLength = function (path) {
  7846. var l = 0;
  7847. for (var i = 1; i < path.length; i++) {
  7848. l += (path[i].subtract(path[i - 1])).length();
  7849. }
  7850. return l;
  7851. };
  7852. return Curve3;
  7853. }());
  7854. BABYLON.Curve3 = Curve3;
  7855. // Vertex formats
  7856. /**
  7857. * Contains position and normal vectors for a vertex
  7858. */
  7859. var PositionNormalVertex = /** @class */ (function () {
  7860. /**
  7861. * Creates a PositionNormalVertex
  7862. * @param position the position of the vertex (defaut: 0,0,0)
  7863. * @param normal the normal of the vertex (defaut: 0,1,0)
  7864. */
  7865. function PositionNormalVertex(
  7866. /** the position of the vertex (defaut: 0,0,0) */
  7867. position,
  7868. /** the normal of the vertex (defaut: 0,1,0) */
  7869. normal) {
  7870. if (position === void 0) { position = Vector3.Zero(); }
  7871. if (normal === void 0) { normal = Vector3.Up(); }
  7872. this.position = position;
  7873. this.normal = normal;
  7874. }
  7875. /**
  7876. * Clones the PositionNormalVertex
  7877. * @returns the cloned PositionNormalVertex
  7878. */
  7879. PositionNormalVertex.prototype.clone = function () {
  7880. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7881. };
  7882. return PositionNormalVertex;
  7883. }());
  7884. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7885. /**
  7886. * Contains position, normal and uv vectors for a vertex
  7887. */
  7888. var PositionNormalTextureVertex = /** @class */ (function () {
  7889. /**
  7890. * Creates a PositionNormalTextureVertex
  7891. * @param position the position of the vertex (defaut: 0,0,0)
  7892. * @param normal the normal of the vertex (defaut: 0,1,0)
  7893. * @param uv the uv of the vertex (default: 0,0)
  7894. */
  7895. function PositionNormalTextureVertex(
  7896. /** the position of the vertex (defaut: 0,0,0) */
  7897. position,
  7898. /** the normal of the vertex (defaut: 0,1,0) */
  7899. normal,
  7900. /** the uv of the vertex (default: 0,0) */
  7901. uv) {
  7902. if (position === void 0) { position = Vector3.Zero(); }
  7903. if (normal === void 0) { normal = Vector3.Up(); }
  7904. if (uv === void 0) { uv = Vector2.Zero(); }
  7905. this.position = position;
  7906. this.normal = normal;
  7907. this.uv = uv;
  7908. }
  7909. /**
  7910. * Clones the PositionNormalTextureVertex
  7911. * @returns the cloned PositionNormalTextureVertex
  7912. */
  7913. PositionNormalTextureVertex.prototype.clone = function () {
  7914. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7915. };
  7916. return PositionNormalTextureVertex;
  7917. }());
  7918. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7919. // Temporary pre-allocated objects for engine internal use
  7920. // usage in any internal function :
  7921. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7922. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7923. /**
  7924. * @hidden
  7925. */
  7926. var Tmp = /** @class */ (function () {
  7927. function Tmp() {
  7928. }
  7929. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7930. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7931. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7932. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7933. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7934. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7935. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7936. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7937. Matrix.Zero(), Matrix.Zero(),
  7938. Matrix.Zero(), Matrix.Zero(),
  7939. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7940. return Tmp;
  7941. }());
  7942. BABYLON.Tmp = Tmp;
  7943. /**
  7944. * @hidden
  7945. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7946. */
  7947. var MathTmp = /** @class */ (function () {
  7948. function MathTmp() {
  7949. }
  7950. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7951. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7952. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7953. return MathTmp;
  7954. }());
  7955. })(BABYLON || (BABYLON = {}));
  7956. //# sourceMappingURL=babylon.math.js.map
  7957. var BABYLON;
  7958. (function (BABYLON) {
  7959. /**
  7960. * Scalar computation library
  7961. */
  7962. var Scalar = /** @class */ (function () {
  7963. function Scalar() {
  7964. }
  7965. /**
  7966. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7967. * @param a number
  7968. * @param b number
  7969. * @param epsilon (default = 1.401298E-45)
  7970. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7971. */
  7972. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7973. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7974. var num = a - b;
  7975. return -epsilon <= num && num <= epsilon;
  7976. };
  7977. /**
  7978. * Returns a string : the upper case translation of the number i to hexadecimal.
  7979. * @param i number
  7980. * @returns the upper case translation of the number i to hexadecimal.
  7981. */
  7982. Scalar.ToHex = function (i) {
  7983. var str = i.toString(16);
  7984. if (i <= 15) {
  7985. return ("0" + str).toUpperCase();
  7986. }
  7987. return str.toUpperCase();
  7988. };
  7989. /**
  7990. * Returns -1 if value is negative and +1 is value is positive.
  7991. * @param value the value
  7992. * @returns the value itself if it's equal to zero.
  7993. */
  7994. Scalar.Sign = function (value) {
  7995. value = +value; // convert to a number
  7996. if (value === 0 || isNaN(value))
  7997. return value;
  7998. return value > 0 ? 1 : -1;
  7999. };
  8000. /**
  8001. * Returns the value itself if it's between min and max.
  8002. * Returns min if the value is lower than min.
  8003. * Returns max if the value is greater than max.
  8004. * @param value the value to clmap
  8005. * @param min the min value to clamp to (default: 0)
  8006. * @param max the max value to clamp to (default: 1)
  8007. * @returns the clamped value
  8008. */
  8009. Scalar.Clamp = function (value, min, max) {
  8010. if (min === void 0) { min = 0; }
  8011. if (max === void 0) { max = 1; }
  8012. return Math.min(max, Math.max(min, value));
  8013. };
  8014. /**
  8015. * the log2 of value.
  8016. * @param value the value to compute log2 of
  8017. * @returns the log2 of value.
  8018. */
  8019. Scalar.Log2 = function (value) {
  8020. return Math.log(value) * Math.LOG2E;
  8021. };
  8022. /**
  8023. * Loops the value, so that it is never larger than length and never smaller than 0.
  8024. *
  8025. * This is similar to the modulo operator but it works with floating point numbers.
  8026. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8027. * With t = 5 and length = 2.5, the result would be 0.0.
  8028. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8029. * @param value the value
  8030. * @param length the length
  8031. * @returns the looped value
  8032. */
  8033. Scalar.Repeat = function (value, length) {
  8034. return value - Math.floor(value / length) * length;
  8035. };
  8036. /**
  8037. * Normalize the value between 0.0 and 1.0 using min and max values
  8038. * @param value value to normalize
  8039. * @param min max to normalize between
  8040. * @param max min to normalize between
  8041. * @returns the normalized value
  8042. */
  8043. Scalar.Normalize = function (value, min, max) {
  8044. return (value - min) / (max - min);
  8045. };
  8046. /**
  8047. * Denormalize the value from 0.0 and 1.0 using min and max values
  8048. * @param normalized value to denormalize
  8049. * @param min max to denormalize between
  8050. * @param max min to denormalize between
  8051. * @returns the denormalized value
  8052. */
  8053. Scalar.Denormalize = function (normalized, min, max) {
  8054. return (normalized * (max - min) + min);
  8055. };
  8056. /**
  8057. * Calculates the shortest difference between two given angles given in degrees.
  8058. * @param current current angle in degrees
  8059. * @param target target angle in degrees
  8060. * @returns the delta
  8061. */
  8062. Scalar.DeltaAngle = function (current, target) {
  8063. var num = Scalar.Repeat(target - current, 360.0);
  8064. if (num > 180.0) {
  8065. num -= 360.0;
  8066. }
  8067. return num;
  8068. };
  8069. /**
  8070. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8071. * @param tx value
  8072. * @param length length
  8073. * @returns The returned value will move back and forth between 0 and length
  8074. */
  8075. Scalar.PingPong = function (tx, length) {
  8076. var t = Scalar.Repeat(tx, length * 2.0);
  8077. return length - Math.abs(t - length);
  8078. };
  8079. /**
  8080. * Interpolates between min and max with smoothing at the limits.
  8081. *
  8082. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8083. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8084. * @param from from
  8085. * @param to to
  8086. * @param tx value
  8087. * @returns the smooth stepped value
  8088. */
  8089. Scalar.SmoothStep = function (from, to, tx) {
  8090. var t = Scalar.Clamp(tx);
  8091. t = -2.0 * t * t * t + 3.0 * t * t;
  8092. return to * t + from * (1.0 - t);
  8093. };
  8094. /**
  8095. * Moves a value current towards target.
  8096. *
  8097. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8098. * Negative values of maxDelta pushes the value away from target.
  8099. * @param current current value
  8100. * @param target target value
  8101. * @param maxDelta max distance to move
  8102. * @returns resulting value
  8103. */
  8104. Scalar.MoveTowards = function (current, target, maxDelta) {
  8105. var result = 0;
  8106. if (Math.abs(target - current) <= maxDelta) {
  8107. result = target;
  8108. }
  8109. else {
  8110. result = current + Scalar.Sign(target - current) * maxDelta;
  8111. }
  8112. return result;
  8113. };
  8114. /**
  8115. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8116. *
  8117. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8118. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8119. * @param current current value
  8120. * @param target target value
  8121. * @param maxDelta max distance to move
  8122. * @returns resulting angle
  8123. */
  8124. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8125. var num = Scalar.DeltaAngle(current, target);
  8126. var result = 0;
  8127. if (-maxDelta < num && num < maxDelta) {
  8128. result = target;
  8129. }
  8130. else {
  8131. target = current + num;
  8132. result = Scalar.MoveTowards(current, target, maxDelta);
  8133. }
  8134. return result;
  8135. };
  8136. /**
  8137. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8138. * @param start start value
  8139. * @param end target value
  8140. * @param amount amount to lerp between
  8141. * @returns the lerped value
  8142. */
  8143. Scalar.Lerp = function (start, end, amount) {
  8144. return start + ((end - start) * amount);
  8145. };
  8146. /**
  8147. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8148. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8149. * @param start start value
  8150. * @param end target value
  8151. * @param amount amount to lerp between
  8152. * @returns the lerped value
  8153. */
  8154. Scalar.LerpAngle = function (start, end, amount) {
  8155. var num = Scalar.Repeat(end - start, 360.0);
  8156. if (num > 180.0) {
  8157. num -= 360.0;
  8158. }
  8159. return start + num * Scalar.Clamp(amount);
  8160. };
  8161. /**
  8162. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8163. * @param a start value
  8164. * @param b target value
  8165. * @param value value between a and b
  8166. * @returns the inverseLerp value
  8167. */
  8168. Scalar.InverseLerp = function (a, b, value) {
  8169. var result = 0;
  8170. if (a != b) {
  8171. result = Scalar.Clamp((value - a) / (b - a));
  8172. }
  8173. else {
  8174. result = 0.0;
  8175. }
  8176. return result;
  8177. };
  8178. /**
  8179. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8180. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8181. * @param value1 spline value
  8182. * @param tangent1 spline value
  8183. * @param value2 spline value
  8184. * @param tangent2 spline value
  8185. * @param amount input value
  8186. * @returns hermite result
  8187. */
  8188. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8189. var squared = amount * amount;
  8190. var cubed = amount * squared;
  8191. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8192. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8193. var part3 = (cubed - (2.0 * squared)) + amount;
  8194. var part4 = cubed - squared;
  8195. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8196. };
  8197. /**
  8198. * Returns a random float number between and min and max values
  8199. * @param min min value of random
  8200. * @param max max value of random
  8201. * @returns random value
  8202. */
  8203. Scalar.RandomRange = function (min, max) {
  8204. if (min === max)
  8205. return min;
  8206. return ((Math.random() * (max - min)) + min);
  8207. };
  8208. /**
  8209. * This function returns percentage of a number in a given range.
  8210. *
  8211. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8212. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8213. * @param number to convert to percentage
  8214. * @param min min range
  8215. * @param max max range
  8216. * @returns the percentage
  8217. */
  8218. Scalar.RangeToPercent = function (number, min, max) {
  8219. return ((number - min) / (max - min));
  8220. };
  8221. /**
  8222. * This function returns number that corresponds to the percentage in a given range.
  8223. *
  8224. * PercentToRange(0.34,0,100) will return 34.
  8225. * @param percent to convert to number
  8226. * @param min min range
  8227. * @param max max range
  8228. * @returns the number
  8229. */
  8230. Scalar.PercentToRange = function (percent, min, max) {
  8231. return ((max - min) * percent + min);
  8232. };
  8233. /**
  8234. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8235. * @param angle The angle to normalize in radian.
  8236. * @return The converted angle.
  8237. */
  8238. Scalar.NormalizeRadians = function (angle) {
  8239. // More precise but slower version kept for reference.
  8240. // angle = angle % Tools.TwoPi;
  8241. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8242. //if (angle > Math.PI) {
  8243. // angle -= Tools.TwoPi;
  8244. //}
  8245. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8246. return angle;
  8247. };
  8248. /**
  8249. * Two pi constants convenient for computation.
  8250. */
  8251. Scalar.TwoPi = Math.PI * 2;
  8252. return Scalar;
  8253. }());
  8254. BABYLON.Scalar = Scalar;
  8255. })(BABYLON || (BABYLON = {}));
  8256. //# sourceMappingURL=babylon.math.scalar.js.map
  8257. //# sourceMappingURL=babylon.mixins.js.map
  8258. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8259. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8260. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8261. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8262. //# sourceMappingURL=babylon.webgl2.js.map
  8263. var BABYLON;
  8264. (function (BABYLON) {
  8265. var __decoratorInitialStore = {};
  8266. var __mergedStore = {};
  8267. var _copySource = function (creationFunction, source, instanciate) {
  8268. var destination = creationFunction();
  8269. // Tags
  8270. if (BABYLON.Tags) {
  8271. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8272. }
  8273. var classStore = getMergedStore(destination);
  8274. // Properties
  8275. for (var property in classStore) {
  8276. var propertyDescriptor = classStore[property];
  8277. var sourceProperty = source[property];
  8278. var propertyType = propertyDescriptor.type;
  8279. if (sourceProperty !== undefined && sourceProperty !== null) {
  8280. switch (propertyType) {
  8281. case 0: // Value
  8282. case 6: // Mesh reference
  8283. case 11: // Camera reference
  8284. destination[property] = sourceProperty;
  8285. break;
  8286. case 1: // Texture
  8287. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8288. break;
  8289. case 2: // Color3
  8290. case 3: // FresnelParameters
  8291. case 4: // Vector2
  8292. case 5: // Vector3
  8293. case 7: // Color Curves
  8294. case 10: // Quaternion
  8295. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8296. break;
  8297. }
  8298. }
  8299. }
  8300. return destination;
  8301. };
  8302. function getDirectStore(target) {
  8303. var classKey = target.getClassName();
  8304. if (!__decoratorInitialStore[classKey]) {
  8305. __decoratorInitialStore[classKey] = {};
  8306. }
  8307. return __decoratorInitialStore[classKey];
  8308. }
  8309. /**
  8310. * Return the list of properties flagged as serializable
  8311. * @param target: host object
  8312. */
  8313. function getMergedStore(target) {
  8314. var classKey = target.getClassName();
  8315. if (__mergedStore[classKey]) {
  8316. return __mergedStore[classKey];
  8317. }
  8318. __mergedStore[classKey] = {};
  8319. var store = __mergedStore[classKey];
  8320. var currentTarget = target;
  8321. var currentKey = classKey;
  8322. while (currentKey) {
  8323. var initialStore = __decoratorInitialStore[currentKey];
  8324. for (var property in initialStore) {
  8325. store[property] = initialStore[property];
  8326. }
  8327. var parent_1 = void 0;
  8328. var done = false;
  8329. do {
  8330. parent_1 = Object.getPrototypeOf(currentTarget);
  8331. if (!parent_1.getClassName) {
  8332. done = true;
  8333. break;
  8334. }
  8335. if (parent_1.getClassName() !== currentKey) {
  8336. break;
  8337. }
  8338. currentTarget = parent_1;
  8339. } while (parent_1);
  8340. if (done) {
  8341. break;
  8342. }
  8343. currentKey = parent_1.getClassName();
  8344. currentTarget = parent_1;
  8345. }
  8346. return store;
  8347. }
  8348. function generateSerializableMember(type, sourceName) {
  8349. return function (target, propertyKey) {
  8350. var classStore = getDirectStore(target);
  8351. if (!classStore[propertyKey]) {
  8352. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8353. }
  8354. };
  8355. }
  8356. function generateExpandMember(setCallback, targetKey) {
  8357. if (targetKey === void 0) { targetKey = null; }
  8358. return function (target, propertyKey) {
  8359. var key = targetKey || ("_" + propertyKey);
  8360. Object.defineProperty(target, propertyKey, {
  8361. get: function () {
  8362. return this[key];
  8363. },
  8364. set: function (value) {
  8365. if (this[key] === value) {
  8366. return;
  8367. }
  8368. this[key] = value;
  8369. target[setCallback].apply(this);
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. };
  8375. }
  8376. function expandToProperty(callback, targetKey) {
  8377. if (targetKey === void 0) { targetKey = null; }
  8378. return generateExpandMember(callback, targetKey);
  8379. }
  8380. BABYLON.expandToProperty = expandToProperty;
  8381. function serialize(sourceName) {
  8382. return generateSerializableMember(0, sourceName); // value member
  8383. }
  8384. BABYLON.serialize = serialize;
  8385. function serializeAsTexture(sourceName) {
  8386. return generateSerializableMember(1, sourceName); // texture member
  8387. }
  8388. BABYLON.serializeAsTexture = serializeAsTexture;
  8389. function serializeAsColor3(sourceName) {
  8390. return generateSerializableMember(2, sourceName); // color3 member
  8391. }
  8392. BABYLON.serializeAsColor3 = serializeAsColor3;
  8393. function serializeAsFresnelParameters(sourceName) {
  8394. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8395. }
  8396. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8397. function serializeAsVector2(sourceName) {
  8398. return generateSerializableMember(4, sourceName); // vector2 member
  8399. }
  8400. BABYLON.serializeAsVector2 = serializeAsVector2;
  8401. function serializeAsVector3(sourceName) {
  8402. return generateSerializableMember(5, sourceName); // vector3 member
  8403. }
  8404. BABYLON.serializeAsVector3 = serializeAsVector3;
  8405. function serializeAsMeshReference(sourceName) {
  8406. return generateSerializableMember(6, sourceName); // mesh reference member
  8407. }
  8408. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8409. function serializeAsColorCurves(sourceName) {
  8410. return generateSerializableMember(7, sourceName); // color curves
  8411. }
  8412. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8413. function serializeAsColor4(sourceName) {
  8414. return generateSerializableMember(8, sourceName); // color 4
  8415. }
  8416. BABYLON.serializeAsColor4 = serializeAsColor4;
  8417. function serializeAsImageProcessingConfiguration(sourceName) {
  8418. return generateSerializableMember(9, sourceName); // image processing
  8419. }
  8420. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8421. function serializeAsQuaternion(sourceName) {
  8422. return generateSerializableMember(10, sourceName); // quaternion member
  8423. }
  8424. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8425. /**
  8426. * Decorator used to define property that can be serialized as reference to a camera
  8427. * @param sourceName defines the name of the property to decorate
  8428. */
  8429. function serializeAsCameraReference(sourceName) {
  8430. return generateSerializableMember(11, sourceName); // camera reference member
  8431. }
  8432. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8433. /**
  8434. * Class used to help serialization objects
  8435. */
  8436. var SerializationHelper = /** @class */ (function () {
  8437. function SerializationHelper() {
  8438. }
  8439. /**
  8440. * Static function used to serialized a specific entity
  8441. * @param entity defines the entity to serialize
  8442. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8443. * @returns a JSON compatible object representing the serialization of the entity
  8444. */
  8445. SerializationHelper.Serialize = function (entity, serializationObject) {
  8446. if (!serializationObject) {
  8447. serializationObject = {};
  8448. }
  8449. // Tags
  8450. if (BABYLON.Tags) {
  8451. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8452. }
  8453. var serializedProperties = getMergedStore(entity);
  8454. // Properties
  8455. for (var property in serializedProperties) {
  8456. var propertyDescriptor = serializedProperties[property];
  8457. var targetPropertyName = propertyDescriptor.sourceName || property;
  8458. var propertyType = propertyDescriptor.type;
  8459. var sourceProperty = entity[property];
  8460. if (sourceProperty !== undefined && sourceProperty !== null) {
  8461. switch (propertyType) {
  8462. case 0: // Value
  8463. serializationObject[targetPropertyName] = sourceProperty;
  8464. break;
  8465. case 1: // Texture
  8466. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8467. break;
  8468. case 2: // Color3
  8469. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8470. break;
  8471. case 3: // FresnelParameters
  8472. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8473. break;
  8474. case 4: // Vector2
  8475. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8476. break;
  8477. case 5: // Vector3
  8478. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8479. break;
  8480. case 6: // Mesh reference
  8481. serializationObject[targetPropertyName] = sourceProperty.id;
  8482. break;
  8483. case 7: // Color Curves
  8484. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8485. break;
  8486. case 8: // Color 4
  8487. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8488. break;
  8489. case 9: // Image Processing
  8490. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8491. break;
  8492. case 10: // Quaternion
  8493. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8494. break;
  8495. case 11: // Camera reference
  8496. serializationObject[targetPropertyName] = sourceProperty.id;
  8497. break;
  8498. }
  8499. }
  8500. }
  8501. return serializationObject;
  8502. };
  8503. /**
  8504. * Creates a new entity from a serialization data object
  8505. * @param creationFunction defines a function used to instanciated the new entity
  8506. * @param source defines the source serialization data
  8507. * @param scene defines the hosting scene
  8508. * @param rootUrl defines the root url for resources
  8509. * @returns a new entity
  8510. */
  8511. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8512. if (rootUrl === void 0) { rootUrl = null; }
  8513. var destination = creationFunction();
  8514. if (!rootUrl) {
  8515. rootUrl = "";
  8516. }
  8517. // Tags
  8518. if (BABYLON.Tags) {
  8519. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8520. }
  8521. var classStore = getMergedStore(destination);
  8522. // Properties
  8523. for (var property in classStore) {
  8524. var propertyDescriptor = classStore[property];
  8525. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8526. var propertyType = propertyDescriptor.type;
  8527. if (sourceProperty !== undefined && sourceProperty !== null) {
  8528. var dest = destination;
  8529. switch (propertyType) {
  8530. case 0: // Value
  8531. dest[property] = sourceProperty;
  8532. break;
  8533. case 1: // Texture
  8534. if (scene) {
  8535. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8536. }
  8537. break;
  8538. case 2: // Color3
  8539. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8540. break;
  8541. case 3: // FresnelParameters
  8542. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8543. break;
  8544. case 4: // Vector2
  8545. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8546. break;
  8547. case 5: // Vector3
  8548. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8549. break;
  8550. case 6: // Mesh reference
  8551. if (scene) {
  8552. dest[property] = scene.getLastMeshByID(sourceProperty);
  8553. }
  8554. break;
  8555. case 7: // Color Curves
  8556. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8557. break;
  8558. case 8: // Color 4
  8559. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8560. break;
  8561. case 9: // Image Processing
  8562. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8563. break;
  8564. case 10: // Quaternion
  8565. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8566. break;
  8567. case 11: // Camera reference
  8568. if (scene) {
  8569. dest[property] = scene.getCameraByID(sourceProperty);
  8570. }
  8571. break;
  8572. }
  8573. }
  8574. }
  8575. return destination;
  8576. };
  8577. /**
  8578. * Clones an object
  8579. * @param creationFunction defines the function used to instanciate the new object
  8580. * @param source defines the source object
  8581. * @returns the cloned object
  8582. */
  8583. SerializationHelper.Clone = function (creationFunction, source) {
  8584. return _copySource(creationFunction, source, false);
  8585. };
  8586. /**
  8587. * Instanciates a new object based on a source one (some data will be shared between both object)
  8588. * @param creationFunction defines the function used to instanciate the new object
  8589. * @param source defines the source object
  8590. * @returns the new object
  8591. */
  8592. SerializationHelper.Instanciate = function (creationFunction, source) {
  8593. return _copySource(creationFunction, source, true);
  8594. };
  8595. return SerializationHelper;
  8596. }());
  8597. BABYLON.SerializationHelper = SerializationHelper;
  8598. })(BABYLON || (BABYLON = {}));
  8599. //# sourceMappingURL=babylon.decorators.js.map
  8600. var BABYLON;
  8601. (function (BABYLON) {
  8602. /**
  8603. * Wrapper class for promise with external resolve and reject.
  8604. */
  8605. var Deferred = /** @class */ (function () {
  8606. /**
  8607. * Constructor for this deferred object.
  8608. */
  8609. function Deferred() {
  8610. var _this = this;
  8611. this.promise = new Promise(function (resolve, reject) {
  8612. _this._resolve = resolve;
  8613. _this._reject = reject;
  8614. });
  8615. }
  8616. Object.defineProperty(Deferred.prototype, "resolve", {
  8617. /**
  8618. * The resolve method of the promise associated with this deferred object.
  8619. */
  8620. get: function () {
  8621. return this._resolve;
  8622. },
  8623. enumerable: true,
  8624. configurable: true
  8625. });
  8626. Object.defineProperty(Deferred.prototype, "reject", {
  8627. /**
  8628. * The reject method of the promise associated with this deferred object.
  8629. */
  8630. get: function () {
  8631. return this._reject;
  8632. },
  8633. enumerable: true,
  8634. configurable: true
  8635. });
  8636. return Deferred;
  8637. }());
  8638. BABYLON.Deferred = Deferred;
  8639. })(BABYLON || (BABYLON = {}));
  8640. //# sourceMappingURL=babylon.deferred.js.map
  8641. var BABYLON;
  8642. (function (BABYLON) {
  8643. /**
  8644. * A class serves as a medium between the observable and its observers
  8645. */
  8646. var EventState = /** @class */ (function () {
  8647. /**
  8648. * Create a new EventState
  8649. * @param mask defines the mask associated with this state
  8650. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8651. * @param target defines the original target of the state
  8652. * @param currentTarget defines the current target of the state
  8653. */
  8654. function EventState(mask, skipNextObservers, target, currentTarget) {
  8655. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8656. this.initalize(mask, skipNextObservers, target, currentTarget);
  8657. }
  8658. /**
  8659. * Initialize the current event state
  8660. * @param mask defines the mask associated with this state
  8661. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8662. * @param target defines the original target of the state
  8663. * @param currentTarget defines the current target of the state
  8664. * @returns the current event state
  8665. */
  8666. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8667. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8668. this.mask = mask;
  8669. this.skipNextObservers = skipNextObservers;
  8670. this.target = target;
  8671. this.currentTarget = currentTarget;
  8672. return this;
  8673. };
  8674. return EventState;
  8675. }());
  8676. BABYLON.EventState = EventState;
  8677. /**
  8678. * Represent an Observer registered to a given Observable object.
  8679. */
  8680. var Observer = /** @class */ (function () {
  8681. /**
  8682. * Creates a new observer
  8683. * @param callback defines the callback to call when the observer is notified
  8684. * @param mask defines the mask of the observer (used to filter notifications)
  8685. * @param scope defines the current scope used to restore the JS context
  8686. */
  8687. function Observer(
  8688. /**
  8689. * Defines the callback to call when the observer is notified
  8690. */
  8691. callback,
  8692. /**
  8693. * Defines the mask of the observer (used to filter notifications)
  8694. */
  8695. mask,
  8696. /**
  8697. * Defines the current scope used to restore the JS context
  8698. */
  8699. scope) {
  8700. if (scope === void 0) { scope = null; }
  8701. this.callback = callback;
  8702. this.mask = mask;
  8703. this.scope = scope;
  8704. /** @hidden */
  8705. this._willBeUnregistered = false;
  8706. /**
  8707. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8708. */
  8709. this.unregisterOnNextCall = false;
  8710. }
  8711. return Observer;
  8712. }());
  8713. BABYLON.Observer = Observer;
  8714. /**
  8715. * Represent a list of observers registered to multiple Observables object.
  8716. */
  8717. var MultiObserver = /** @class */ (function () {
  8718. function MultiObserver() {
  8719. }
  8720. /**
  8721. * Release associated resources
  8722. */
  8723. MultiObserver.prototype.dispose = function () {
  8724. if (this._observers && this._observables) {
  8725. for (var index = 0; index < this._observers.length; index++) {
  8726. this._observables[index].remove(this._observers[index]);
  8727. }
  8728. }
  8729. this._observers = null;
  8730. this._observables = null;
  8731. };
  8732. /**
  8733. * Raise a callback when one of the observable will notify
  8734. * @param observables defines a list of observables to watch
  8735. * @param callback defines the callback to call on notification
  8736. * @param mask defines the mask used to filter notifications
  8737. * @param scope defines the current scope used to restore the JS context
  8738. * @returns the new MultiObserver
  8739. */
  8740. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8741. if (mask === void 0) { mask = -1; }
  8742. if (scope === void 0) { scope = null; }
  8743. var result = new MultiObserver();
  8744. result._observers = new Array();
  8745. result._observables = observables;
  8746. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8747. var observable = observables_1[_i];
  8748. var observer = observable.add(callback, mask, false, scope);
  8749. if (observer) {
  8750. result._observers.push(observer);
  8751. }
  8752. }
  8753. return result;
  8754. };
  8755. return MultiObserver;
  8756. }());
  8757. BABYLON.MultiObserver = MultiObserver;
  8758. /**
  8759. * The Observable class is a simple implementation of the Observable pattern.
  8760. *
  8761. * 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.
  8762. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8763. * 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).
  8764. * 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.
  8765. */
  8766. var Observable = /** @class */ (function () {
  8767. /**
  8768. * Creates a new observable
  8769. * @param onObserverAdded defines a callback to call when a new observer is added
  8770. */
  8771. function Observable(onObserverAdded) {
  8772. this._observers = new Array();
  8773. this._eventState = new EventState(0);
  8774. if (onObserverAdded) {
  8775. this._onObserverAdded = onObserverAdded;
  8776. }
  8777. }
  8778. /**
  8779. * Create a new Observer with the specified callback
  8780. * @param callback the callback that will be executed for that Observer
  8781. * @param mask the mask used to filter observers
  8782. * @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.
  8783. * @param scope optional scope for the callback to be called from
  8784. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8785. * @returns the new observer created for the callback
  8786. */
  8787. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8788. if (mask === void 0) { mask = -1; }
  8789. if (insertFirst === void 0) { insertFirst = false; }
  8790. if (scope === void 0) { scope = null; }
  8791. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8792. if (!callback) {
  8793. return null;
  8794. }
  8795. var observer = new Observer(callback, mask, scope);
  8796. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8797. if (insertFirst) {
  8798. this._observers.unshift(observer);
  8799. }
  8800. else {
  8801. this._observers.push(observer);
  8802. }
  8803. if (this._onObserverAdded) {
  8804. this._onObserverAdded(observer);
  8805. }
  8806. return observer;
  8807. };
  8808. /**
  8809. * Create a new Observer with the specified callback and unregisters after the next notification
  8810. * @param callback the callback that will be executed for that Observer
  8811. * @returns the new observer created for the callback
  8812. */
  8813. Observable.prototype.addOnce = function (callback) {
  8814. return this.add(callback, undefined, undefined, undefined, true);
  8815. };
  8816. /**
  8817. * Remove an Observer from the Observable object
  8818. * @param observer the instance of the Observer to remove
  8819. * @returns false if it doesn't belong to this Observable
  8820. */
  8821. Observable.prototype.remove = function (observer) {
  8822. if (!observer) {
  8823. return false;
  8824. }
  8825. var index = this._observers.indexOf(observer);
  8826. if (index !== -1) {
  8827. this._deferUnregister(observer);
  8828. return true;
  8829. }
  8830. return false;
  8831. };
  8832. /**
  8833. * Remove a callback from the Observable object
  8834. * @param callback the callback to remove
  8835. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8836. * @returns false if it doesn't belong to this Observable
  8837. */
  8838. Observable.prototype.removeCallback = function (callback, scope) {
  8839. for (var index = 0; index < this._observers.length; index++) {
  8840. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8841. this._deferUnregister(this._observers[index]);
  8842. return true;
  8843. }
  8844. }
  8845. return false;
  8846. };
  8847. Observable.prototype._deferUnregister = function (observer) {
  8848. var _this = this;
  8849. observer.unregisterOnNextCall = false;
  8850. observer._willBeUnregistered = true;
  8851. BABYLON.Tools.SetImmediate(function () {
  8852. _this._remove(observer);
  8853. });
  8854. };
  8855. // This should only be called when not iterating over _observers to avoid callback skipping.
  8856. // Removes an observer from the _observer Array.
  8857. Observable.prototype._remove = function (observer) {
  8858. if (!observer) {
  8859. return false;
  8860. }
  8861. var index = this._observers.indexOf(observer);
  8862. if (index !== -1) {
  8863. this._observers.splice(index, 1);
  8864. return true;
  8865. }
  8866. return false;
  8867. };
  8868. /**
  8869. * Notify all Observers by calling their respective callback with the given data
  8870. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8871. * @param eventData defines the data to send to all observers
  8872. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8873. * @param target defines the original target of the state
  8874. * @param currentTarget defines the current target of the state
  8875. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8876. */
  8877. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8878. if (mask === void 0) { mask = -1; }
  8879. if (!this._observers.length) {
  8880. return true;
  8881. }
  8882. var state = this._eventState;
  8883. state.mask = mask;
  8884. state.target = target;
  8885. state.currentTarget = currentTarget;
  8886. state.skipNextObservers = false;
  8887. state.lastReturnValue = eventData;
  8888. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8889. var obs = _a[_i];
  8890. if (obs._willBeUnregistered) {
  8891. continue;
  8892. }
  8893. if (obs.mask & mask) {
  8894. if (obs.scope) {
  8895. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8896. }
  8897. else {
  8898. state.lastReturnValue = obs.callback(eventData, state);
  8899. }
  8900. if (obs.unregisterOnNextCall) {
  8901. this._deferUnregister(obs);
  8902. }
  8903. }
  8904. if (state.skipNextObservers) {
  8905. return false;
  8906. }
  8907. }
  8908. return true;
  8909. };
  8910. /**
  8911. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8912. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8913. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8914. * and it is crucial that all callbacks will be executed.
  8915. * The order of the callbacks is kept, callbacks are not executed parallel.
  8916. *
  8917. * @param eventData The data to be sent to each callback
  8918. * @param mask is used to filter observers defaults to -1
  8919. * @param target defines the callback target (see EventState)
  8920. * @param currentTarget defines he current object in the bubbling phase
  8921. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8922. */
  8923. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8924. var _this = this;
  8925. if (mask === void 0) { mask = -1; }
  8926. // create an empty promise
  8927. var p = Promise.resolve(eventData);
  8928. // no observers? return this promise.
  8929. if (!this._observers.length) {
  8930. return p;
  8931. }
  8932. var state = this._eventState;
  8933. state.mask = mask;
  8934. state.target = target;
  8935. state.currentTarget = currentTarget;
  8936. state.skipNextObservers = false;
  8937. // execute one callback after another (not using Promise.all, the order is important)
  8938. this._observers.forEach(function (obs) {
  8939. if (state.skipNextObservers) {
  8940. return;
  8941. }
  8942. if (obs._willBeUnregistered) {
  8943. return;
  8944. }
  8945. if (obs.mask & mask) {
  8946. if (obs.scope) {
  8947. p = p.then(function (lastReturnedValue) {
  8948. state.lastReturnValue = lastReturnedValue;
  8949. return obs.callback.apply(obs.scope, [eventData, state]);
  8950. });
  8951. }
  8952. else {
  8953. p = p.then(function (lastReturnedValue) {
  8954. state.lastReturnValue = lastReturnedValue;
  8955. return obs.callback(eventData, state);
  8956. });
  8957. }
  8958. if (obs.unregisterOnNextCall) {
  8959. _this._deferUnregister(obs);
  8960. }
  8961. }
  8962. });
  8963. // return the eventData
  8964. return p.then(function () { return eventData; });
  8965. };
  8966. /**
  8967. * Notify a specific observer
  8968. * @param observer defines the observer to notify
  8969. * @param eventData defines the data to be sent to each callback
  8970. * @param mask is used to filter observers defaults to -1
  8971. */
  8972. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8973. if (mask === void 0) { mask = -1; }
  8974. var state = this._eventState;
  8975. state.mask = mask;
  8976. state.skipNextObservers = false;
  8977. observer.callback(eventData, state);
  8978. };
  8979. /**
  8980. * Gets a boolean indicating if the observable has at least one observer
  8981. * @returns true is the Observable has at least one Observer registered
  8982. */
  8983. Observable.prototype.hasObservers = function () {
  8984. return this._observers.length > 0;
  8985. };
  8986. /**
  8987. * Clear the list of observers
  8988. */
  8989. Observable.prototype.clear = function () {
  8990. this._observers = new Array();
  8991. this._onObserverAdded = null;
  8992. };
  8993. /**
  8994. * Clone the current observable
  8995. * @returns a new observable
  8996. */
  8997. Observable.prototype.clone = function () {
  8998. var result = new Observable();
  8999. result._observers = this._observers.slice(0);
  9000. return result;
  9001. };
  9002. /**
  9003. * Does this observable handles observer registered with a given mask
  9004. * @param mask defines the mask to be tested
  9005. * @return whether or not one observer registered with the given mask is handeled
  9006. **/
  9007. Observable.prototype.hasSpecificMask = function (mask) {
  9008. if (mask === void 0) { mask = -1; }
  9009. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9010. var obs = _a[_i];
  9011. if (obs.mask & mask || obs.mask === mask) {
  9012. return true;
  9013. }
  9014. }
  9015. return false;
  9016. };
  9017. return Observable;
  9018. }());
  9019. BABYLON.Observable = Observable;
  9020. })(BABYLON || (BABYLON = {}));
  9021. //# sourceMappingURL=babylon.observable.js.map
  9022. var BABYLON;
  9023. (function (BABYLON) {
  9024. /**
  9025. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9026. */
  9027. var SmartArray = /** @class */ (function () {
  9028. /**
  9029. * Instantiates a Smart Array.
  9030. * @param capacity defines the default capacity of the array.
  9031. */
  9032. function SmartArray(capacity) {
  9033. /**
  9034. * The active length of the array.
  9035. */
  9036. this.length = 0;
  9037. this.data = new Array(capacity);
  9038. this._id = SmartArray._GlobalId++;
  9039. }
  9040. /**
  9041. * Pushes a value at the end of the active data.
  9042. * @param value defines the object to push in the array.
  9043. */
  9044. SmartArray.prototype.push = function (value) {
  9045. this.data[this.length++] = value;
  9046. if (this.length > this.data.length) {
  9047. this.data.length *= 2;
  9048. }
  9049. };
  9050. /**
  9051. * Iterates over the active data and apply the lambda to them.
  9052. * @param func defines the action to apply on each value.
  9053. */
  9054. SmartArray.prototype.forEach = function (func) {
  9055. for (var index = 0; index < this.length; index++) {
  9056. func(this.data[index]);
  9057. }
  9058. };
  9059. /**
  9060. * Sorts the full sets of data.
  9061. * @param compareFn defines the comparison function to apply.
  9062. */
  9063. SmartArray.prototype.sort = function (compareFn) {
  9064. this.data.sort(compareFn);
  9065. };
  9066. /**
  9067. * Resets the active data to an empty array.
  9068. */
  9069. SmartArray.prototype.reset = function () {
  9070. this.length = 0;
  9071. };
  9072. /**
  9073. * Releases all the data from the array as well as the array.
  9074. */
  9075. SmartArray.prototype.dispose = function () {
  9076. this.reset();
  9077. if (this.data) {
  9078. this.data.length = 0;
  9079. this.data = [];
  9080. }
  9081. };
  9082. /**
  9083. * Concats the active data with a given array.
  9084. * @param array defines the data to concatenate with.
  9085. */
  9086. SmartArray.prototype.concat = function (array) {
  9087. if (array.length === 0) {
  9088. return;
  9089. }
  9090. if (this.length + array.length > this.data.length) {
  9091. this.data.length = (this.length + array.length) * 2;
  9092. }
  9093. for (var index = 0; index < array.length; index++) {
  9094. this.data[this.length++] = (array.data || array)[index];
  9095. }
  9096. };
  9097. /**
  9098. * Returns the position of a value in the active data.
  9099. * @param value defines the value to find the index for
  9100. * @returns the index if found in the active data otherwise -1
  9101. */
  9102. SmartArray.prototype.indexOf = function (value) {
  9103. var position = this.data.indexOf(value);
  9104. if (position >= this.length) {
  9105. return -1;
  9106. }
  9107. return position;
  9108. };
  9109. /**
  9110. * Returns whether an element is part of the active data.
  9111. * @param value defines the value to look for
  9112. * @returns true if found in the active data otherwise false
  9113. */
  9114. SmartArray.prototype.contains = function (value) {
  9115. return this.indexOf(value) !== -1;
  9116. };
  9117. // Statics
  9118. SmartArray._GlobalId = 0;
  9119. return SmartArray;
  9120. }());
  9121. BABYLON.SmartArray = SmartArray;
  9122. /**
  9123. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9124. * The data in this array can only be present once
  9125. */
  9126. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9127. __extends(SmartArrayNoDuplicate, _super);
  9128. function SmartArrayNoDuplicate() {
  9129. var _this = _super !== null && _super.apply(this, arguments) || this;
  9130. _this._duplicateId = 0;
  9131. return _this;
  9132. }
  9133. /**
  9134. * Pushes a value at the end of the active data.
  9135. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9136. * @param value defines the object to push in the array.
  9137. */
  9138. SmartArrayNoDuplicate.prototype.push = function (value) {
  9139. _super.prototype.push.call(this, value);
  9140. if (!value.__smartArrayFlags) {
  9141. value.__smartArrayFlags = {};
  9142. }
  9143. value.__smartArrayFlags[this._id] = this._duplicateId;
  9144. };
  9145. /**
  9146. * Pushes a value at the end of the active data.
  9147. * If the data is already present, it won t be added again
  9148. * @param value defines the object to push in the array.
  9149. * @returns true if added false if it was already present
  9150. */
  9151. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9152. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9153. return false;
  9154. }
  9155. this.push(value);
  9156. return true;
  9157. };
  9158. /**
  9159. * Resets the active data to an empty array.
  9160. */
  9161. SmartArrayNoDuplicate.prototype.reset = function () {
  9162. _super.prototype.reset.call(this);
  9163. this._duplicateId++;
  9164. };
  9165. /**
  9166. * Concats the active data with a given array.
  9167. * This ensures no dupplicate will be present in the result.
  9168. * @param array defines the data to concatenate with.
  9169. */
  9170. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9171. if (array.length === 0) {
  9172. return;
  9173. }
  9174. if (this.length + array.length > this.data.length) {
  9175. this.data.length = (this.length + array.length) * 2;
  9176. }
  9177. for (var index = 0; index < array.length; index++) {
  9178. var item = (array.data || array)[index];
  9179. this.pushNoDuplicate(item);
  9180. }
  9181. };
  9182. return SmartArrayNoDuplicate;
  9183. }(SmartArray));
  9184. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9185. })(BABYLON || (BABYLON = {}));
  9186. //# sourceMappingURL=babylon.smartArray.js.map
  9187. var BABYLON;
  9188. (function (BABYLON) {
  9189. /** Class used to store color4 gradient */
  9190. var ColorGradient = /** @class */ (function () {
  9191. function ColorGradient() {
  9192. }
  9193. /**
  9194. * Will get a color picked randomly between color1 and color2.
  9195. * If color2 is undefined then color1 will be used
  9196. * @param result defines the target Color4 to store the result in
  9197. */
  9198. ColorGradient.prototype.getColorToRef = function (result) {
  9199. if (!this.color2) {
  9200. result.copyFrom(this.color1);
  9201. return;
  9202. }
  9203. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9204. };
  9205. return ColorGradient;
  9206. }());
  9207. BABYLON.ColorGradient = ColorGradient;
  9208. /** Class used to store color 3 gradient */
  9209. var Color3Gradient = /** @class */ (function () {
  9210. function Color3Gradient() {
  9211. }
  9212. return Color3Gradient;
  9213. }());
  9214. BABYLON.Color3Gradient = Color3Gradient;
  9215. /** Class used to store factor gradient */
  9216. var FactorGradient = /** @class */ (function () {
  9217. function FactorGradient() {
  9218. }
  9219. /**
  9220. * Will get a number picked randomly between factor1 and factor2.
  9221. * If factor2 is undefined then factor1 will be used
  9222. * @returns the picked number
  9223. */
  9224. FactorGradient.prototype.getFactor = function () {
  9225. if (this.factor2 === undefined) {
  9226. return this.factor1;
  9227. }
  9228. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9229. };
  9230. return FactorGradient;
  9231. }());
  9232. BABYLON.FactorGradient = FactorGradient;
  9233. /**
  9234. * @ignore
  9235. * Application error to support additional information when loading a file
  9236. */
  9237. var LoadFileError = /** @class */ (function (_super) {
  9238. __extends(LoadFileError, _super);
  9239. /**
  9240. * Creates a new LoadFileError
  9241. * @param message defines the message of the error
  9242. * @param request defines the optional XHR request
  9243. */
  9244. function LoadFileError(message,
  9245. /** defines the optional XHR request */
  9246. request) {
  9247. var _this = _super.call(this, message) || this;
  9248. _this.request = request;
  9249. _this.name = "LoadFileError";
  9250. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9251. return _this;
  9252. }
  9253. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9254. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9255. // Polyfill for Object.setPrototypeOf if necessary.
  9256. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9257. return LoadFileError;
  9258. }(Error));
  9259. BABYLON.LoadFileError = LoadFileError;
  9260. /**
  9261. * Class used to define a retry strategy when error happens while loading assets
  9262. */
  9263. var RetryStrategy = /** @class */ (function () {
  9264. function RetryStrategy() {
  9265. }
  9266. /**
  9267. * Function used to defines an exponential back off strategy
  9268. * @param maxRetries defines the maximum number of retries (3 by default)
  9269. * @param baseInterval defines the interval between retries
  9270. * @returns the strategy function to use
  9271. */
  9272. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9273. if (maxRetries === void 0) { maxRetries = 3; }
  9274. if (baseInterval === void 0) { baseInterval = 500; }
  9275. return function (url, request, retryIndex) {
  9276. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9277. return -1;
  9278. }
  9279. return Math.pow(2, retryIndex) * baseInterval;
  9280. };
  9281. };
  9282. return RetryStrategy;
  9283. }());
  9284. BABYLON.RetryStrategy = RetryStrategy;
  9285. // Screenshots
  9286. var screenshotCanvas;
  9287. var cloneValue = function (source, destinationObject) {
  9288. if (!source)
  9289. return null;
  9290. if (source instanceof BABYLON.Mesh) {
  9291. return null;
  9292. }
  9293. if (source instanceof BABYLON.SubMesh) {
  9294. return source.clone(destinationObject);
  9295. }
  9296. else if (source.clone) {
  9297. return source.clone();
  9298. }
  9299. return null;
  9300. };
  9301. /**
  9302. * Class containing a set of static utilities functions
  9303. */
  9304. var Tools = /** @class */ (function () {
  9305. function Tools() {
  9306. }
  9307. /**
  9308. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9309. * @param u defines the coordinate on X axis
  9310. * @param v defines the coordinate on Y axis
  9311. * @param width defines the width of the source data
  9312. * @param height defines the height of the source data
  9313. * @param pixels defines the source byte array
  9314. * @param color defines the output color
  9315. */
  9316. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9317. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9318. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9319. var position = (wrappedU + wrappedV * width) * 4;
  9320. color.r = pixels[position] / 255;
  9321. color.g = pixels[position + 1] / 255;
  9322. color.b = pixels[position + 2] / 255;
  9323. color.a = pixels[position + 3] / 255;
  9324. };
  9325. /**
  9326. * Interpolates between a and b via alpha
  9327. * @param a The lower value (returned when alpha = 0)
  9328. * @param b The upper value (returned when alpha = 1)
  9329. * @param alpha The interpolation-factor
  9330. * @return The mixed value
  9331. */
  9332. Tools.Mix = function (a, b, alpha) {
  9333. return a * (1 - alpha) + b * alpha;
  9334. };
  9335. /**
  9336. * Tries to instantiate a new object from a given class name
  9337. * @param className defines the class name to instantiate
  9338. * @returns the new object or null if the system was not able to do the instantiation
  9339. */
  9340. Tools.Instantiate = function (className) {
  9341. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9342. return Tools.RegisteredExternalClasses[className];
  9343. }
  9344. var arr = className.split(".");
  9345. var fn = (window || this);
  9346. for (var i = 0, len = arr.length; i < len; i++) {
  9347. fn = fn[arr[i]];
  9348. }
  9349. if (typeof fn !== "function") {
  9350. return null;
  9351. }
  9352. return fn;
  9353. };
  9354. /**
  9355. * Provides a slice function that will work even on IE
  9356. * @param data defines the array to slice
  9357. * @param start defines the start of the data (optional)
  9358. * @param end defines the end of the data (optional)
  9359. * @returns the new sliced array
  9360. */
  9361. Tools.Slice = function (data, start, end) {
  9362. if (data.slice) {
  9363. return data.slice(start, end);
  9364. }
  9365. return Array.prototype.slice.call(data, start, end);
  9366. };
  9367. /**
  9368. * Polyfill for setImmediate
  9369. * @param action defines the action to execute after the current execution block
  9370. */
  9371. Tools.SetImmediate = function (action) {
  9372. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9373. window.setImmediate(action);
  9374. }
  9375. else {
  9376. setTimeout(action, 1);
  9377. }
  9378. };
  9379. /**
  9380. * Function indicating if a number is an exponent of 2
  9381. * @param value defines the value to test
  9382. * @returns true if the value is an exponent of 2
  9383. */
  9384. Tools.IsExponentOfTwo = function (value) {
  9385. var count = 1;
  9386. do {
  9387. count *= 2;
  9388. } while (count < value);
  9389. return count === value;
  9390. };
  9391. /**
  9392. * Returns the nearest 32-bit single precision float representation of a Number
  9393. * @param value A Number. If the parameter is of a different type, it will get converted
  9394. * to a number or to NaN if it cannot be converted
  9395. * @returns number
  9396. */
  9397. Tools.FloatRound = function (value) {
  9398. if (Math.fround) {
  9399. return Math.fround(value);
  9400. }
  9401. return (Tools._tmpFloatArray[0] = value);
  9402. };
  9403. /**
  9404. * Find the next highest power of two.
  9405. * @param x Number to start search from.
  9406. * @return Next highest power of two.
  9407. */
  9408. Tools.CeilingPOT = function (x) {
  9409. x--;
  9410. x |= x >> 1;
  9411. x |= x >> 2;
  9412. x |= x >> 4;
  9413. x |= x >> 8;
  9414. x |= x >> 16;
  9415. x++;
  9416. return x;
  9417. };
  9418. /**
  9419. * Find the next lowest power of two.
  9420. * @param x Number to start search from.
  9421. * @return Next lowest power of two.
  9422. */
  9423. Tools.FloorPOT = function (x) {
  9424. x = x | (x >> 1);
  9425. x = x | (x >> 2);
  9426. x = x | (x >> 4);
  9427. x = x | (x >> 8);
  9428. x = x | (x >> 16);
  9429. return x - (x >> 1);
  9430. };
  9431. /**
  9432. * Find the nearest power of two.
  9433. * @param x Number to start search from.
  9434. * @return Next nearest power of two.
  9435. */
  9436. Tools.NearestPOT = function (x) {
  9437. var c = Tools.CeilingPOT(x);
  9438. var f = Tools.FloorPOT(x);
  9439. return (c - x) > (x - f) ? f : c;
  9440. };
  9441. /**
  9442. * Get the closest exponent of two
  9443. * @param value defines the value to approximate
  9444. * @param max defines the maximum value to return
  9445. * @param mode defines how to define the closest value
  9446. * @returns closest exponent of two of the given value
  9447. */
  9448. Tools.GetExponentOfTwo = function (value, max, mode) {
  9449. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9450. var pot;
  9451. switch (mode) {
  9452. case BABYLON.Engine.SCALEMODE_FLOOR:
  9453. pot = Tools.FloorPOT(value);
  9454. break;
  9455. case BABYLON.Engine.SCALEMODE_NEAREST:
  9456. pot = Tools.NearestPOT(value);
  9457. break;
  9458. case BABYLON.Engine.SCALEMODE_CEILING:
  9459. default:
  9460. pot = Tools.CeilingPOT(value);
  9461. break;
  9462. }
  9463. return Math.min(pot, max);
  9464. };
  9465. /**
  9466. * Extracts the filename from a path
  9467. * @param path defines the path to use
  9468. * @returns the filename
  9469. */
  9470. Tools.GetFilename = function (path) {
  9471. var index = path.lastIndexOf("/");
  9472. if (index < 0)
  9473. return path;
  9474. return path.substring(index + 1);
  9475. };
  9476. /**
  9477. * Extracts the "folder" part of a path (everything before the filename).
  9478. * @param uri The URI to extract the info from
  9479. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9480. * @returns The "folder" part of the path
  9481. */
  9482. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9483. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9484. var index = uri.lastIndexOf("/");
  9485. if (index < 0) {
  9486. if (returnUnchangedIfNoSlash) {
  9487. return uri;
  9488. }
  9489. return "";
  9490. }
  9491. return uri.substring(0, index + 1);
  9492. };
  9493. /**
  9494. * Extracts text content from a DOM element hierarchy
  9495. * @param element defines the root element
  9496. * @returns a string
  9497. */
  9498. Tools.GetDOMTextContent = function (element) {
  9499. var result = "";
  9500. var child = element.firstChild;
  9501. while (child) {
  9502. if (child.nodeType === 3) {
  9503. result += child.textContent;
  9504. }
  9505. child = child.nextSibling;
  9506. }
  9507. return result;
  9508. };
  9509. /**
  9510. * Convert an angle in radians to degrees
  9511. * @param angle defines the angle to convert
  9512. * @returns the angle in degrees
  9513. */
  9514. Tools.ToDegrees = function (angle) {
  9515. return angle * 180 / Math.PI;
  9516. };
  9517. /**
  9518. * Convert an angle in degrees to radians
  9519. * @param angle defines the angle to convert
  9520. * @returns the angle in radians
  9521. */
  9522. Tools.ToRadians = function (angle) {
  9523. return angle * Math.PI / 180;
  9524. };
  9525. /**
  9526. * Encode a buffer to a base64 string
  9527. * @param buffer defines the buffer to encode
  9528. * @returns the encoded string
  9529. */
  9530. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9531. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9532. var output = "";
  9533. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9534. var i = 0;
  9535. var bytes = new Uint8Array(buffer);
  9536. while (i < bytes.length) {
  9537. chr1 = bytes[i++];
  9538. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9539. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9540. enc1 = chr1 >> 2;
  9541. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9542. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9543. enc4 = chr3 & 63;
  9544. if (isNaN(chr2)) {
  9545. enc3 = enc4 = 64;
  9546. }
  9547. else if (isNaN(chr3)) {
  9548. enc4 = 64;
  9549. }
  9550. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9551. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9552. }
  9553. return "data:image/png;base64," + output;
  9554. };
  9555. /**
  9556. * Extracts minimum and maximum values from a list of indexed positions
  9557. * @param positions defines the positions to use
  9558. * @param indices defines the indices to the positions
  9559. * @param indexStart defines the start index
  9560. * @param indexCount defines the end index
  9561. * @param bias defines bias value to add to the result
  9562. * @return minimum and maximum values
  9563. */
  9564. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9565. if (bias === void 0) { bias = null; }
  9566. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9567. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9568. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9569. var offset = indices[index] * 3;
  9570. var x = positions[offset];
  9571. var y = positions[offset + 1];
  9572. var z = positions[offset + 2];
  9573. minimum.minimizeInPlaceFromFloats(x, y, z);
  9574. maximum.maximizeInPlaceFromFloats(x, y, z);
  9575. }
  9576. if (bias) {
  9577. minimum.x -= minimum.x * bias.x + bias.y;
  9578. minimum.y -= minimum.y * bias.x + bias.y;
  9579. minimum.z -= minimum.z * bias.x + bias.y;
  9580. maximum.x += maximum.x * bias.x + bias.y;
  9581. maximum.y += maximum.y * bias.x + bias.y;
  9582. maximum.z += maximum.z * bias.x + bias.y;
  9583. }
  9584. return {
  9585. minimum: minimum,
  9586. maximum: maximum
  9587. };
  9588. };
  9589. /**
  9590. * Extracts minimum and maximum values from a list of positions
  9591. * @param positions defines the positions to use
  9592. * @param start defines the start index in the positions array
  9593. * @param count defines the number of positions to handle
  9594. * @param bias defines bias value to add to the result
  9595. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9596. * @return minimum and maximum values
  9597. */
  9598. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9599. if (bias === void 0) { bias = null; }
  9600. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9601. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9602. if (!stride) {
  9603. stride = 3;
  9604. }
  9605. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9606. var x = positions[offset];
  9607. var y = positions[offset + 1];
  9608. var z = positions[offset + 2];
  9609. minimum.minimizeInPlaceFromFloats(x, y, z);
  9610. maximum.maximizeInPlaceFromFloats(x, y, z);
  9611. }
  9612. if (bias) {
  9613. minimum.x -= minimum.x * bias.x + bias.y;
  9614. minimum.y -= minimum.y * bias.x + bias.y;
  9615. minimum.z -= minimum.z * bias.x + bias.y;
  9616. maximum.x += maximum.x * bias.x + bias.y;
  9617. maximum.y += maximum.y * bias.x + bias.y;
  9618. maximum.z += maximum.z * bias.x + bias.y;
  9619. }
  9620. return {
  9621. minimum: minimum,
  9622. maximum: maximum
  9623. };
  9624. };
  9625. /**
  9626. * Returns an array if obj is not an array
  9627. * @param obj defines the object to evaluate as an array
  9628. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9629. * @returns either obj directly if obj is an array or a new array containing obj
  9630. */
  9631. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9632. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9633. return null;
  9634. return Array.isArray(obj) ? obj : [obj];
  9635. };
  9636. /**
  9637. * Gets the pointer prefix to use
  9638. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9639. */
  9640. Tools.GetPointerPrefix = function () {
  9641. var eventPrefix = "pointer";
  9642. // Check if pointer events are supported
  9643. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9644. eventPrefix = "mouse";
  9645. }
  9646. return eventPrefix;
  9647. };
  9648. /**
  9649. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9650. * @param func - the function to be called
  9651. * @param requester - the object that will request the next frame. Falls back to window.
  9652. * @returns frame number
  9653. */
  9654. Tools.QueueNewFrame = function (func, requester) {
  9655. if (!Tools.IsWindowObjectExist()) {
  9656. return setTimeout(func, 16);
  9657. }
  9658. if (!requester) {
  9659. requester = window;
  9660. }
  9661. if (requester.requestAnimationFrame) {
  9662. return requester.requestAnimationFrame(func);
  9663. }
  9664. else if (requester.msRequestAnimationFrame) {
  9665. return requester.msRequestAnimationFrame(func);
  9666. }
  9667. else if (requester.webkitRequestAnimationFrame) {
  9668. return requester.webkitRequestAnimationFrame(func);
  9669. }
  9670. else if (requester.mozRequestAnimationFrame) {
  9671. return requester.mozRequestAnimationFrame(func);
  9672. }
  9673. else if (requester.oRequestAnimationFrame) {
  9674. return requester.oRequestAnimationFrame(func);
  9675. }
  9676. else {
  9677. return window.setTimeout(func, 16);
  9678. }
  9679. };
  9680. /**
  9681. * Ask the browser to promote the current element to fullscreen rendering mode
  9682. * @param element defines the DOM element to promote
  9683. */
  9684. Tools.RequestFullscreen = function (element) {
  9685. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9686. if (!requestFunction)
  9687. return;
  9688. requestFunction.call(element);
  9689. };
  9690. /**
  9691. * Asks the browser to exit fullscreen mode
  9692. */
  9693. Tools.ExitFullscreen = function () {
  9694. if (document.exitFullscreen) {
  9695. document.exitFullscreen();
  9696. }
  9697. else if (document.mozCancelFullScreen) {
  9698. document.mozCancelFullScreen();
  9699. }
  9700. else if (document.webkitCancelFullScreen) {
  9701. document.webkitCancelFullScreen();
  9702. }
  9703. else if (document.msCancelFullScreen) {
  9704. document.msCancelFullScreen();
  9705. }
  9706. };
  9707. /**
  9708. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9709. * @param url define the url we are trying
  9710. * @param element define the dom element where to configure the cors policy
  9711. */
  9712. Tools.SetCorsBehavior = function (url, element) {
  9713. if (url && url.indexOf("data:") === 0) {
  9714. return;
  9715. }
  9716. if (Tools.CorsBehavior) {
  9717. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9718. element.crossOrigin = Tools.CorsBehavior;
  9719. }
  9720. else {
  9721. var result = Tools.CorsBehavior(url);
  9722. if (result) {
  9723. element.crossOrigin = result;
  9724. }
  9725. }
  9726. }
  9727. };
  9728. // External files
  9729. /**
  9730. * Removes unwanted characters from an url
  9731. * @param url defines the url to clean
  9732. * @returns the cleaned url
  9733. */
  9734. Tools.CleanUrl = function (url) {
  9735. url = url.replace(/#/mg, "%23");
  9736. return url;
  9737. };
  9738. /**
  9739. * Loads an image as an HTMLImageElement.
  9740. * @param input url string, ArrayBuffer, or Blob to load
  9741. * @param onLoad callback called when the image successfully loads
  9742. * @param onError callback called when the image fails to load
  9743. * @param database database for caching
  9744. * @returns the HTMLImageElement of the loaded image
  9745. */
  9746. Tools.LoadImage = function (input, onLoad, onError, database) {
  9747. var url;
  9748. var usingObjectURL = false;
  9749. if (input instanceof ArrayBuffer) {
  9750. url = URL.createObjectURL(new Blob([input]));
  9751. usingObjectURL = true;
  9752. }
  9753. else if (input instanceof Blob) {
  9754. url = URL.createObjectURL(input);
  9755. usingObjectURL = true;
  9756. }
  9757. else {
  9758. url = Tools.CleanUrl(input);
  9759. url = Tools.PreprocessUrl(input);
  9760. }
  9761. var img = new Image();
  9762. Tools.SetCorsBehavior(url, img);
  9763. var loadHandler = function () {
  9764. if (usingObjectURL && img.src) {
  9765. URL.revokeObjectURL(img.src);
  9766. }
  9767. img.removeEventListener("load", loadHandler);
  9768. img.removeEventListener("error", errorHandler);
  9769. onLoad(img);
  9770. };
  9771. var errorHandler = function (err) {
  9772. if (usingObjectURL && img.src) {
  9773. URL.revokeObjectURL(img.src);
  9774. }
  9775. img.removeEventListener("load", loadHandler);
  9776. img.removeEventListener("error", errorHandler);
  9777. Tools.Error("Error while trying to load image: " + input);
  9778. if (onError) {
  9779. onError("Error while trying to load image: " + input, err);
  9780. }
  9781. };
  9782. img.addEventListener("load", loadHandler);
  9783. img.addEventListener("error", errorHandler);
  9784. var noIndexedDB = function () {
  9785. img.src = url;
  9786. };
  9787. var loadFromIndexedDB = function () {
  9788. if (database) {
  9789. database.loadImageFromDB(url, img);
  9790. }
  9791. };
  9792. //ANY database to do!
  9793. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9794. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9795. }
  9796. else {
  9797. if (url.indexOf("file:") !== -1) {
  9798. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9799. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9800. try {
  9801. var blobURL;
  9802. try {
  9803. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9804. }
  9805. catch (ex) {
  9806. // Chrome doesn't support oneTimeOnly parameter
  9807. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9808. }
  9809. img.src = blobURL;
  9810. usingObjectURL = true;
  9811. }
  9812. catch (e) {
  9813. img.src = "";
  9814. }
  9815. return img;
  9816. }
  9817. }
  9818. noIndexedDB();
  9819. }
  9820. return img;
  9821. };
  9822. /**
  9823. * Loads a file
  9824. * @param url url string, ArrayBuffer, or Blob to load
  9825. * @param onSuccess callback called when the file successfully loads
  9826. * @param onProgress callback called while file is loading (if the server supports this mode)
  9827. * @param database database for caching
  9828. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9829. * @param onError callback called when the file fails to load
  9830. * @returns a file request object
  9831. */
  9832. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9833. url = Tools.CleanUrl(url);
  9834. url = Tools.PreprocessUrl(url);
  9835. // If file and file input are set
  9836. if (url.indexOf("file:") !== -1) {
  9837. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9838. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9839. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9840. }
  9841. }
  9842. var loadUrl = Tools.BaseUrl + url;
  9843. var aborted = false;
  9844. var fileRequest = {
  9845. onCompleteObservable: new BABYLON.Observable(),
  9846. abort: function () { return aborted = true; },
  9847. };
  9848. var requestFile = function () {
  9849. var request = new XMLHttpRequest();
  9850. var retryHandle = null;
  9851. fileRequest.abort = function () {
  9852. aborted = true;
  9853. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9854. request.abort();
  9855. }
  9856. if (retryHandle !== null) {
  9857. clearTimeout(retryHandle);
  9858. retryHandle = null;
  9859. }
  9860. };
  9861. var retryLoop = function (retryIndex) {
  9862. request.open('GET', loadUrl, true);
  9863. if (useArrayBuffer) {
  9864. request.responseType = "arraybuffer";
  9865. }
  9866. if (onProgress) {
  9867. request.addEventListener("progress", onProgress);
  9868. }
  9869. var onLoadEnd = function () {
  9870. request.removeEventListener("loadend", onLoadEnd);
  9871. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9872. fileRequest.onCompleteObservable.clear();
  9873. };
  9874. request.addEventListener("loadend", onLoadEnd);
  9875. var onReadyStateChange = function () {
  9876. if (aborted) {
  9877. return;
  9878. }
  9879. // In case of undefined state in some browsers.
  9880. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9881. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9882. request.removeEventListener("readystatechange", onReadyStateChange);
  9883. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9884. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9885. return;
  9886. }
  9887. var retryStrategy = Tools.DefaultRetryStrategy;
  9888. if (retryStrategy) {
  9889. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9890. if (waitTime !== -1) {
  9891. // Prevent the request from completing for retry.
  9892. request.removeEventListener("loadend", onLoadEnd);
  9893. request = new XMLHttpRequest();
  9894. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9895. return;
  9896. }
  9897. }
  9898. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9899. if (onError) {
  9900. onError(request, e);
  9901. }
  9902. else {
  9903. throw e;
  9904. }
  9905. }
  9906. };
  9907. request.addEventListener("readystatechange", onReadyStateChange);
  9908. request.send();
  9909. };
  9910. retryLoop(0);
  9911. };
  9912. // Caching all files
  9913. if (database && database.enableSceneOffline) {
  9914. var noIndexedDB_1 = function (request) {
  9915. if (request && request.status > 400) {
  9916. if (onError) {
  9917. onError(request);
  9918. }
  9919. }
  9920. else {
  9921. if (!aborted) {
  9922. requestFile();
  9923. }
  9924. }
  9925. };
  9926. var loadFromIndexedDB = function () {
  9927. // TODO: database needs to support aborting and should return a IFileRequest
  9928. if (aborted) {
  9929. return;
  9930. }
  9931. if (database) {
  9932. database.loadFileFromDB(url, function (data) {
  9933. if (!aborted) {
  9934. onSuccess(data);
  9935. }
  9936. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9937. }, onProgress ? function (event) {
  9938. if (!aborted) {
  9939. onProgress(event);
  9940. }
  9941. } : undefined, noIndexedDB_1, useArrayBuffer);
  9942. }
  9943. };
  9944. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9945. }
  9946. else {
  9947. requestFile();
  9948. }
  9949. return fileRequest;
  9950. };
  9951. /**
  9952. * Load a script (identified by an url). When the url returns, the
  9953. * content of this file is added into a new script element, attached to the DOM (body element)
  9954. * @param scriptUrl defines the url of the script to laod
  9955. * @param onSuccess defines the callback called when the script is loaded
  9956. * @param onError defines the callback to call if an error occurs
  9957. */
  9958. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9959. if (!Tools.IsWindowObjectExist()) {
  9960. return;
  9961. }
  9962. var head = document.getElementsByTagName('head')[0];
  9963. var script = document.createElement('script');
  9964. script.type = 'text/javascript';
  9965. script.src = scriptUrl;
  9966. script.onload = function () {
  9967. if (onSuccess) {
  9968. onSuccess();
  9969. }
  9970. };
  9971. script.onerror = function (e) {
  9972. if (onError) {
  9973. onError("Unable to load script '" + scriptUrl + "'", e);
  9974. }
  9975. };
  9976. head.appendChild(script);
  9977. };
  9978. /**
  9979. * Loads a file from a blob
  9980. * @param fileToLoad defines the blob to use
  9981. * @param callback defines the callback to call when data is loaded
  9982. * @param progressCallback defines the callback to call during loading process
  9983. * @returns a file request object
  9984. */
  9985. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9986. var reader = new FileReader();
  9987. var request = {
  9988. onCompleteObservable: new BABYLON.Observable(),
  9989. abort: function () { return reader.abort(); },
  9990. };
  9991. reader.onloadend = function (e) {
  9992. request.onCompleteObservable.notifyObservers(request);
  9993. };
  9994. reader.onload = function (e) {
  9995. //target doesn't have result from ts 1.3
  9996. callback(e.target['result']);
  9997. };
  9998. reader.onprogress = progressCallback;
  9999. reader.readAsDataURL(fileToLoad);
  10000. return request;
  10001. };
  10002. /**
  10003. * Loads a file
  10004. * @param fileToLoad defines the file to load
  10005. * @param callback defines the callback to call when data is loaded
  10006. * @param progressCallBack defines the callback to call during loading process
  10007. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10008. * @returns a file request object
  10009. */
  10010. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10011. var reader = new FileReader();
  10012. var request = {
  10013. onCompleteObservable: new BABYLON.Observable(),
  10014. abort: function () { return reader.abort(); },
  10015. };
  10016. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10017. reader.onerror = function (e) {
  10018. Tools.Log("Error while reading file: " + fileToLoad.name);
  10019. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10020. };
  10021. reader.onload = function (e) {
  10022. //target doesn't have result from ts 1.3
  10023. callback(e.target['result']);
  10024. };
  10025. if (progressCallBack) {
  10026. reader.onprogress = progressCallBack;
  10027. }
  10028. if (!useArrayBuffer) {
  10029. // Asynchronous read
  10030. reader.readAsText(fileToLoad);
  10031. }
  10032. else {
  10033. reader.readAsArrayBuffer(fileToLoad);
  10034. }
  10035. return request;
  10036. };
  10037. /**
  10038. * Creates a data url from a given string content
  10039. * @param content defines the content to convert
  10040. * @returns the new data url link
  10041. */
  10042. Tools.FileAsURL = function (content) {
  10043. var fileBlob = new Blob([content]);
  10044. var url = window.URL || window.webkitURL;
  10045. var link = url.createObjectURL(fileBlob);
  10046. return link;
  10047. };
  10048. /**
  10049. * Format the given number to a specific decimal format
  10050. * @param value defines the number to format
  10051. * @param decimals defines the number of decimals to use
  10052. * @returns the formatted string
  10053. */
  10054. Tools.Format = function (value, decimals) {
  10055. if (decimals === void 0) { decimals = 2; }
  10056. return value.toFixed(decimals);
  10057. };
  10058. /**
  10059. * Checks if a given vector is inside a specific range
  10060. * @param v defines the vector to test
  10061. * @param min defines the minimum range
  10062. * @param max defines the maximum range
  10063. */
  10064. Tools.CheckExtends = function (v, min, max) {
  10065. if (v.x < min.x)
  10066. min.x = v.x;
  10067. if (v.y < min.y)
  10068. min.y = v.y;
  10069. if (v.z < min.z)
  10070. min.z = v.z;
  10071. if (v.x > max.x)
  10072. max.x = v.x;
  10073. if (v.y > max.y)
  10074. max.y = v.y;
  10075. if (v.z > max.z)
  10076. max.z = v.z;
  10077. };
  10078. /**
  10079. * Tries to copy an object by duplicating every property
  10080. * @param source defines the source object
  10081. * @param destination defines the target object
  10082. * @param doNotCopyList defines a list of properties to avoid
  10083. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10084. */
  10085. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10086. for (var prop in source) {
  10087. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10088. continue;
  10089. }
  10090. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10091. continue;
  10092. }
  10093. var sourceValue = source[prop];
  10094. var typeOfSourceValue = typeof sourceValue;
  10095. if (typeOfSourceValue === "function") {
  10096. continue;
  10097. }
  10098. try {
  10099. if (typeOfSourceValue === "object") {
  10100. if (sourceValue instanceof Array) {
  10101. destination[prop] = [];
  10102. if (sourceValue.length > 0) {
  10103. if (typeof sourceValue[0] == "object") {
  10104. for (var index = 0; index < sourceValue.length; index++) {
  10105. var clonedValue = cloneValue(sourceValue[index], destination);
  10106. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10107. destination[prop].push(clonedValue);
  10108. }
  10109. }
  10110. }
  10111. else {
  10112. destination[prop] = sourceValue.slice(0);
  10113. }
  10114. }
  10115. }
  10116. else {
  10117. destination[prop] = cloneValue(sourceValue, destination);
  10118. }
  10119. }
  10120. else {
  10121. destination[prop] = sourceValue;
  10122. }
  10123. }
  10124. catch (e) {
  10125. // Just ignore error (it could be because of a read-only property)
  10126. }
  10127. }
  10128. };
  10129. /**
  10130. * Gets a boolean indicating if the given object has no own property
  10131. * @param obj defines the object to test
  10132. * @returns true if object has no own property
  10133. */
  10134. Tools.IsEmpty = function (obj) {
  10135. for (var i in obj) {
  10136. if (obj.hasOwnProperty(i)) {
  10137. return false;
  10138. }
  10139. }
  10140. return true;
  10141. };
  10142. /**
  10143. * Function used to register events at window level
  10144. * @param events defines the events to register
  10145. */
  10146. Tools.RegisterTopRootEvents = function (events) {
  10147. for (var index = 0; index < events.length; index++) {
  10148. var event = events[index];
  10149. window.addEventListener(event.name, event.handler, false);
  10150. try {
  10151. if (window.parent) {
  10152. window.parent.addEventListener(event.name, event.handler, false);
  10153. }
  10154. }
  10155. catch (e) {
  10156. // Silently fails...
  10157. }
  10158. }
  10159. };
  10160. /**
  10161. * Function used to unregister events from window level
  10162. * @param events defines the events to unregister
  10163. */
  10164. Tools.UnregisterTopRootEvents = function (events) {
  10165. for (var index = 0; index < events.length; index++) {
  10166. var event = events[index];
  10167. window.removeEventListener(event.name, event.handler);
  10168. try {
  10169. if (window.parent) {
  10170. window.parent.removeEventListener(event.name, event.handler);
  10171. }
  10172. }
  10173. catch (e) {
  10174. // Silently fails...
  10175. }
  10176. }
  10177. };
  10178. /**
  10179. * Dumps the current bound framebuffer
  10180. * @param width defines the rendering width
  10181. * @param height defines the rendering height
  10182. * @param engine defines the hosting engine
  10183. * @param successCallback defines the callback triggered once the data are available
  10184. * @param mimeType defines the mime type of the result
  10185. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10186. */
  10187. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10188. if (mimeType === void 0) { mimeType = "image/png"; }
  10189. // Read the contents of the framebuffer
  10190. var numberOfChannelsByLine = width * 4;
  10191. var halfHeight = height / 2;
  10192. //Reading datas from WebGL
  10193. var data = engine.readPixels(0, 0, width, height);
  10194. //To flip image on Y axis.
  10195. for (var i = 0; i < halfHeight; i++) {
  10196. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10197. var currentCell = j + i * numberOfChannelsByLine;
  10198. var targetLine = height - i - 1;
  10199. var targetCell = j + targetLine * numberOfChannelsByLine;
  10200. var temp = data[currentCell];
  10201. data[currentCell] = data[targetCell];
  10202. data[targetCell] = temp;
  10203. }
  10204. }
  10205. // Create a 2D canvas to store the result
  10206. if (!screenshotCanvas) {
  10207. screenshotCanvas = document.createElement('canvas');
  10208. }
  10209. screenshotCanvas.width = width;
  10210. screenshotCanvas.height = height;
  10211. var context = screenshotCanvas.getContext('2d');
  10212. if (context) {
  10213. // Copy the pixels to a 2D canvas
  10214. var imageData = context.createImageData(width, height);
  10215. var castData = (imageData.data);
  10216. castData.set(data);
  10217. context.putImageData(imageData, 0, 0);
  10218. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10219. }
  10220. };
  10221. /**
  10222. * Converts the canvas data to blob.
  10223. * This acts as a polyfill for browsers not supporting the to blob function.
  10224. * @param canvas Defines the canvas to extract the data from
  10225. * @param successCallback Defines the callback triggered once the data are available
  10226. * @param mimeType Defines the mime type of the result
  10227. */
  10228. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10229. if (mimeType === void 0) { mimeType = "image/png"; }
  10230. // We need HTMLCanvasElement.toBlob for HD screenshots
  10231. if (!canvas.toBlob) {
  10232. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10233. canvas.toBlob = function (callback, type, quality) {
  10234. var _this = this;
  10235. setTimeout(function () {
  10236. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10237. for (var i = 0; i < len; i++) {
  10238. arr[i] = binStr.charCodeAt(i);
  10239. }
  10240. callback(new Blob([arr]));
  10241. });
  10242. };
  10243. }
  10244. canvas.toBlob(function (blob) {
  10245. successCallback(blob);
  10246. }, mimeType);
  10247. };
  10248. /**
  10249. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10250. * @param successCallback defines the callback triggered once the data are available
  10251. * @param mimeType defines the mime type of the result
  10252. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10253. */
  10254. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10255. if (mimeType === void 0) { mimeType = "image/png"; }
  10256. if (successCallback) {
  10257. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10258. successCallback(base64Image);
  10259. }
  10260. else {
  10261. this.ToBlob(screenshotCanvas, function (blob) {
  10262. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10263. if (("download" in document.createElement("a"))) {
  10264. if (!fileName) {
  10265. var date = new Date();
  10266. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10267. fileName = "screenshot_" + stringDate + ".png";
  10268. }
  10269. Tools.Download(blob, fileName);
  10270. }
  10271. else {
  10272. var url = URL.createObjectURL(blob);
  10273. var newWindow = window.open("");
  10274. if (!newWindow)
  10275. return;
  10276. var img = newWindow.document.createElement("img");
  10277. img.onload = function () {
  10278. // no longer need to read the blob so it's revoked
  10279. URL.revokeObjectURL(url);
  10280. };
  10281. img.src = url;
  10282. newWindow.document.body.appendChild(img);
  10283. }
  10284. }, mimeType);
  10285. }
  10286. };
  10287. /**
  10288. * Downloads a blob in the browser
  10289. * @param blob defines the blob to download
  10290. * @param fileName defines the name of the downloaded file
  10291. */
  10292. Tools.Download = function (blob, fileName) {
  10293. if (navigator && navigator.msSaveBlob) {
  10294. navigator.msSaveBlob(blob, fileName);
  10295. return;
  10296. }
  10297. var url = window.URL.createObjectURL(blob);
  10298. var a = document.createElement("a");
  10299. document.body.appendChild(a);
  10300. a.style.display = "none";
  10301. a.href = url;
  10302. a.download = fileName;
  10303. a.addEventListener("click", function () {
  10304. if (a.parentElement) {
  10305. a.parentElement.removeChild(a);
  10306. }
  10307. });
  10308. a.click();
  10309. window.URL.revokeObjectURL(url);
  10310. };
  10311. /**
  10312. * Captures a screenshot of the current rendering
  10313. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10314. * @param engine defines the rendering engine
  10315. * @param camera defines the source camera
  10316. * @param size This parameter can be set to a single number or to an object with the
  10317. * following (optional) properties: precision, width, height. If a single number is passed,
  10318. * it will be used for both width and height. If an object is passed, the screenshot size
  10319. * will be derived from the parameters. The precision property is a multiplier allowing
  10320. * rendering at a higher or lower resolution
  10321. * @param successCallback defines the callback receives a single parameter which contains the
  10322. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10323. * src parameter of an <img> to display it
  10324. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10325. * Check your browser for supported MIME types
  10326. */
  10327. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10328. if (mimeType === void 0) { mimeType = "image/png"; }
  10329. var width;
  10330. var height;
  10331. // If a precision value is specified
  10332. if (size.precision) {
  10333. width = Math.round(engine.getRenderWidth() * size.precision);
  10334. height = Math.round(width / engine.getAspectRatio(camera));
  10335. }
  10336. else if (size.width && size.height) {
  10337. width = size.width;
  10338. height = size.height;
  10339. }
  10340. //If passing only width, computing height to keep display canvas ratio.
  10341. else if (size.width && !size.height) {
  10342. width = size.width;
  10343. height = Math.round(width / engine.getAspectRatio(camera));
  10344. }
  10345. //If passing only height, computing width to keep display canvas ratio.
  10346. else if (size.height && !size.width) {
  10347. height = size.height;
  10348. width = Math.round(height * engine.getAspectRatio(camera));
  10349. }
  10350. //Assuming here that "size" parameter is a number
  10351. else if (!isNaN(size)) {
  10352. height = size;
  10353. width = size;
  10354. }
  10355. else {
  10356. Tools.Error("Invalid 'size' parameter !");
  10357. return;
  10358. }
  10359. if (!screenshotCanvas) {
  10360. screenshotCanvas = document.createElement('canvas');
  10361. }
  10362. screenshotCanvas.width = width;
  10363. screenshotCanvas.height = height;
  10364. var renderContext = screenshotCanvas.getContext("2d");
  10365. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10366. var newWidth = width;
  10367. var newHeight = newWidth / ratio;
  10368. if (newHeight > height) {
  10369. newHeight = height;
  10370. newWidth = newHeight * ratio;
  10371. }
  10372. var offsetX = Math.max(0, width - newWidth) / 2;
  10373. var offsetY = Math.max(0, height - newHeight) / 2;
  10374. var renderingCanvas = engine.getRenderingCanvas();
  10375. if (renderContext && renderingCanvas) {
  10376. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10377. }
  10378. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10379. };
  10380. /**
  10381. * Generates an image screenshot from the specified camera.
  10382. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10383. * @param engine The engine to use for rendering
  10384. * @param camera The camera to use for rendering
  10385. * @param size This parameter can be set to a single number or to an object with the
  10386. * following (optional) properties: precision, width, height. If a single number is passed,
  10387. * it will be used for both width and height. If an object is passed, the screenshot size
  10388. * will be derived from the parameters. The precision property is a multiplier allowing
  10389. * rendering at a higher or lower resolution
  10390. * @param successCallback The callback receives a single parameter which contains the
  10391. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10392. * src parameter of an <img> to display it
  10393. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10394. * Check your browser for supported MIME types
  10395. * @param samples Texture samples (default: 1)
  10396. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10397. * @param fileName A name for for the downloaded file.
  10398. */
  10399. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10400. if (mimeType === void 0) { mimeType = "image/png"; }
  10401. if (samples === void 0) { samples = 1; }
  10402. if (antialiasing === void 0) { antialiasing = false; }
  10403. var width;
  10404. var height;
  10405. //If a precision value is specified
  10406. if (size.precision) {
  10407. width = Math.round(engine.getRenderWidth() * size.precision);
  10408. height = Math.round(width / engine.getAspectRatio(camera));
  10409. size = { width: width, height: height };
  10410. }
  10411. else if (size.width && size.height) {
  10412. width = size.width;
  10413. height = size.height;
  10414. }
  10415. //If passing only width, computing height to keep display canvas ratio.
  10416. else if (size.width && !size.height) {
  10417. width = size.width;
  10418. height = Math.round(width / engine.getAspectRatio(camera));
  10419. size = { width: width, height: height };
  10420. }
  10421. //If passing only height, computing width to keep display canvas ratio.
  10422. else if (size.height && !size.width) {
  10423. height = size.height;
  10424. width = Math.round(height * engine.getAspectRatio(camera));
  10425. size = { width: width, height: height };
  10426. }
  10427. //Assuming here that "size" parameter is a number
  10428. else if (!isNaN(size)) {
  10429. height = size;
  10430. width = size;
  10431. }
  10432. else {
  10433. Tools.Error("Invalid 'size' parameter !");
  10434. return;
  10435. }
  10436. var scene = camera.getScene();
  10437. var previousCamera = null;
  10438. if (scene.activeCamera !== camera) {
  10439. previousCamera = scene.activeCamera;
  10440. scene.activeCamera = camera;
  10441. }
  10442. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10443. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10444. texture.renderList = null;
  10445. texture.samples = samples;
  10446. if (antialiasing) {
  10447. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10448. }
  10449. texture.onAfterRenderObservable.add(function () {
  10450. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10451. });
  10452. scene.incrementRenderId();
  10453. scene.resetCachedMaterial();
  10454. texture.render(true);
  10455. texture.dispose();
  10456. if (previousCamera) {
  10457. scene.activeCamera = previousCamera;
  10458. }
  10459. camera.getProjectionMatrix(true); // Force cache refresh;
  10460. };
  10461. /**
  10462. * Validates if xhr data is correct
  10463. * @param xhr defines the request to validate
  10464. * @param dataType defines the expected data type
  10465. * @returns true if data is correct
  10466. */
  10467. Tools.ValidateXHRData = function (xhr, dataType) {
  10468. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10469. if (dataType === void 0) { dataType = 7; }
  10470. try {
  10471. if (dataType & 1) {
  10472. if (xhr.responseText && xhr.responseText.length > 0) {
  10473. return true;
  10474. }
  10475. else if (dataType === 1) {
  10476. return false;
  10477. }
  10478. }
  10479. if (dataType & 2) {
  10480. // Check header width and height since there is no "TGA" magic number
  10481. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10482. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10483. return true;
  10484. }
  10485. else if (dataType === 2) {
  10486. return false;
  10487. }
  10488. }
  10489. if (dataType & 4) {
  10490. // Check for the "DDS" magic number
  10491. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10492. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10493. return true;
  10494. }
  10495. else {
  10496. return false;
  10497. }
  10498. }
  10499. }
  10500. catch (e) {
  10501. // Global protection
  10502. }
  10503. return false;
  10504. };
  10505. /**
  10506. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10507. * Be aware Math.random() could cause collisions, but:
  10508. * "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"
  10509. * @returns a pseudo random id
  10510. */
  10511. Tools.RandomId = function () {
  10512. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10513. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10514. return v.toString(16);
  10515. });
  10516. };
  10517. /**
  10518. * Test if the given uri is a base64 string
  10519. * @param uri The uri to test
  10520. * @return True if the uri is a base64 string or false otherwise
  10521. */
  10522. Tools.IsBase64 = function (uri) {
  10523. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10524. };
  10525. /**
  10526. * Decode the given base64 uri.
  10527. * @param uri The uri to decode
  10528. * @return The decoded base64 data.
  10529. */
  10530. Tools.DecodeBase64 = function (uri) {
  10531. var decodedString = atob(uri.split(",")[1]);
  10532. var bufferLength = decodedString.length;
  10533. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10534. for (var i = 0; i < bufferLength; i++) {
  10535. bufferView[i] = decodedString.charCodeAt(i);
  10536. }
  10537. return bufferView.buffer;
  10538. };
  10539. Tools._AddLogEntry = function (entry) {
  10540. Tools._LogCache = entry + Tools._LogCache;
  10541. if (Tools.OnNewCacheEntry) {
  10542. Tools.OnNewCacheEntry(entry);
  10543. }
  10544. };
  10545. Tools._FormatMessage = function (message) {
  10546. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10547. var date = new Date();
  10548. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10549. };
  10550. Tools._LogDisabled = function (message) {
  10551. // nothing to do
  10552. };
  10553. Tools._LogEnabled = function (message) {
  10554. var formattedMessage = Tools._FormatMessage(message);
  10555. console.log("BJS - " + formattedMessage);
  10556. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10557. Tools._AddLogEntry(entry);
  10558. };
  10559. Tools._WarnDisabled = function (message) {
  10560. // nothing to do
  10561. };
  10562. Tools._WarnEnabled = function (message) {
  10563. var formattedMessage = Tools._FormatMessage(message);
  10564. console.warn("BJS - " + formattedMessage);
  10565. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10566. Tools._AddLogEntry(entry);
  10567. };
  10568. Tools._ErrorDisabled = function (message) {
  10569. // nothing to do
  10570. };
  10571. Tools._ErrorEnabled = function (message) {
  10572. Tools.errorsCount++;
  10573. var formattedMessage = Tools._FormatMessage(message);
  10574. console.error("BJS - " + formattedMessage);
  10575. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10576. Tools._AddLogEntry(entry);
  10577. };
  10578. Object.defineProperty(Tools, "LogCache", {
  10579. /**
  10580. * Gets current log cache (list of logs)
  10581. */
  10582. get: function () {
  10583. return Tools._LogCache;
  10584. },
  10585. enumerable: true,
  10586. configurable: true
  10587. });
  10588. /**
  10589. * Clears the log cache
  10590. */
  10591. Tools.ClearLogCache = function () {
  10592. Tools._LogCache = "";
  10593. Tools.errorsCount = 0;
  10594. };
  10595. Object.defineProperty(Tools, "LogLevels", {
  10596. /**
  10597. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10598. */
  10599. set: function (level) {
  10600. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10601. Tools.Log = Tools._LogEnabled;
  10602. }
  10603. else {
  10604. Tools.Log = Tools._LogDisabled;
  10605. }
  10606. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10607. Tools.Warn = Tools._WarnEnabled;
  10608. }
  10609. else {
  10610. Tools.Warn = Tools._WarnDisabled;
  10611. }
  10612. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10613. Tools.Error = Tools._ErrorEnabled;
  10614. }
  10615. else {
  10616. Tools.Error = Tools._ErrorDisabled;
  10617. }
  10618. },
  10619. enumerable: true,
  10620. configurable: true
  10621. });
  10622. /**
  10623. * Checks if the loaded document was accessed via `file:`-Protocol.
  10624. * @returns boolean
  10625. */
  10626. Tools.IsFileURL = function () {
  10627. return location.protocol === "file:";
  10628. };
  10629. /**
  10630. * Checks if the window object exists
  10631. * @returns true if the window object exists
  10632. */
  10633. Tools.IsWindowObjectExist = function () {
  10634. return (typeof window) !== "undefined";
  10635. };
  10636. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10637. /**
  10638. * Sets the current performance log level
  10639. */
  10640. set: function (level) {
  10641. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10642. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10643. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10644. return;
  10645. }
  10646. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10647. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10648. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10649. return;
  10650. }
  10651. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10652. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10653. },
  10654. enumerable: true,
  10655. configurable: true
  10656. });
  10657. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10658. };
  10659. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10660. };
  10661. Tools._StartUserMark = function (counterName, condition) {
  10662. if (condition === void 0) { condition = true; }
  10663. if (!Tools._performance) {
  10664. if (!Tools.IsWindowObjectExist()) {
  10665. return;
  10666. }
  10667. Tools._performance = window.performance;
  10668. }
  10669. if (!condition || !Tools._performance.mark) {
  10670. return;
  10671. }
  10672. Tools._performance.mark(counterName + "-Begin");
  10673. };
  10674. Tools._EndUserMark = function (counterName, condition) {
  10675. if (condition === void 0) { condition = true; }
  10676. if (!condition || !Tools._performance.mark) {
  10677. return;
  10678. }
  10679. Tools._performance.mark(counterName + "-End");
  10680. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10681. };
  10682. Tools._StartPerformanceConsole = function (counterName, condition) {
  10683. if (condition === void 0) { condition = true; }
  10684. if (!condition) {
  10685. return;
  10686. }
  10687. Tools._StartUserMark(counterName, condition);
  10688. if (console.time) {
  10689. console.time(counterName);
  10690. }
  10691. };
  10692. Tools._EndPerformanceConsole = function (counterName, condition) {
  10693. if (condition === void 0) { condition = true; }
  10694. if (!condition) {
  10695. return;
  10696. }
  10697. Tools._EndUserMark(counterName, condition);
  10698. if (console.time) {
  10699. console.timeEnd(counterName);
  10700. }
  10701. };
  10702. Object.defineProperty(Tools, "Now", {
  10703. /**
  10704. * Gets either window.performance.now() if supported or Date.now() else
  10705. */
  10706. get: function () {
  10707. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10708. return window.performance.now();
  10709. }
  10710. return Date.now();
  10711. },
  10712. enumerable: true,
  10713. configurable: true
  10714. });
  10715. /**
  10716. * This method will return the name of the class used to create the instance of the given object.
  10717. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10718. * @param object the object to get the class name from
  10719. * @param isType defines if the object is actually a type
  10720. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10721. */
  10722. Tools.GetClassName = function (object, isType) {
  10723. if (isType === void 0) { isType = false; }
  10724. var name = null;
  10725. if (!isType && object.getClassName) {
  10726. name = object.getClassName();
  10727. }
  10728. else {
  10729. if (object instanceof Object) {
  10730. var classObj = isType ? object : Object.getPrototypeOf(object);
  10731. name = classObj.constructor["__bjsclassName__"];
  10732. }
  10733. if (!name) {
  10734. name = typeof object;
  10735. }
  10736. }
  10737. return name;
  10738. };
  10739. /**
  10740. * Gets the first element of an array satisfying a given predicate
  10741. * @param array defines the array to browse
  10742. * @param predicate defines the predicate to use
  10743. * @returns null if not found or the element
  10744. */
  10745. Tools.First = function (array, predicate) {
  10746. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10747. var el = array_1[_i];
  10748. if (predicate(el)) {
  10749. return el;
  10750. }
  10751. }
  10752. return null;
  10753. };
  10754. /**
  10755. * This method will return the name of the full name of the class, including its owning module (if any).
  10756. * 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).
  10757. * @param object the object to get the class name from
  10758. * @param isType defines if the object is actually a type
  10759. * @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.
  10760. * @ignorenaming
  10761. */
  10762. Tools.getFullClassName = function (object, isType) {
  10763. if (isType === void 0) { isType = false; }
  10764. var className = null;
  10765. var moduleName = null;
  10766. if (!isType && object.getClassName) {
  10767. className = object.getClassName();
  10768. }
  10769. else {
  10770. if (object instanceof Object) {
  10771. var classObj = isType ? object : Object.getPrototypeOf(object);
  10772. className = classObj.constructor["__bjsclassName__"];
  10773. moduleName = classObj.constructor["__bjsmoduleName__"];
  10774. }
  10775. if (!className) {
  10776. className = typeof object;
  10777. }
  10778. }
  10779. if (!className) {
  10780. return null;
  10781. }
  10782. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10783. };
  10784. /**
  10785. * Returns a promise that resolves after the given amount of time.
  10786. * @param delay Number of milliseconds to delay
  10787. * @returns Promise that resolves after the given amount of time
  10788. */
  10789. Tools.DelayAsync = function (delay) {
  10790. return new Promise(function (resolve) {
  10791. setTimeout(function () {
  10792. resolve();
  10793. }, delay);
  10794. });
  10795. };
  10796. /**
  10797. * Gets the current gradient from an array of IValueGradient
  10798. * @param ratio defines the current ratio to get
  10799. * @param gradients defines the array of IValueGradient
  10800. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10801. */
  10802. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10803. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10804. var currentGradient = gradients[gradientIndex];
  10805. var nextGradient = gradients[gradientIndex + 1];
  10806. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10807. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10808. updateFunc(currentGradient, nextGradient, scale);
  10809. return;
  10810. }
  10811. }
  10812. // Use last index if over
  10813. var lastIndex = gradients.length - 1;
  10814. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10815. };
  10816. /**
  10817. * Gets or sets the base URL to use to load assets
  10818. */
  10819. Tools.BaseUrl = "";
  10820. /**
  10821. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10822. */
  10823. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10824. /**
  10825. * Default behaviour for cors in the application.
  10826. * It can be a string if the expected behavior is identical in the entire app.
  10827. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10828. */
  10829. Tools.CorsBehavior = "anonymous";
  10830. /**
  10831. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10832. * @ignorenaming
  10833. */
  10834. Tools.UseFallbackTexture = true;
  10835. /**
  10836. * Use this object to register external classes like custom textures or material
  10837. * to allow the laoders to instantiate them
  10838. */
  10839. Tools.RegisteredExternalClasses = {};
  10840. /**
  10841. * Texture content used if a texture cannot loaded
  10842. * @ignorenaming
  10843. */
  10844. 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";
  10845. Tools._tmpFloatArray = new Float32Array(1);
  10846. /**
  10847. * Gets or sets a function used to pre-process url before using them to load assets
  10848. */
  10849. Tools.PreprocessUrl = function (url) {
  10850. return url;
  10851. };
  10852. // Logs
  10853. /**
  10854. * No log
  10855. */
  10856. Tools.NoneLogLevel = 0;
  10857. /**
  10858. * Only message logs
  10859. */
  10860. Tools.MessageLogLevel = 1;
  10861. /**
  10862. * Only warning logs
  10863. */
  10864. Tools.WarningLogLevel = 2;
  10865. /**
  10866. * Only error logs
  10867. */
  10868. Tools.ErrorLogLevel = 4;
  10869. /**
  10870. * All logs
  10871. */
  10872. Tools.AllLogLevel = 7;
  10873. Tools._LogCache = "";
  10874. /**
  10875. * Gets a value indicating the number of loading errors
  10876. * @ignorenaming
  10877. */
  10878. Tools.errorsCount = 0;
  10879. /**
  10880. * Log a message to the console
  10881. */
  10882. Tools.Log = Tools._LogEnabled;
  10883. /**
  10884. * Write a warning message to the console
  10885. */
  10886. Tools.Warn = Tools._WarnEnabled;
  10887. /**
  10888. * Write an error message to the console
  10889. */
  10890. Tools.Error = Tools._ErrorEnabled;
  10891. // Performances
  10892. /**
  10893. * No performance log
  10894. */
  10895. Tools.PerformanceNoneLogLevel = 0;
  10896. /**
  10897. * Use user marks to log performance
  10898. */
  10899. Tools.PerformanceUserMarkLogLevel = 1;
  10900. /**
  10901. * Log performance to the console
  10902. */
  10903. Tools.PerformanceConsoleLogLevel = 2;
  10904. /**
  10905. * Starts a performance counter
  10906. */
  10907. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10908. /**
  10909. * Ends a specific performance coutner
  10910. */
  10911. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10912. return Tools;
  10913. }());
  10914. BABYLON.Tools = Tools;
  10915. /**
  10916. * This class is used to track a performance counter which is number based.
  10917. * The user has access to many properties which give statistics of different nature.
  10918. *
  10919. * The implementer can track two kinds of Performance Counter: time and count.
  10920. * 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.
  10921. * 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.
  10922. */
  10923. var PerfCounter = /** @class */ (function () {
  10924. /**
  10925. * Creates a new counter
  10926. */
  10927. function PerfCounter() {
  10928. this._startMonitoringTime = 0;
  10929. this._min = 0;
  10930. this._max = 0;
  10931. this._average = 0;
  10932. this._lastSecAverage = 0;
  10933. this._current = 0;
  10934. this._totalValueCount = 0;
  10935. this._totalAccumulated = 0;
  10936. this._lastSecAccumulated = 0;
  10937. this._lastSecTime = 0;
  10938. this._lastSecValueCount = 0;
  10939. }
  10940. Object.defineProperty(PerfCounter.prototype, "min", {
  10941. /**
  10942. * Returns the smallest value ever
  10943. */
  10944. get: function () {
  10945. return this._min;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(PerfCounter.prototype, "max", {
  10951. /**
  10952. * Returns the biggest value ever
  10953. */
  10954. get: function () {
  10955. return this._max;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(PerfCounter.prototype, "average", {
  10961. /**
  10962. * Returns the average value since the performance counter is running
  10963. */
  10964. get: function () {
  10965. return this._average;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10971. /**
  10972. * Returns the average value of the last second the counter was monitored
  10973. */
  10974. get: function () {
  10975. return this._lastSecAverage;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(PerfCounter.prototype, "current", {
  10981. /**
  10982. * Returns the current value
  10983. */
  10984. get: function () {
  10985. return this._current;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(PerfCounter.prototype, "total", {
  10991. /**
  10992. * Gets the accumulated total
  10993. */
  10994. get: function () {
  10995. return this._totalAccumulated;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(PerfCounter.prototype, "count", {
  11001. /**
  11002. * Gets the total value count
  11003. */
  11004. get: function () {
  11005. return this._totalValueCount;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. /**
  11011. * Call this method to start monitoring a new frame.
  11012. * 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.
  11013. */
  11014. PerfCounter.prototype.fetchNewFrame = function () {
  11015. this._totalValueCount++;
  11016. this._current = 0;
  11017. this._lastSecValueCount++;
  11018. };
  11019. /**
  11020. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11021. * @param newCount the count value to add to the monitored count
  11022. * @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.
  11023. */
  11024. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11025. if (!PerfCounter.Enabled) {
  11026. return;
  11027. }
  11028. this._current += newCount;
  11029. if (fetchResult) {
  11030. this._fetchResult();
  11031. }
  11032. };
  11033. /**
  11034. * Start monitoring this performance counter
  11035. */
  11036. PerfCounter.prototype.beginMonitoring = function () {
  11037. if (!PerfCounter.Enabled) {
  11038. return;
  11039. }
  11040. this._startMonitoringTime = Tools.Now;
  11041. };
  11042. /**
  11043. * Compute the time lapsed since the previous beginMonitoring() call.
  11044. * @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
  11045. */
  11046. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11047. if (newFrame === void 0) { newFrame = true; }
  11048. if (!PerfCounter.Enabled) {
  11049. return;
  11050. }
  11051. if (newFrame) {
  11052. this.fetchNewFrame();
  11053. }
  11054. var currentTime = Tools.Now;
  11055. this._current = currentTime - this._startMonitoringTime;
  11056. if (newFrame) {
  11057. this._fetchResult();
  11058. }
  11059. };
  11060. PerfCounter.prototype._fetchResult = function () {
  11061. this._totalAccumulated += this._current;
  11062. this._lastSecAccumulated += this._current;
  11063. // Min/Max update
  11064. this._min = Math.min(this._min, this._current);
  11065. this._max = Math.max(this._max, this._current);
  11066. this._average = this._totalAccumulated / this._totalValueCount;
  11067. // Reset last sec?
  11068. var now = Tools.Now;
  11069. if ((now - this._lastSecTime) > 1000) {
  11070. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11071. this._lastSecTime = now;
  11072. this._lastSecAccumulated = 0;
  11073. this._lastSecValueCount = 0;
  11074. }
  11075. };
  11076. /**
  11077. * Gets or sets a global boolean to turn on and off all the counters
  11078. */
  11079. PerfCounter.Enabled = true;
  11080. return PerfCounter;
  11081. }());
  11082. BABYLON.PerfCounter = PerfCounter;
  11083. /**
  11084. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11085. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11086. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11087. * @param name The name of the class, case should be preserved
  11088. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11089. */
  11090. function className(name, module) {
  11091. return function (target) {
  11092. target["__bjsclassName__"] = name;
  11093. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11094. };
  11095. }
  11096. BABYLON.className = className;
  11097. /**
  11098. * An implementation of a loop for asynchronous functions.
  11099. */
  11100. var AsyncLoop = /** @class */ (function () {
  11101. /**
  11102. * Constructor.
  11103. * @param iterations the number of iterations.
  11104. * @param func the function to run each iteration
  11105. * @param successCallback the callback that will be called upon succesful execution
  11106. * @param offset starting offset.
  11107. */
  11108. function AsyncLoop(
  11109. /**
  11110. * Defines the number of iterations for the loop
  11111. */
  11112. iterations, func, successCallback, offset) {
  11113. if (offset === void 0) { offset = 0; }
  11114. this.iterations = iterations;
  11115. this.index = offset - 1;
  11116. this._done = false;
  11117. this._fn = func;
  11118. this._successCallback = successCallback;
  11119. }
  11120. /**
  11121. * Execute the next iteration. Must be called after the last iteration was finished.
  11122. */
  11123. AsyncLoop.prototype.executeNext = function () {
  11124. if (!this._done) {
  11125. if (this.index + 1 < this.iterations) {
  11126. ++this.index;
  11127. this._fn(this);
  11128. }
  11129. else {
  11130. this.breakLoop();
  11131. }
  11132. }
  11133. };
  11134. /**
  11135. * Break the loop and run the success callback.
  11136. */
  11137. AsyncLoop.prototype.breakLoop = function () {
  11138. this._done = true;
  11139. this._successCallback();
  11140. };
  11141. /**
  11142. * Create and run an async loop.
  11143. * @param iterations the number of iterations.
  11144. * @param fn the function to run each iteration
  11145. * @param successCallback the callback that will be called upon succesful execution
  11146. * @param offset starting offset.
  11147. * @returns the created async loop object
  11148. */
  11149. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11150. if (offset === void 0) { offset = 0; }
  11151. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11152. loop.executeNext();
  11153. return loop;
  11154. };
  11155. /**
  11156. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11157. * @param iterations total number of iterations
  11158. * @param syncedIterations number of synchronous iterations in each async iteration.
  11159. * @param fn the function to call each iteration.
  11160. * @param callback a success call back that will be called when iterating stops.
  11161. * @param breakFunction a break condition (optional)
  11162. * @param timeout timeout settings for the setTimeout function. default - 0.
  11163. * @returns the created async loop object
  11164. */
  11165. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11166. if (timeout === void 0) { timeout = 0; }
  11167. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11168. if (breakFunction && breakFunction())
  11169. loop.breakLoop();
  11170. else {
  11171. setTimeout(function () {
  11172. for (var i = 0; i < syncedIterations; ++i) {
  11173. var iteration = (loop.index * syncedIterations) + i;
  11174. if (iteration >= iterations)
  11175. break;
  11176. fn(iteration);
  11177. if (breakFunction && breakFunction()) {
  11178. loop.breakLoop();
  11179. break;
  11180. }
  11181. }
  11182. loop.executeNext();
  11183. }, timeout);
  11184. }
  11185. }, callback);
  11186. };
  11187. return AsyncLoop;
  11188. }());
  11189. BABYLON.AsyncLoop = AsyncLoop;
  11190. })(BABYLON || (BABYLON = {}));
  11191. //# sourceMappingURL=babylon.tools.js.map
  11192. var BABYLON;
  11193. (function (BABYLON) {
  11194. var PromiseStates;
  11195. (function (PromiseStates) {
  11196. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11197. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11198. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11199. })(PromiseStates || (PromiseStates = {}));
  11200. var FulFillmentAgregator = /** @class */ (function () {
  11201. function FulFillmentAgregator() {
  11202. this.count = 0;
  11203. this.target = 0;
  11204. this.results = [];
  11205. }
  11206. return FulFillmentAgregator;
  11207. }());
  11208. var InternalPromise = /** @class */ (function () {
  11209. function InternalPromise(resolver) {
  11210. var _this = this;
  11211. this._state = PromiseStates.Pending;
  11212. this._children = new Array();
  11213. this._rejectWasConsumed = false;
  11214. if (!resolver) {
  11215. return;
  11216. }
  11217. try {
  11218. resolver(function (value) {
  11219. _this._resolve(value);
  11220. }, function (reason) {
  11221. _this._reject(reason);
  11222. });
  11223. }
  11224. catch (e) {
  11225. this._reject(e);
  11226. }
  11227. }
  11228. Object.defineProperty(InternalPromise.prototype, "_result", {
  11229. get: function () {
  11230. return this._resultValue;
  11231. },
  11232. set: function (value) {
  11233. this._resultValue = value;
  11234. if (this._parent && this._parent._result === undefined) {
  11235. this._parent._result = value;
  11236. }
  11237. },
  11238. enumerable: true,
  11239. configurable: true
  11240. });
  11241. InternalPromise.prototype.catch = function (onRejected) {
  11242. return this.then(undefined, onRejected);
  11243. };
  11244. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11245. var _this = this;
  11246. var newPromise = new InternalPromise();
  11247. newPromise._onFulfilled = onFulfilled;
  11248. newPromise._onRejected = onRejected;
  11249. // Composition
  11250. this._children.push(newPromise);
  11251. newPromise._parent = this;
  11252. if (this._state !== PromiseStates.Pending) {
  11253. BABYLON.Tools.SetImmediate(function () {
  11254. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11255. var returnedValue = newPromise._resolve(_this._result);
  11256. if (returnedValue !== undefined && returnedValue !== null) {
  11257. if (returnedValue._state !== undefined) {
  11258. var returnedPromise = returnedValue;
  11259. newPromise._children.push(returnedPromise);
  11260. returnedPromise._parent = newPromise;
  11261. newPromise = returnedPromise;
  11262. }
  11263. else {
  11264. newPromise._result = returnedValue;
  11265. }
  11266. }
  11267. }
  11268. else {
  11269. newPromise._reject(_this._reason);
  11270. }
  11271. });
  11272. }
  11273. return newPromise;
  11274. };
  11275. InternalPromise.prototype._moveChildren = function (children) {
  11276. var _this = this;
  11277. var _a;
  11278. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11279. this._children.forEach(function (child) {
  11280. child._parent = _this;
  11281. });
  11282. if (this._state === PromiseStates.Fulfilled) {
  11283. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11284. var child = _b[_i];
  11285. child._resolve(this._result);
  11286. }
  11287. }
  11288. else if (this._state === PromiseStates.Rejected) {
  11289. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11290. var child = _d[_c];
  11291. child._reject(this._reason);
  11292. }
  11293. }
  11294. };
  11295. InternalPromise.prototype._resolve = function (value) {
  11296. try {
  11297. this._state = PromiseStates.Fulfilled;
  11298. var returnedValue = null;
  11299. if (this._onFulfilled) {
  11300. returnedValue = this._onFulfilled(value);
  11301. }
  11302. if (returnedValue !== undefined && returnedValue !== null) {
  11303. if (returnedValue._state !== undefined) {
  11304. // Transmit children
  11305. var returnedPromise = returnedValue;
  11306. returnedPromise._parent = this;
  11307. returnedPromise._moveChildren(this._children);
  11308. value = returnedPromise._result;
  11309. }
  11310. else {
  11311. value = returnedValue;
  11312. }
  11313. }
  11314. this._result = value;
  11315. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11316. var child = _a[_i];
  11317. child._resolve(value);
  11318. }
  11319. this._children.length = 0;
  11320. delete this._onFulfilled;
  11321. delete this._onRejected;
  11322. }
  11323. catch (e) {
  11324. this._reject(e, true);
  11325. }
  11326. };
  11327. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11328. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11329. this._state = PromiseStates.Rejected;
  11330. this._reason = reason;
  11331. if (this._onRejected && !onLocalThrow) {
  11332. try {
  11333. this._onRejected(reason);
  11334. this._rejectWasConsumed = true;
  11335. }
  11336. catch (e) {
  11337. reason = e;
  11338. }
  11339. }
  11340. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11341. var child = _a[_i];
  11342. if (this._rejectWasConsumed) {
  11343. child._resolve(null);
  11344. }
  11345. else {
  11346. child._reject(reason);
  11347. }
  11348. }
  11349. this._children.length = 0;
  11350. delete this._onFulfilled;
  11351. delete this._onRejected;
  11352. };
  11353. InternalPromise.resolve = function (value) {
  11354. var newPromise = new InternalPromise();
  11355. newPromise._resolve(value);
  11356. return newPromise;
  11357. };
  11358. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11359. promise.then(function (value) {
  11360. agregator.results[index] = value;
  11361. agregator.count++;
  11362. if (agregator.count === agregator.target) {
  11363. agregator.rootPromise._resolve(agregator.results);
  11364. }
  11365. return null;
  11366. }, function (reason) {
  11367. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11368. agregator.rootPromise._reject(reason);
  11369. }
  11370. });
  11371. };
  11372. InternalPromise.all = function (promises) {
  11373. var newPromise = new InternalPromise();
  11374. var agregator = new FulFillmentAgregator();
  11375. agregator.target = promises.length;
  11376. agregator.rootPromise = newPromise;
  11377. if (promises.length) {
  11378. for (var index = 0; index < promises.length; index++) {
  11379. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11380. }
  11381. }
  11382. else {
  11383. newPromise._resolve([]);
  11384. }
  11385. return newPromise;
  11386. };
  11387. InternalPromise.race = function (promises) {
  11388. var newPromise = new InternalPromise();
  11389. if (promises.length) {
  11390. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11391. var promise = promises_1[_i];
  11392. promise.then(function (value) {
  11393. if (newPromise) {
  11394. newPromise._resolve(value);
  11395. newPromise = null;
  11396. }
  11397. return null;
  11398. }, function (reason) {
  11399. if (newPromise) {
  11400. newPromise._reject(reason);
  11401. newPromise = null;
  11402. }
  11403. });
  11404. }
  11405. }
  11406. return newPromise;
  11407. };
  11408. return InternalPromise;
  11409. }());
  11410. /**
  11411. * Helper class that provides a small promise polyfill
  11412. */
  11413. var PromisePolyfill = /** @class */ (function () {
  11414. function PromisePolyfill() {
  11415. }
  11416. /**
  11417. * Static function used to check if the polyfill is required
  11418. * If this is the case then the function will inject the polyfill to window.Promise
  11419. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11420. */
  11421. PromisePolyfill.Apply = function (force) {
  11422. if (force === void 0) { force = false; }
  11423. if (force || typeof Promise === 'undefined') {
  11424. var root = window;
  11425. root.Promise = InternalPromise;
  11426. }
  11427. };
  11428. return PromisePolyfill;
  11429. }());
  11430. BABYLON.PromisePolyfill = PromisePolyfill;
  11431. })(BABYLON || (BABYLON = {}));
  11432. //# sourceMappingURL=babylon.promise.js.map
  11433. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11434. var BABYLON;
  11435. (function (BABYLON) {
  11436. /**
  11437. * Helper class to push actions to a pool of workers.
  11438. */
  11439. var WorkerPool = /** @class */ (function () {
  11440. /**
  11441. * Constructor
  11442. * @param workers Array of workers to use for actions
  11443. */
  11444. function WorkerPool(workers) {
  11445. this._pendingActions = new Array();
  11446. this._workerInfos = workers.map(function (worker) { return ({
  11447. worker: worker,
  11448. active: false
  11449. }); });
  11450. }
  11451. /**
  11452. * Terminates all workers and clears any pending actions.
  11453. */
  11454. WorkerPool.prototype.dispose = function () {
  11455. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11456. var workerInfo = _a[_i];
  11457. workerInfo.worker.terminate();
  11458. }
  11459. delete this._workerInfos;
  11460. delete this._pendingActions;
  11461. };
  11462. /**
  11463. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11464. * pended until a worker has completed its action.
  11465. * @param action The action to perform. Call onComplete when the action is complete.
  11466. */
  11467. WorkerPool.prototype.push = function (action) {
  11468. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11469. var workerInfo = _a[_i];
  11470. if (!workerInfo.active) {
  11471. this._execute(workerInfo, action);
  11472. return;
  11473. }
  11474. }
  11475. this._pendingActions.push(action);
  11476. };
  11477. WorkerPool.prototype._execute = function (workerInfo, action) {
  11478. var _this = this;
  11479. workerInfo.active = true;
  11480. action(workerInfo.worker, function () {
  11481. workerInfo.active = false;
  11482. var nextAction = _this._pendingActions.shift();
  11483. if (nextAction) {
  11484. _this._execute(workerInfo, nextAction);
  11485. }
  11486. });
  11487. };
  11488. return WorkerPool;
  11489. }());
  11490. BABYLON.WorkerPool = WorkerPool;
  11491. })(BABYLON || (BABYLON = {}));
  11492. //# sourceMappingURL=babylon.workerPool.js.map
  11493. var BABYLON;
  11494. (function (BABYLON) {
  11495. /**
  11496. * @hidden
  11497. **/
  11498. var _AlphaState = /** @class */ (function () {
  11499. /**
  11500. * Initializes the state.
  11501. */
  11502. function _AlphaState() {
  11503. this._isAlphaBlendDirty = false;
  11504. this._isBlendFunctionParametersDirty = false;
  11505. this._isBlendEquationParametersDirty = false;
  11506. this._isBlendConstantsDirty = false;
  11507. this._alphaBlend = false;
  11508. this._blendFunctionParameters = new Array(4);
  11509. this._blendEquationParameters = new Array(2);
  11510. this._blendConstants = new Array(4);
  11511. this.reset();
  11512. }
  11513. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11514. get: function () {
  11515. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11516. },
  11517. enumerable: true,
  11518. configurable: true
  11519. });
  11520. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11521. get: function () {
  11522. return this._alphaBlend;
  11523. },
  11524. set: function (value) {
  11525. if (this._alphaBlend === value) {
  11526. return;
  11527. }
  11528. this._alphaBlend = value;
  11529. this._isAlphaBlendDirty = true;
  11530. },
  11531. enumerable: true,
  11532. configurable: true
  11533. });
  11534. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11535. if (this._blendConstants[0] === r &&
  11536. this._blendConstants[1] === g &&
  11537. this._blendConstants[2] === b &&
  11538. this._blendConstants[3] === a) {
  11539. return;
  11540. }
  11541. this._blendConstants[0] = r;
  11542. this._blendConstants[1] = g;
  11543. this._blendConstants[2] = b;
  11544. this._blendConstants[3] = a;
  11545. this._isBlendConstantsDirty = true;
  11546. };
  11547. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11548. if (this._blendFunctionParameters[0] === value0 &&
  11549. this._blendFunctionParameters[1] === value1 &&
  11550. this._blendFunctionParameters[2] === value2 &&
  11551. this._blendFunctionParameters[3] === value3) {
  11552. return;
  11553. }
  11554. this._blendFunctionParameters[0] = value0;
  11555. this._blendFunctionParameters[1] = value1;
  11556. this._blendFunctionParameters[2] = value2;
  11557. this._blendFunctionParameters[3] = value3;
  11558. this._isBlendFunctionParametersDirty = true;
  11559. };
  11560. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11561. if (this._blendEquationParameters[0] === rgb &&
  11562. this._blendEquationParameters[1] === alpha) {
  11563. return;
  11564. }
  11565. this._blendEquationParameters[0] = rgb;
  11566. this._blendEquationParameters[1] = alpha;
  11567. this._isBlendEquationParametersDirty = true;
  11568. };
  11569. _AlphaState.prototype.reset = function () {
  11570. this._alphaBlend = false;
  11571. this._blendFunctionParameters[0] = null;
  11572. this._blendFunctionParameters[1] = null;
  11573. this._blendFunctionParameters[2] = null;
  11574. this._blendFunctionParameters[3] = null;
  11575. this._blendEquationParameters[0] = null;
  11576. this._blendEquationParameters[1] = null;
  11577. this._blendConstants[0] = null;
  11578. this._blendConstants[1] = null;
  11579. this._blendConstants[2] = null;
  11580. this._blendConstants[3] = null;
  11581. this._isAlphaBlendDirty = true;
  11582. this._isBlendFunctionParametersDirty = false;
  11583. this._isBlendEquationParametersDirty = false;
  11584. this._isBlendConstantsDirty = false;
  11585. };
  11586. _AlphaState.prototype.apply = function (gl) {
  11587. if (!this.isDirty) {
  11588. return;
  11589. }
  11590. // Alpha blend
  11591. if (this._isAlphaBlendDirty) {
  11592. if (this._alphaBlend) {
  11593. gl.enable(gl.BLEND);
  11594. }
  11595. else {
  11596. gl.disable(gl.BLEND);
  11597. }
  11598. this._isAlphaBlendDirty = false;
  11599. }
  11600. // Alpha function
  11601. if (this._isBlendFunctionParametersDirty) {
  11602. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11603. this._isBlendFunctionParametersDirty = false;
  11604. }
  11605. // Alpha equation
  11606. if (this._isBlendEquationParametersDirty) {
  11607. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11608. this._isBlendEquationParametersDirty = false;
  11609. }
  11610. // Constants
  11611. if (this._isBlendConstantsDirty) {
  11612. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11613. this._isBlendConstantsDirty = false;
  11614. }
  11615. };
  11616. return _AlphaState;
  11617. }());
  11618. BABYLON._AlphaState = _AlphaState;
  11619. })(BABYLON || (BABYLON = {}));
  11620. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11621. var BABYLON;
  11622. (function (BABYLON) {
  11623. /**
  11624. * @hidden
  11625. **/
  11626. var _DepthCullingState = /** @class */ (function () {
  11627. /**
  11628. * Initializes the state.
  11629. */
  11630. function _DepthCullingState() {
  11631. this._isDepthTestDirty = false;
  11632. this._isDepthMaskDirty = false;
  11633. this._isDepthFuncDirty = false;
  11634. this._isCullFaceDirty = false;
  11635. this._isCullDirty = false;
  11636. this._isZOffsetDirty = false;
  11637. this._isFrontFaceDirty = false;
  11638. this.reset();
  11639. }
  11640. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11641. get: function () {
  11642. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11643. },
  11644. enumerable: true,
  11645. configurable: true
  11646. });
  11647. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11648. get: function () {
  11649. return this._zOffset;
  11650. },
  11651. set: function (value) {
  11652. if (this._zOffset === value) {
  11653. return;
  11654. }
  11655. this._zOffset = value;
  11656. this._isZOffsetDirty = true;
  11657. },
  11658. enumerable: true,
  11659. configurable: true
  11660. });
  11661. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11662. get: function () {
  11663. return this._cullFace;
  11664. },
  11665. set: function (value) {
  11666. if (this._cullFace === value) {
  11667. return;
  11668. }
  11669. this._cullFace = value;
  11670. this._isCullFaceDirty = true;
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11676. get: function () {
  11677. return this._cull;
  11678. },
  11679. set: function (value) {
  11680. if (this._cull === value) {
  11681. return;
  11682. }
  11683. this._cull = value;
  11684. this._isCullDirty = true;
  11685. },
  11686. enumerable: true,
  11687. configurable: true
  11688. });
  11689. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11690. get: function () {
  11691. return this._depthFunc;
  11692. },
  11693. set: function (value) {
  11694. if (this._depthFunc === value) {
  11695. return;
  11696. }
  11697. this._depthFunc = value;
  11698. this._isDepthFuncDirty = true;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11704. get: function () {
  11705. return this._depthMask;
  11706. },
  11707. set: function (value) {
  11708. if (this._depthMask === value) {
  11709. return;
  11710. }
  11711. this._depthMask = value;
  11712. this._isDepthMaskDirty = true;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11718. get: function () {
  11719. return this._depthTest;
  11720. },
  11721. set: function (value) {
  11722. if (this._depthTest === value) {
  11723. return;
  11724. }
  11725. this._depthTest = value;
  11726. this._isDepthTestDirty = true;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11732. get: function () {
  11733. return this._frontFace;
  11734. },
  11735. set: function (value) {
  11736. if (this._frontFace === value) {
  11737. return;
  11738. }
  11739. this._frontFace = value;
  11740. this._isFrontFaceDirty = true;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. _DepthCullingState.prototype.reset = function () {
  11746. this._depthMask = true;
  11747. this._depthTest = true;
  11748. this._depthFunc = null;
  11749. this._cullFace = null;
  11750. this._cull = null;
  11751. this._zOffset = 0;
  11752. this._frontFace = null;
  11753. this._isDepthTestDirty = true;
  11754. this._isDepthMaskDirty = true;
  11755. this._isDepthFuncDirty = false;
  11756. this._isCullFaceDirty = false;
  11757. this._isCullDirty = false;
  11758. this._isZOffsetDirty = false;
  11759. this._isFrontFaceDirty = false;
  11760. };
  11761. _DepthCullingState.prototype.apply = function (gl) {
  11762. if (!this.isDirty) {
  11763. return;
  11764. }
  11765. // Cull
  11766. if (this._isCullDirty) {
  11767. if (this.cull) {
  11768. gl.enable(gl.CULL_FACE);
  11769. }
  11770. else {
  11771. gl.disable(gl.CULL_FACE);
  11772. }
  11773. this._isCullDirty = false;
  11774. }
  11775. // Cull face
  11776. if (this._isCullFaceDirty) {
  11777. gl.cullFace(this.cullFace);
  11778. this._isCullFaceDirty = false;
  11779. }
  11780. // Depth mask
  11781. if (this._isDepthMaskDirty) {
  11782. gl.depthMask(this.depthMask);
  11783. this._isDepthMaskDirty = false;
  11784. }
  11785. // Depth test
  11786. if (this._isDepthTestDirty) {
  11787. if (this.depthTest) {
  11788. gl.enable(gl.DEPTH_TEST);
  11789. }
  11790. else {
  11791. gl.disable(gl.DEPTH_TEST);
  11792. }
  11793. this._isDepthTestDirty = false;
  11794. }
  11795. // Depth func
  11796. if (this._isDepthFuncDirty) {
  11797. gl.depthFunc(this.depthFunc);
  11798. this._isDepthFuncDirty = false;
  11799. }
  11800. // zOffset
  11801. if (this._isZOffsetDirty) {
  11802. if (this.zOffset) {
  11803. gl.enable(gl.POLYGON_OFFSET_FILL);
  11804. gl.polygonOffset(this.zOffset, 0);
  11805. }
  11806. else {
  11807. gl.disable(gl.POLYGON_OFFSET_FILL);
  11808. }
  11809. this._isZOffsetDirty = false;
  11810. }
  11811. // Front face
  11812. if (this._isFrontFaceDirty) {
  11813. gl.frontFace(this.frontFace);
  11814. this._isFrontFaceDirty = false;
  11815. }
  11816. };
  11817. return _DepthCullingState;
  11818. }());
  11819. BABYLON._DepthCullingState = _DepthCullingState;
  11820. })(BABYLON || (BABYLON = {}));
  11821. //# sourceMappingURL=babylon.depthCullingState.js.map
  11822. var BABYLON;
  11823. (function (BABYLON) {
  11824. /**
  11825. * @hidden
  11826. **/
  11827. var _StencilState = /** @class */ (function () {
  11828. function _StencilState() {
  11829. this._isStencilTestDirty = false;
  11830. this._isStencilMaskDirty = false;
  11831. this._isStencilFuncDirty = false;
  11832. this._isStencilOpDirty = false;
  11833. this.reset();
  11834. }
  11835. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11836. get: function () {
  11837. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11843. get: function () {
  11844. return this._stencilFunc;
  11845. },
  11846. set: function (value) {
  11847. if (this._stencilFunc === value) {
  11848. return;
  11849. }
  11850. this._stencilFunc = value;
  11851. this._isStencilFuncDirty = true;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11857. get: function () {
  11858. return this._stencilFuncRef;
  11859. },
  11860. set: function (value) {
  11861. if (this._stencilFuncRef === value) {
  11862. return;
  11863. }
  11864. this._stencilFuncRef = value;
  11865. this._isStencilFuncDirty = true;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11871. get: function () {
  11872. return this._stencilFuncMask;
  11873. },
  11874. set: function (value) {
  11875. if (this._stencilFuncMask === value) {
  11876. return;
  11877. }
  11878. this._stencilFuncMask = value;
  11879. this._isStencilFuncDirty = true;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11885. get: function () {
  11886. return this._stencilOpStencilFail;
  11887. },
  11888. set: function (value) {
  11889. if (this._stencilOpStencilFail === value) {
  11890. return;
  11891. }
  11892. this._stencilOpStencilFail = value;
  11893. this._isStencilOpDirty = true;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11899. get: function () {
  11900. return this._stencilOpDepthFail;
  11901. },
  11902. set: function (value) {
  11903. if (this._stencilOpDepthFail === value) {
  11904. return;
  11905. }
  11906. this._stencilOpDepthFail = value;
  11907. this._isStencilOpDirty = true;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11913. get: function () {
  11914. return this._stencilOpStencilDepthPass;
  11915. },
  11916. set: function (value) {
  11917. if (this._stencilOpStencilDepthPass === value) {
  11918. return;
  11919. }
  11920. this._stencilOpStencilDepthPass = value;
  11921. this._isStencilOpDirty = true;
  11922. },
  11923. enumerable: true,
  11924. configurable: true
  11925. });
  11926. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11927. get: function () {
  11928. return this._stencilMask;
  11929. },
  11930. set: function (value) {
  11931. if (this._stencilMask === value) {
  11932. return;
  11933. }
  11934. this._stencilMask = value;
  11935. this._isStencilMaskDirty = true;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11941. get: function () {
  11942. return this._stencilTest;
  11943. },
  11944. set: function (value) {
  11945. if (this._stencilTest === value) {
  11946. return;
  11947. }
  11948. this._stencilTest = value;
  11949. this._isStencilTestDirty = true;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. _StencilState.prototype.reset = function () {
  11955. this._stencilTest = false;
  11956. this._stencilMask = 0xFF;
  11957. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11958. this._stencilFuncRef = 1;
  11959. this._stencilFuncMask = 0xFF;
  11960. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11961. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11962. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11963. this._isStencilTestDirty = true;
  11964. this._isStencilMaskDirty = true;
  11965. this._isStencilFuncDirty = true;
  11966. this._isStencilOpDirty = true;
  11967. };
  11968. _StencilState.prototype.apply = function (gl) {
  11969. if (!this.isDirty) {
  11970. return;
  11971. }
  11972. // Stencil test
  11973. if (this._isStencilTestDirty) {
  11974. if (this.stencilTest) {
  11975. gl.enable(gl.STENCIL_TEST);
  11976. }
  11977. else {
  11978. gl.disable(gl.STENCIL_TEST);
  11979. }
  11980. this._isStencilTestDirty = false;
  11981. }
  11982. // Stencil mask
  11983. if (this._isStencilMaskDirty) {
  11984. gl.stencilMask(this.stencilMask);
  11985. this._isStencilMaskDirty = false;
  11986. }
  11987. // Stencil func
  11988. if (this._isStencilFuncDirty) {
  11989. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11990. this._isStencilFuncDirty = false;
  11991. }
  11992. // Stencil op
  11993. if (this._isStencilOpDirty) {
  11994. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11995. this._isStencilOpDirty = false;
  11996. }
  11997. };
  11998. return _StencilState;
  11999. }());
  12000. BABYLON._StencilState = _StencilState;
  12001. })(BABYLON || (BABYLON = {}));
  12002. //# sourceMappingURL=babylon.stencilState.js.map
  12003. var __assign = (this && this.__assign) || function () {
  12004. __assign = Object.assign || function(t) {
  12005. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12006. s = arguments[i];
  12007. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12008. t[p] = s[p];
  12009. }
  12010. return t;
  12011. };
  12012. return __assign.apply(this, arguments);
  12013. };
  12014. var BABYLON;
  12015. (function (BABYLON) {
  12016. /**
  12017. * Keeps track of all the buffer info used in engine.
  12018. */
  12019. var BufferPointer = /** @class */ (function () {
  12020. function BufferPointer() {
  12021. }
  12022. return BufferPointer;
  12023. }());
  12024. /**
  12025. * Interface for attribute information associated with buffer instanciation
  12026. */
  12027. var InstancingAttributeInfo = /** @class */ (function () {
  12028. function InstancingAttributeInfo() {
  12029. }
  12030. return InstancingAttributeInfo;
  12031. }());
  12032. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12033. /**
  12034. * Define options used to create a render target texture
  12035. */
  12036. var RenderTargetCreationOptions = /** @class */ (function () {
  12037. function RenderTargetCreationOptions() {
  12038. }
  12039. return RenderTargetCreationOptions;
  12040. }());
  12041. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12042. /**
  12043. * Define options used to create a depth texture
  12044. */
  12045. var DepthTextureCreationOptions = /** @class */ (function () {
  12046. function DepthTextureCreationOptions() {
  12047. }
  12048. return DepthTextureCreationOptions;
  12049. }());
  12050. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12051. /**
  12052. * Class used to describe the capabilities of the engine relatively to the current browser
  12053. */
  12054. var EngineCapabilities = /** @class */ (function () {
  12055. function EngineCapabilities() {
  12056. }
  12057. return EngineCapabilities;
  12058. }());
  12059. BABYLON.EngineCapabilities = EngineCapabilities;
  12060. /**
  12061. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12062. */
  12063. var Engine = /** @class */ (function () {
  12064. /**
  12065. * Creates a new engine
  12066. * @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
  12067. * @param antialias defines enable antialiasing (default: false)
  12068. * @param options defines further options to be sent to the getContext() function
  12069. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12070. */
  12071. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12072. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12073. var _this = this;
  12074. // Public members
  12075. /**
  12076. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12077. */
  12078. this.forcePOTTextures = false;
  12079. /**
  12080. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12081. */
  12082. this.isFullscreen = false;
  12083. /**
  12084. * Gets a boolean indicating if the pointer is currently locked
  12085. */
  12086. this.isPointerLock = false;
  12087. /**
  12088. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12089. */
  12090. this.cullBackFaces = true;
  12091. /**
  12092. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12093. */
  12094. this.renderEvenInBackground = true;
  12095. /**
  12096. * Gets or sets a boolean indicating that cache can be kept between frames
  12097. */
  12098. this.preventCacheWipeBetweenFrames = false;
  12099. /**
  12100. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12101. **/
  12102. this.enableOfflineSupport = false;
  12103. /**
  12104. * 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)
  12105. **/
  12106. this.disableManifestCheck = false;
  12107. /**
  12108. * Gets the list of created scenes
  12109. */
  12110. this.scenes = new Array();
  12111. /**
  12112. * Gets the list of created postprocesses
  12113. */
  12114. this.postProcesses = new Array();
  12115. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12116. this.validateShaderPrograms = false;
  12117. // Observables
  12118. /**
  12119. * Observable event triggered each time the rendering canvas is resized
  12120. */
  12121. this.onResizeObservable = new BABYLON.Observable();
  12122. /**
  12123. * Observable event triggered each time the canvas loses focus
  12124. */
  12125. this.onCanvasBlurObservable = new BABYLON.Observable();
  12126. /**
  12127. * Observable event triggered each time the canvas gains focus
  12128. */
  12129. this.onCanvasFocusObservable = new BABYLON.Observable();
  12130. /**
  12131. * Observable event triggered each time the canvas receives pointerout event
  12132. */
  12133. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12134. /**
  12135. * Observable event triggered before each texture is initialized
  12136. */
  12137. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12138. //WebVR
  12139. this._vrDisplay = undefined;
  12140. this._vrSupported = false;
  12141. this._vrExclusivePointerMode = false;
  12142. // Uniform buffers list
  12143. /**
  12144. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12145. */
  12146. this.disableUniformBuffers = false;
  12147. /** @hidden */
  12148. this._uniformBuffers = new Array();
  12149. // Observables
  12150. /**
  12151. * Observable raised when the engine begins a new frame
  12152. */
  12153. this.onBeginFrameObservable = new BABYLON.Observable();
  12154. /**
  12155. * Observable raised when the engine ends the current frame
  12156. */
  12157. this.onEndFrameObservable = new BABYLON.Observable();
  12158. /**
  12159. * Observable raised when the engine is about to compile a shader
  12160. */
  12161. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12162. /**
  12163. * Observable raised when the engine has jsut compiled a shader
  12164. */
  12165. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12166. this._windowIsBackground = false;
  12167. this._webGLVersion = 1.0;
  12168. /** @hidden */
  12169. this._badOS = false;
  12170. /** @hidden */
  12171. this._badDesktopOS = false;
  12172. /**
  12173. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12174. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12175. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12176. */
  12177. this.disableTextureBindingOptimization = false;
  12178. /**
  12179. * Observable signaled when VR display mode changes
  12180. */
  12181. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12182. /**
  12183. * Observable signaled when VR request present is complete
  12184. */
  12185. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12186. /**
  12187. * Observable signaled when VR request present starts
  12188. */
  12189. this.onVRRequestPresentStart = new BABYLON.Observable();
  12190. this._colorWrite = true;
  12191. /** @hidden */
  12192. this._drawCalls = new BABYLON.PerfCounter();
  12193. /** @hidden */
  12194. this._textureCollisions = new BABYLON.PerfCounter();
  12195. this._renderingQueueLaunched = false;
  12196. this._activeRenderLoops = new Array();
  12197. // Deterministic lockstepMaxSteps
  12198. this._deterministicLockstep = false;
  12199. this._lockstepMaxSteps = 4;
  12200. // Lost context
  12201. /**
  12202. * Observable signaled when a context lost event is raised
  12203. */
  12204. this.onContextLostObservable = new BABYLON.Observable();
  12205. /**
  12206. * Observable signaled when a context restored event is raised
  12207. */
  12208. this.onContextRestoredObservable = new BABYLON.Observable();
  12209. this._contextWasLost = false;
  12210. this._doNotHandleContextLost = false;
  12211. // FPS
  12212. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12213. this._fps = 60;
  12214. this._deltaTime = 0;
  12215. /**
  12216. * Turn this value on if you want to pause FPS computation when in background
  12217. */
  12218. this.disablePerformanceMonitorInBackground = false;
  12219. // States
  12220. /** @hidden */
  12221. this._depthCullingState = new BABYLON._DepthCullingState();
  12222. /** @hidden */
  12223. this._stencilState = new BABYLON._StencilState();
  12224. /** @hidden */
  12225. this._alphaState = new BABYLON._AlphaState();
  12226. /** @hidden */
  12227. this._alphaMode = Engine.ALPHA_DISABLE;
  12228. // Cache
  12229. this._internalTexturesCache = new Array();
  12230. /** @hidden */
  12231. this._activeChannel = 0;
  12232. this._currentTextureChannel = -1;
  12233. /** @hidden */
  12234. this._boundTexturesCache = {};
  12235. this._compiledEffects = {};
  12236. this._vertexAttribArraysEnabled = [];
  12237. this._uintIndicesCurrentlySet = false;
  12238. this._currentBoundBuffer = new Array();
  12239. /** @hidden */
  12240. this._currentFramebuffer = null;
  12241. this._currentBufferPointers = new Array();
  12242. this._currentInstanceLocations = new Array();
  12243. this._currentInstanceBuffers = new Array();
  12244. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12245. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12246. this._vaoRecordInProgress = false;
  12247. this._mustWipeVertexAttributes = false;
  12248. this._nextFreeTextureSlots = new Array();
  12249. this._maxSimultaneousTextures = 0;
  12250. this._activeRequests = new Array();
  12251. // Hardware supported Compressed Textures
  12252. this._texturesSupported = new Array();
  12253. /**
  12254. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12255. */
  12256. this.premultipliedAlpha = true;
  12257. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12258. this._onVRFullScreenTriggered = function () {
  12259. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12260. //get the old size before we change
  12261. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12262. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12263. //get the width and height, change the render size
  12264. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12265. _this.setHardwareScalingLevel(1);
  12266. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12267. }
  12268. else {
  12269. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12270. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12271. }
  12272. };
  12273. this._unpackFlipYCached = null;
  12274. /**
  12275. * In case you are sharing the context with other applications, it might
  12276. * be interested to not cache the unpack flip y state to ensure a consistent
  12277. * value would be set.
  12278. */
  12279. this.enableUnpackFlipYCached = true;
  12280. this._boundUniforms = {};
  12281. // Register promises
  12282. BABYLON.PromisePolyfill.Apply();
  12283. var canvas = null;
  12284. Engine.Instances.push(this);
  12285. if (!canvasOrContext) {
  12286. return;
  12287. }
  12288. options = options || {};
  12289. if (canvasOrContext.getContext) {
  12290. canvas = canvasOrContext;
  12291. this._renderingCanvas = canvas;
  12292. if (antialias != null) {
  12293. options.antialias = antialias;
  12294. }
  12295. if (options.deterministicLockstep === undefined) {
  12296. options.deterministicLockstep = false;
  12297. }
  12298. if (options.lockstepMaxSteps === undefined) {
  12299. options.lockstepMaxSteps = 4;
  12300. }
  12301. if (options.preserveDrawingBuffer === undefined) {
  12302. options.preserveDrawingBuffer = false;
  12303. }
  12304. if (options.audioEngine === undefined) {
  12305. options.audioEngine = true;
  12306. }
  12307. if (options.stencil === undefined) {
  12308. options.stencil = true;
  12309. }
  12310. if (options.premultipliedAlpha === false) {
  12311. this.premultipliedAlpha = false;
  12312. }
  12313. this._deterministicLockstep = options.deterministicLockstep;
  12314. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12315. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12316. // Exceptions
  12317. if (navigator && navigator.userAgent) {
  12318. var ua = navigator.userAgent;
  12319. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12320. var exception = _a[_i];
  12321. var key = exception.key;
  12322. var targets = exception.targets;
  12323. if (ua.indexOf(key) > -1) {
  12324. if (exception.capture && exception.captureConstraint) {
  12325. var capture = exception.capture;
  12326. var constraint = exception.captureConstraint;
  12327. var regex = new RegExp(capture);
  12328. var matches = regex.exec(ua);
  12329. if (matches && matches.length > 0) {
  12330. var capturedValue = parseInt(matches[matches.length - 1]);
  12331. if (capturedValue >= constraint) {
  12332. continue;
  12333. }
  12334. }
  12335. }
  12336. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12337. var target = targets_1[_b];
  12338. switch (target) {
  12339. case "uniformBuffer":
  12340. this.disableUniformBuffers = true;
  12341. break;
  12342. case "textureBindingOptimization":
  12343. this.disableTextureBindingOptimization = true;
  12344. break;
  12345. }
  12346. }
  12347. }
  12348. }
  12349. }
  12350. // GL
  12351. if (!options.disableWebGL2Support) {
  12352. try {
  12353. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12354. if (this._gl) {
  12355. this._webGLVersion = 2.0;
  12356. // Prevent weird browsers to lie :-)
  12357. if (!this._gl.deleteQuery) {
  12358. this._webGLVersion = 1.0;
  12359. }
  12360. }
  12361. }
  12362. catch (e) {
  12363. // Do nothing
  12364. }
  12365. }
  12366. if (!this._gl) {
  12367. if (!canvas) {
  12368. throw new Error("The provided canvas is null or undefined.");
  12369. }
  12370. try {
  12371. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12372. }
  12373. catch (e) {
  12374. throw new Error("WebGL not supported");
  12375. }
  12376. }
  12377. if (!this._gl) {
  12378. throw new Error("WebGL not supported");
  12379. }
  12380. this._onCanvasFocus = function () {
  12381. _this.onCanvasFocusObservable.notifyObservers(_this);
  12382. };
  12383. this._onCanvasBlur = function () {
  12384. _this.onCanvasBlurObservable.notifyObservers(_this);
  12385. };
  12386. canvas.addEventListener("focus", this._onCanvasFocus);
  12387. canvas.addEventListener("blur", this._onCanvasBlur);
  12388. this._onBlur = function () {
  12389. if (_this.disablePerformanceMonitorInBackground) {
  12390. _this._performanceMonitor.disable();
  12391. }
  12392. _this._windowIsBackground = true;
  12393. };
  12394. this._onFocus = function () {
  12395. if (_this.disablePerformanceMonitorInBackground) {
  12396. _this._performanceMonitor.enable();
  12397. }
  12398. _this._windowIsBackground = false;
  12399. };
  12400. this._onCanvasPointerOut = function (ev) {
  12401. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12402. };
  12403. window.addEventListener("blur", this._onBlur);
  12404. window.addEventListener("focus", this._onFocus);
  12405. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12406. // Context lost
  12407. if (!this._doNotHandleContextLost) {
  12408. this._onContextLost = function (evt) {
  12409. evt.preventDefault();
  12410. _this._contextWasLost = true;
  12411. BABYLON.Tools.Warn("WebGL context lost.");
  12412. _this.onContextLostObservable.notifyObservers(_this);
  12413. };
  12414. this._onContextRestored = function (evt) {
  12415. // Adding a timeout to avoid race condition at browser level
  12416. setTimeout(function () {
  12417. // Rebuild gl context
  12418. _this._initGLContext();
  12419. // Rebuild effects
  12420. _this._rebuildEffects();
  12421. // Rebuild textures
  12422. _this._rebuildInternalTextures();
  12423. // Rebuild buffers
  12424. _this._rebuildBuffers();
  12425. // Cache
  12426. _this.wipeCaches(true);
  12427. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12428. _this.onContextRestoredObservable.notifyObservers(_this);
  12429. _this._contextWasLost = false;
  12430. }, 0);
  12431. };
  12432. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12433. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12434. }
  12435. }
  12436. else {
  12437. this._gl = canvasOrContext;
  12438. this._renderingCanvas = this._gl.canvas;
  12439. if (this._gl.renderbufferStorageMultisample) {
  12440. this._webGLVersion = 2.0;
  12441. }
  12442. options.stencil = this._gl.getContextAttributes().stencil;
  12443. }
  12444. // Viewport
  12445. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12446. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12447. this.resize();
  12448. this._isStencilEnable = options.stencil ? true : false;
  12449. this._initGLContext();
  12450. if (canvas) {
  12451. // Fullscreen
  12452. this._onFullscreenChange = function () {
  12453. if (document.fullscreen !== undefined) {
  12454. _this.isFullscreen = document.fullscreen;
  12455. }
  12456. else if (document.mozFullScreen !== undefined) {
  12457. _this.isFullscreen = document.mozFullScreen;
  12458. }
  12459. else if (document.webkitIsFullScreen !== undefined) {
  12460. _this.isFullscreen = document.webkitIsFullScreen;
  12461. }
  12462. else if (document.msIsFullScreen !== undefined) {
  12463. _this.isFullscreen = document.msIsFullScreen;
  12464. }
  12465. // Pointer lock
  12466. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12467. canvas.requestPointerLock = canvas.requestPointerLock ||
  12468. canvas.msRequestPointerLock ||
  12469. canvas.mozRequestPointerLock ||
  12470. canvas.webkitRequestPointerLock;
  12471. if (canvas.requestPointerLock) {
  12472. canvas.requestPointerLock();
  12473. }
  12474. }
  12475. };
  12476. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12477. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12478. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12479. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12480. // Pointer lock
  12481. this._onPointerLockChange = function () {
  12482. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12483. document.webkitPointerLockElement === canvas ||
  12484. document.msPointerLockElement === canvas ||
  12485. document.pointerLockElement === canvas);
  12486. };
  12487. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12488. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12489. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12490. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12491. this._onVRDisplayPointerRestricted = function () {
  12492. if (canvas) {
  12493. canvas.requestPointerLock();
  12494. }
  12495. };
  12496. this._onVRDisplayPointerUnrestricted = function () {
  12497. document.exitPointerLock();
  12498. };
  12499. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12500. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12501. }
  12502. // Create Audio Engine if needed.
  12503. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12504. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12505. }
  12506. // Prepare buffer pointers
  12507. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12508. this._currentBufferPointers[i] = new BufferPointer();
  12509. }
  12510. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12511. // Load WebVR Devices
  12512. if (options.autoEnableWebVR) {
  12513. this.initWebVR();
  12514. }
  12515. // Detect if we are running on a faulty buggy OS.
  12516. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12517. // Detect if we are running on a faulty buggy desktop OS.
  12518. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12519. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12520. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12521. }
  12522. Object.defineProperty(Engine, "LastCreatedEngine", {
  12523. /**
  12524. * Gets the latest created engine
  12525. */
  12526. get: function () {
  12527. if (Engine.Instances.length === 0) {
  12528. return null;
  12529. }
  12530. return Engine.Instances[Engine.Instances.length - 1];
  12531. },
  12532. enumerable: true,
  12533. configurable: true
  12534. });
  12535. Object.defineProperty(Engine, "LastCreatedScene", {
  12536. /**
  12537. * Gets the latest created scene
  12538. */
  12539. get: function () {
  12540. var lastCreatedEngine = Engine.LastCreatedEngine;
  12541. if (!lastCreatedEngine) {
  12542. return null;
  12543. }
  12544. if (lastCreatedEngine.scenes.length === 0) {
  12545. return null;
  12546. }
  12547. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12548. },
  12549. enumerable: true,
  12550. configurable: true
  12551. });
  12552. /**
  12553. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12554. * @param flag defines which part of the materials must be marked as dirty
  12555. * @param predicate defines a predicate used to filter which materials should be affected
  12556. */
  12557. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12558. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12559. var engine = Engine.Instances[engineIndex];
  12560. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12561. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12562. }
  12563. }
  12564. };
  12565. Object.defineProperty(Engine, "Version", {
  12566. /**
  12567. * Returns the current version of the framework
  12568. */
  12569. get: function () {
  12570. return "3.3.0-rc.4";
  12571. },
  12572. enumerable: true,
  12573. configurable: true
  12574. });
  12575. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12576. /**
  12577. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12578. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12579. */
  12580. get: function () {
  12581. return this._vrExclusivePointerMode;
  12582. },
  12583. enumerable: true,
  12584. configurable: true
  12585. });
  12586. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12587. /**
  12588. * Gets a boolean indicating that the engine supports uniform buffers
  12589. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12590. */
  12591. get: function () {
  12592. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12593. },
  12594. enumerable: true,
  12595. configurable: true
  12596. });
  12597. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12598. /**
  12599. * Gets a boolean indicating that only power of 2 textures are supported
  12600. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12601. */
  12602. get: function () {
  12603. return this._webGLVersion < 2 || this.forcePOTTextures;
  12604. },
  12605. enumerable: true,
  12606. configurable: true
  12607. });
  12608. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12609. /**
  12610. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12611. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12612. */
  12613. get: function () {
  12614. return this._doNotHandleContextLost;
  12615. },
  12616. set: function (value) {
  12617. this._doNotHandleContextLost = value;
  12618. },
  12619. enumerable: true,
  12620. configurable: true
  12621. });
  12622. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12623. /**
  12624. * Gets the performance monitor attached to this engine
  12625. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12626. */
  12627. get: function () {
  12628. return this._performanceMonitor;
  12629. },
  12630. enumerable: true,
  12631. configurable: true
  12632. });
  12633. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12634. /**
  12635. * Gets the list of texture formats supported
  12636. */
  12637. get: function () {
  12638. return this._texturesSupported;
  12639. },
  12640. enumerable: true,
  12641. configurable: true
  12642. });
  12643. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12644. /**
  12645. * Gets the list of texture formats in use
  12646. */
  12647. get: function () {
  12648. return this._textureFormatInUse;
  12649. },
  12650. enumerable: true,
  12651. configurable: true
  12652. });
  12653. Object.defineProperty(Engine.prototype, "currentViewport", {
  12654. /**
  12655. * Gets the current viewport
  12656. */
  12657. get: function () {
  12658. return this._cachedViewport;
  12659. },
  12660. enumerable: true,
  12661. configurable: true
  12662. });
  12663. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12664. /**
  12665. * Gets the default empty texture
  12666. */
  12667. get: function () {
  12668. if (!this._emptyTexture) {
  12669. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12670. }
  12671. return this._emptyTexture;
  12672. },
  12673. enumerable: true,
  12674. configurable: true
  12675. });
  12676. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12677. /**
  12678. * Gets the default empty 3D texture
  12679. */
  12680. get: function () {
  12681. if (!this._emptyTexture3D) {
  12682. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12683. }
  12684. return this._emptyTexture3D;
  12685. },
  12686. enumerable: true,
  12687. configurable: true
  12688. });
  12689. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12690. /**
  12691. * Gets the default empty cube texture
  12692. */
  12693. get: function () {
  12694. if (!this._emptyCubeTexture) {
  12695. var faceData = new Uint8Array(4);
  12696. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12697. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12698. }
  12699. return this._emptyCubeTexture;
  12700. },
  12701. enumerable: true,
  12702. configurable: true
  12703. });
  12704. Engine.prototype._rebuildInternalTextures = function () {
  12705. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12706. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12707. var internalTexture = currentState_1[_i];
  12708. internalTexture._rebuild();
  12709. }
  12710. };
  12711. Engine.prototype._rebuildEffects = function () {
  12712. for (var key in this._compiledEffects) {
  12713. var effect = this._compiledEffects[key];
  12714. effect._prepareEffect();
  12715. }
  12716. BABYLON.Effect.ResetCache();
  12717. };
  12718. Engine.prototype._rebuildBuffers = function () {
  12719. // Index / Vertex
  12720. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12721. var scene = _a[_i];
  12722. scene.resetCachedMaterial();
  12723. scene._rebuildGeometries();
  12724. scene._rebuildTextures();
  12725. }
  12726. // Uniforms
  12727. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12728. var uniformBuffer = _c[_b];
  12729. uniformBuffer._rebuild();
  12730. }
  12731. };
  12732. Engine.prototype._initGLContext = function () {
  12733. // Caps
  12734. this._caps = new EngineCapabilities();
  12735. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12736. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12737. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12738. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12739. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12740. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12741. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12742. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12743. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12744. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12745. // Infos
  12746. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12747. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12748. if (rendererInfo != null) {
  12749. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12750. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12751. }
  12752. if (!this._glVendor) {
  12753. this._glVendor = "Unknown vendor";
  12754. }
  12755. if (!this._glRenderer) {
  12756. this._glRenderer = "Unknown renderer";
  12757. }
  12758. // Constants
  12759. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12760. if (this._gl.RGBA16F !== 0x881A) {
  12761. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12762. }
  12763. if (this._gl.RGBA32F !== 0x8814) {
  12764. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12765. }
  12766. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12767. this._gl.DEPTH24_STENCIL8 = 35056;
  12768. }
  12769. // Extensions
  12770. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12771. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12772. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12773. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12774. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12775. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12776. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12777. 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');
  12778. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12779. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12780. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12781. this._caps.highPrecisionShaderSupported = true;
  12782. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12783. if (this._caps.timerQuery) {
  12784. if (this._webGLVersion === 1) {
  12785. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12786. }
  12787. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12788. }
  12789. // Checks if some of the format renders first to allow the use of webgl inspector.
  12790. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12791. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12792. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12793. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12794. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12795. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12796. if (this._webGLVersion > 1) {
  12797. this._gl.HALF_FLOAT_OES = 0x140B;
  12798. }
  12799. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12800. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12801. // Draw buffers
  12802. if (this._webGLVersion > 1) {
  12803. this._caps.drawBuffersExtension = true;
  12804. }
  12805. else {
  12806. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12807. if (drawBuffersExtension !== null) {
  12808. this._caps.drawBuffersExtension = true;
  12809. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12810. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12811. for (var i = 0; i < 16; i++) {
  12812. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12813. }
  12814. }
  12815. else {
  12816. this._caps.drawBuffersExtension = false;
  12817. }
  12818. }
  12819. // Depth Texture
  12820. if (this._webGLVersion > 1) {
  12821. this._caps.depthTextureExtension = true;
  12822. }
  12823. else {
  12824. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12825. if (depthTextureExtension != null) {
  12826. this._caps.depthTextureExtension = true;
  12827. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12828. }
  12829. }
  12830. // Vertex array object
  12831. if (this._webGLVersion > 1) {
  12832. this._caps.vertexArrayObject = true;
  12833. }
  12834. else {
  12835. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12836. if (vertexArrayObjectExtension != null) {
  12837. this._caps.vertexArrayObject = true;
  12838. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12839. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12840. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12841. }
  12842. else {
  12843. this._caps.vertexArrayObject = false;
  12844. }
  12845. }
  12846. // Instances count
  12847. if (this._webGLVersion > 1) {
  12848. this._caps.instancedArrays = true;
  12849. }
  12850. else {
  12851. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12852. if (instanceExtension != null) {
  12853. this._caps.instancedArrays = true;
  12854. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12855. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12856. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12857. }
  12858. else {
  12859. this._caps.instancedArrays = false;
  12860. }
  12861. }
  12862. // Intelligently add supported compressed formats in order to check for.
  12863. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12864. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12865. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12866. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12867. if (this._caps.astc)
  12868. this.texturesSupported.push('-astc.ktx');
  12869. if (this._caps.s3tc)
  12870. this.texturesSupported.push('-dxt.ktx');
  12871. if (this._caps.pvrtc)
  12872. this.texturesSupported.push('-pvrtc.ktx');
  12873. if (this._caps.etc2)
  12874. this.texturesSupported.push('-etc2.ktx');
  12875. if (this._caps.etc1)
  12876. this.texturesSupported.push('-etc1.ktx');
  12877. if (this._gl.getShaderPrecisionFormat) {
  12878. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12879. if (highp) {
  12880. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12881. }
  12882. }
  12883. // Depth buffer
  12884. this.setDepthBuffer(true);
  12885. this.setDepthFunctionToLessOrEqual();
  12886. this.setDepthWrite(true);
  12887. // Texture maps
  12888. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12889. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12890. this._nextFreeTextureSlots.push(slot);
  12891. }
  12892. };
  12893. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12894. /**
  12895. * Gets version of the current webGL context
  12896. */
  12897. get: function () {
  12898. return this._webGLVersion;
  12899. },
  12900. enumerable: true,
  12901. configurable: true
  12902. });
  12903. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12904. /**
  12905. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12906. */
  12907. get: function () {
  12908. return this._isStencilEnable;
  12909. },
  12910. enumerable: true,
  12911. configurable: true
  12912. });
  12913. Engine.prototype._prepareWorkingCanvas = function () {
  12914. if (this._workingCanvas) {
  12915. return;
  12916. }
  12917. this._workingCanvas = document.createElement("canvas");
  12918. var context = this._workingCanvas.getContext("2d");
  12919. if (context) {
  12920. this._workingContext = context;
  12921. }
  12922. };
  12923. /**
  12924. * Reset the texture cache to empty state
  12925. */
  12926. Engine.prototype.resetTextureCache = function () {
  12927. for (var key in this._boundTexturesCache) {
  12928. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12929. continue;
  12930. }
  12931. var boundTexture = this._boundTexturesCache[key];
  12932. if (boundTexture) {
  12933. this._removeDesignatedSlot(boundTexture);
  12934. }
  12935. this._boundTexturesCache[key] = null;
  12936. }
  12937. if (!this.disableTextureBindingOptimization) {
  12938. this._nextFreeTextureSlots = [];
  12939. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12940. this._nextFreeTextureSlots.push(slot);
  12941. }
  12942. }
  12943. this._currentTextureChannel = -1;
  12944. };
  12945. /**
  12946. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12947. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12948. * @returns true if engine is in deterministic lock step mode
  12949. */
  12950. Engine.prototype.isDeterministicLockStep = function () {
  12951. return this._deterministicLockstep;
  12952. };
  12953. /**
  12954. * Gets the max steps when engine is running in deterministic lock step
  12955. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12956. * @returns the max steps
  12957. */
  12958. Engine.prototype.getLockstepMaxSteps = function () {
  12959. return this._lockstepMaxSteps;
  12960. };
  12961. /**
  12962. * Gets an object containing information about the current webGL context
  12963. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12964. */
  12965. Engine.prototype.getGlInfo = function () {
  12966. return {
  12967. vendor: this._glVendor,
  12968. renderer: this._glRenderer,
  12969. version: this._glVersion
  12970. };
  12971. };
  12972. /**
  12973. * Gets current aspect ratio
  12974. * @param camera defines the camera to use to get the aspect ratio
  12975. * @param useScreen defines if screen size must be used (or the current render target if any)
  12976. * @returns a number defining the aspect ratio
  12977. */
  12978. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12979. if (useScreen === void 0) { useScreen = false; }
  12980. var viewport = camera.viewport;
  12981. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12982. };
  12983. /**
  12984. * Gets current screen aspect ratio
  12985. * @returns a number defining the aspect ratio
  12986. */
  12987. Engine.prototype.getScreenAspectRatio = function () {
  12988. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12989. };
  12990. /**
  12991. * Gets the current render width
  12992. * @param useScreen defines if screen size must be used (or the current render target if any)
  12993. * @returns a number defining the current render width
  12994. */
  12995. Engine.prototype.getRenderWidth = function (useScreen) {
  12996. if (useScreen === void 0) { useScreen = false; }
  12997. if (!useScreen && this._currentRenderTarget) {
  12998. return this._currentRenderTarget.width;
  12999. }
  13000. return this._gl.drawingBufferWidth;
  13001. };
  13002. /**
  13003. * Gets the current render height
  13004. * @param useScreen defines if screen size must be used (or the current render target if any)
  13005. * @returns a number defining the current render height
  13006. */
  13007. Engine.prototype.getRenderHeight = function (useScreen) {
  13008. if (useScreen === void 0) { useScreen = false; }
  13009. if (!useScreen && this._currentRenderTarget) {
  13010. return this._currentRenderTarget.height;
  13011. }
  13012. return this._gl.drawingBufferHeight;
  13013. };
  13014. /**
  13015. * Gets the HTML canvas attached with the current webGL context
  13016. * @returns a HTML canvas
  13017. */
  13018. Engine.prototype.getRenderingCanvas = function () {
  13019. return this._renderingCanvas;
  13020. };
  13021. /**
  13022. * Gets the client rect of the HTML canvas attached with the current webGL context
  13023. * @returns a client rectanglee
  13024. */
  13025. Engine.prototype.getRenderingCanvasClientRect = function () {
  13026. if (!this._renderingCanvas) {
  13027. return null;
  13028. }
  13029. return this._renderingCanvas.getBoundingClientRect();
  13030. };
  13031. /**
  13032. * Defines the hardware scaling level.
  13033. * By default the hardware scaling level is computed from the window device ratio.
  13034. * 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.
  13035. * @param level defines the level to use
  13036. */
  13037. Engine.prototype.setHardwareScalingLevel = function (level) {
  13038. this._hardwareScalingLevel = level;
  13039. this.resize();
  13040. };
  13041. /**
  13042. * Gets the current hardware scaling level.
  13043. * By default the hardware scaling level is computed from the window device ratio.
  13044. * 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.
  13045. * @returns a number indicating the current hardware scaling level
  13046. */
  13047. Engine.prototype.getHardwareScalingLevel = function () {
  13048. return this._hardwareScalingLevel;
  13049. };
  13050. /**
  13051. * Gets the list of loaded textures
  13052. * @returns an array containing all loaded textures
  13053. */
  13054. Engine.prototype.getLoadedTexturesCache = function () {
  13055. return this._internalTexturesCache;
  13056. };
  13057. /**
  13058. * Gets the object containing all engine capabilities
  13059. * @returns the EngineCapabilities object
  13060. */
  13061. Engine.prototype.getCaps = function () {
  13062. return this._caps;
  13063. };
  13064. Object.defineProperty(Engine.prototype, "drawCalls", {
  13065. /** @hidden */
  13066. get: function () {
  13067. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13068. return 0;
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13074. /** @hidden */
  13075. get: function () {
  13076. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13077. return null;
  13078. },
  13079. enumerable: true,
  13080. configurable: true
  13081. });
  13082. /**
  13083. * Gets the current depth function
  13084. * @returns a number defining the depth function
  13085. */
  13086. Engine.prototype.getDepthFunction = function () {
  13087. return this._depthCullingState.depthFunc;
  13088. };
  13089. /**
  13090. * Sets the current depth function
  13091. * @param depthFunc defines the function to use
  13092. */
  13093. Engine.prototype.setDepthFunction = function (depthFunc) {
  13094. this._depthCullingState.depthFunc = depthFunc;
  13095. };
  13096. /**
  13097. * Sets the current depth function to GREATER
  13098. */
  13099. Engine.prototype.setDepthFunctionToGreater = function () {
  13100. this._depthCullingState.depthFunc = this._gl.GREATER;
  13101. };
  13102. /**
  13103. * Sets the current depth function to GEQUAL
  13104. */
  13105. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13106. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13107. };
  13108. /**
  13109. * Sets the current depth function to LESS
  13110. */
  13111. Engine.prototype.setDepthFunctionToLess = function () {
  13112. this._depthCullingState.depthFunc = this._gl.LESS;
  13113. };
  13114. /**
  13115. * Sets the current depth function to LEQUAL
  13116. */
  13117. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13118. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13119. };
  13120. /**
  13121. * Gets a boolean indicating if stencil buffer is enabled
  13122. * @returns the current stencil buffer state
  13123. */
  13124. Engine.prototype.getStencilBuffer = function () {
  13125. return this._stencilState.stencilTest;
  13126. };
  13127. /**
  13128. * Enable or disable the stencil buffer
  13129. * @param enable defines if the stencil buffer must be enabled or disabled
  13130. */
  13131. Engine.prototype.setStencilBuffer = function (enable) {
  13132. this._stencilState.stencilTest = enable;
  13133. };
  13134. /**
  13135. * Gets the current stencil mask
  13136. * @returns a number defining the new stencil mask to use
  13137. */
  13138. Engine.prototype.getStencilMask = function () {
  13139. return this._stencilState.stencilMask;
  13140. };
  13141. /**
  13142. * Sets the current stencil mask
  13143. * @param mask defines the new stencil mask to use
  13144. */
  13145. Engine.prototype.setStencilMask = function (mask) {
  13146. this._stencilState.stencilMask = mask;
  13147. };
  13148. /**
  13149. * Gets the current stencil function
  13150. * @returns a number defining the stencil function to use
  13151. */
  13152. Engine.prototype.getStencilFunction = function () {
  13153. return this._stencilState.stencilFunc;
  13154. };
  13155. /**
  13156. * Gets the current stencil reference value
  13157. * @returns a number defining the stencil reference value to use
  13158. */
  13159. Engine.prototype.getStencilFunctionReference = function () {
  13160. return this._stencilState.stencilFuncRef;
  13161. };
  13162. /**
  13163. * Gets the current stencil mask
  13164. * @returns a number defining the stencil mask to use
  13165. */
  13166. Engine.prototype.getStencilFunctionMask = function () {
  13167. return this._stencilState.stencilFuncMask;
  13168. };
  13169. /**
  13170. * Sets the current stencil function
  13171. * @param stencilFunc defines the new stencil function to use
  13172. */
  13173. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13174. this._stencilState.stencilFunc = stencilFunc;
  13175. };
  13176. /**
  13177. * Sets the current stencil reference
  13178. * @param reference defines the new stencil reference to use
  13179. */
  13180. Engine.prototype.setStencilFunctionReference = function (reference) {
  13181. this._stencilState.stencilFuncRef = reference;
  13182. };
  13183. /**
  13184. * Sets the current stencil mask
  13185. * @param mask defines the new stencil mask to use
  13186. */
  13187. Engine.prototype.setStencilFunctionMask = function (mask) {
  13188. this._stencilState.stencilFuncMask = mask;
  13189. };
  13190. /**
  13191. * Gets the current stencil operation when stencil fails
  13192. * @returns a number defining stencil operation to use when stencil fails
  13193. */
  13194. Engine.prototype.getStencilOperationFail = function () {
  13195. return this._stencilState.stencilOpStencilFail;
  13196. };
  13197. /**
  13198. * Gets the current stencil operation when depth fails
  13199. * @returns a number defining stencil operation to use when depth fails
  13200. */
  13201. Engine.prototype.getStencilOperationDepthFail = function () {
  13202. return this._stencilState.stencilOpDepthFail;
  13203. };
  13204. /**
  13205. * Gets the current stencil operation when stencil passes
  13206. * @returns a number defining stencil operation to use when stencil passes
  13207. */
  13208. Engine.prototype.getStencilOperationPass = function () {
  13209. return this._stencilState.stencilOpStencilDepthPass;
  13210. };
  13211. /**
  13212. * Sets the stencil operation to use when stencil fails
  13213. * @param operation defines the stencil operation to use when stencil fails
  13214. */
  13215. Engine.prototype.setStencilOperationFail = function (operation) {
  13216. this._stencilState.stencilOpStencilFail = operation;
  13217. };
  13218. /**
  13219. * Sets the stencil operation to use when depth fails
  13220. * @param operation defines the stencil operation to use when depth fails
  13221. */
  13222. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13223. this._stencilState.stencilOpDepthFail = operation;
  13224. };
  13225. /**
  13226. * Sets the stencil operation to use when stencil passes
  13227. * @param operation defines the stencil operation to use when stencil passes
  13228. */
  13229. Engine.prototype.setStencilOperationPass = function (operation) {
  13230. this._stencilState.stencilOpStencilDepthPass = operation;
  13231. };
  13232. /**
  13233. * Sets a boolean indicating if the dithering state is enabled or disabled
  13234. * @param value defines the dithering state
  13235. */
  13236. Engine.prototype.setDitheringState = function (value) {
  13237. if (value) {
  13238. this._gl.enable(this._gl.DITHER);
  13239. }
  13240. else {
  13241. this._gl.disable(this._gl.DITHER);
  13242. }
  13243. };
  13244. /**
  13245. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13246. * @param value defines the rasterizer state
  13247. */
  13248. Engine.prototype.setRasterizerState = function (value) {
  13249. if (value) {
  13250. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13251. }
  13252. else {
  13253. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13254. }
  13255. };
  13256. /**
  13257. * stop executing a render loop function and remove it from the execution array
  13258. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13259. */
  13260. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13261. if (!renderFunction) {
  13262. this._activeRenderLoops = [];
  13263. return;
  13264. }
  13265. var index = this._activeRenderLoops.indexOf(renderFunction);
  13266. if (index >= 0) {
  13267. this._activeRenderLoops.splice(index, 1);
  13268. }
  13269. };
  13270. /** @hidden */
  13271. Engine.prototype._renderLoop = function () {
  13272. if (!this._contextWasLost) {
  13273. var shouldRender = true;
  13274. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13275. shouldRender = false;
  13276. }
  13277. if (shouldRender) {
  13278. // Start new frame
  13279. this.beginFrame();
  13280. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13281. var renderFunction = this._activeRenderLoops[index];
  13282. renderFunction();
  13283. }
  13284. // Present
  13285. this.endFrame();
  13286. }
  13287. }
  13288. if (this._activeRenderLoops.length > 0) {
  13289. // Register new frame
  13290. var requester = null;
  13291. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13292. requester = this._vrDisplay;
  13293. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13294. }
  13295. else {
  13296. this._renderingQueueLaunched = false;
  13297. }
  13298. };
  13299. /**
  13300. * Register and execute a render loop. The engine can have more than one render function
  13301. * @param renderFunction defines the function to continuously execute
  13302. */
  13303. Engine.prototype.runRenderLoop = function (renderFunction) {
  13304. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13305. return;
  13306. }
  13307. this._activeRenderLoops.push(renderFunction);
  13308. if (!this._renderingQueueLaunched) {
  13309. this._renderingQueueLaunched = true;
  13310. this._bindedRenderFunction = this._renderLoop.bind(this);
  13311. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13312. }
  13313. };
  13314. /**
  13315. * Toggle full screen mode
  13316. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13317. */
  13318. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13319. if (this.isFullscreen) {
  13320. BABYLON.Tools.ExitFullscreen();
  13321. }
  13322. else {
  13323. this._pointerLockRequested = requestPointerLock;
  13324. if (this._renderingCanvas) {
  13325. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13326. }
  13327. }
  13328. };
  13329. /**
  13330. * Clear the current render buffer or the current render target (if any is set up)
  13331. * @param color defines the color to use
  13332. * @param backBuffer defines if the back buffer must be cleared
  13333. * @param depth defines if the depth buffer must be cleared
  13334. * @param stencil defines if the stencil buffer must be cleared
  13335. */
  13336. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13337. if (stencil === void 0) { stencil = false; }
  13338. this.applyStates();
  13339. var mode = 0;
  13340. if (backBuffer && color) {
  13341. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13342. mode |= this._gl.COLOR_BUFFER_BIT;
  13343. }
  13344. if (depth) {
  13345. this._gl.clearDepth(1.0);
  13346. mode |= this._gl.DEPTH_BUFFER_BIT;
  13347. }
  13348. if (stencil) {
  13349. this._gl.clearStencil(0);
  13350. mode |= this._gl.STENCIL_BUFFER_BIT;
  13351. }
  13352. this._gl.clear(mode);
  13353. };
  13354. /**
  13355. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13356. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13357. * @param y defines the y-coordinate of the corner of the clear rectangle
  13358. * @param width defines the width of the clear rectangle
  13359. * @param height defines the height of the clear rectangle
  13360. * @param clearColor defines the clear color
  13361. */
  13362. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13363. var gl = this._gl;
  13364. // Save state
  13365. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13366. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13367. // Change state
  13368. gl.enable(gl.SCISSOR_TEST);
  13369. gl.scissor(x, y, width, height);
  13370. // Clear
  13371. this.clear(clearColor, true, true, true);
  13372. // Restore state
  13373. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13374. if (curScissor === true) {
  13375. gl.enable(gl.SCISSOR_TEST);
  13376. }
  13377. else {
  13378. gl.disable(gl.SCISSOR_TEST);
  13379. }
  13380. };
  13381. /** @hidden */
  13382. Engine.prototype._viewport = function (x, y, width, height) {
  13383. if (x !== this._viewportCached.x ||
  13384. y !== this._viewportCached.y ||
  13385. width !== this._viewportCached.z ||
  13386. height !== this._viewportCached.w) {
  13387. this._viewportCached.x = x;
  13388. this._viewportCached.y = y;
  13389. this._viewportCached.z = width;
  13390. this._viewportCached.w = height;
  13391. this._gl.viewport(x, y, width, height);
  13392. }
  13393. };
  13394. /**
  13395. * Set the WebGL's viewport
  13396. * @param viewport defines the viewport element to be used
  13397. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13398. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13399. */
  13400. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13401. var width = requiredWidth || this.getRenderWidth();
  13402. var height = requiredHeight || this.getRenderHeight();
  13403. var x = viewport.x || 0;
  13404. var y = viewport.y || 0;
  13405. this._cachedViewport = viewport;
  13406. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13407. };
  13408. /**
  13409. * Directly set the WebGL Viewport
  13410. * @param x defines the x coordinate of the viewport (in screen space)
  13411. * @param y defines the y coordinate of the viewport (in screen space)
  13412. * @param width defines the width of the viewport (in screen space)
  13413. * @param height defines the height of the viewport (in screen space)
  13414. * @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
  13415. */
  13416. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13417. var currentViewport = this._cachedViewport;
  13418. this._cachedViewport = null;
  13419. this._viewport(x, y, width, height);
  13420. return currentViewport;
  13421. };
  13422. /**
  13423. * Begin a new frame
  13424. */
  13425. Engine.prototype.beginFrame = function () {
  13426. this.onBeginFrameObservable.notifyObservers(this);
  13427. this._measureFps();
  13428. };
  13429. /**
  13430. * Enf the current frame
  13431. */
  13432. Engine.prototype.endFrame = function () {
  13433. // Force a flush in case we are using a bad OS.
  13434. if (this._badOS) {
  13435. this.flushFramebuffer();
  13436. }
  13437. // Submit frame to the vr device, if enabled
  13438. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13439. // TODO: We should only submit the frame if we read frameData successfully.
  13440. this._vrDisplay.submitFrame();
  13441. }
  13442. this.onEndFrameObservable.notifyObservers(this);
  13443. };
  13444. /**
  13445. * Resize the view according to the canvas' size
  13446. */
  13447. Engine.prototype.resize = function () {
  13448. // We're not resizing the size of the canvas while in VR mode & presenting
  13449. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13450. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13451. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13452. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13453. }
  13454. };
  13455. /**
  13456. * Force a specific size of the canvas
  13457. * @param width defines the new canvas' width
  13458. * @param height defines the new canvas' height
  13459. */
  13460. Engine.prototype.setSize = function (width, height) {
  13461. if (!this._renderingCanvas) {
  13462. return;
  13463. }
  13464. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13465. return;
  13466. }
  13467. this._renderingCanvas.width = width;
  13468. this._renderingCanvas.height = height;
  13469. for (var index = 0; index < this.scenes.length; index++) {
  13470. var scene = this.scenes[index];
  13471. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13472. var cam = scene.cameras[camIndex];
  13473. cam._currentRenderId = 0;
  13474. }
  13475. }
  13476. if (this.onResizeObservable.hasObservers) {
  13477. this.onResizeObservable.notifyObservers(this);
  13478. }
  13479. };
  13480. // WebVR functions
  13481. /**
  13482. * Gets a boolean indicating if a webVR device was detected
  13483. * @returns true if a webVR device was detected
  13484. */
  13485. Engine.prototype.isVRDevicePresent = function () {
  13486. return !!this._vrDisplay;
  13487. };
  13488. /**
  13489. * Gets the current webVR device
  13490. * @returns the current webVR device (or null)
  13491. */
  13492. Engine.prototype.getVRDevice = function () {
  13493. return this._vrDisplay;
  13494. };
  13495. /**
  13496. * Initializes a webVR display and starts listening to display change events
  13497. * The onVRDisplayChangedObservable will be notified upon these changes
  13498. * @returns The onVRDisplayChangedObservable
  13499. */
  13500. Engine.prototype.initWebVR = function () {
  13501. this.initWebVRAsync();
  13502. return this.onVRDisplayChangedObservable;
  13503. };
  13504. /**
  13505. * Initializes a webVR display and starts listening to display change events
  13506. * The onVRDisplayChangedObservable will be notified upon these changes
  13507. * @returns A promise containing a VRDisplay and if vr is supported
  13508. */
  13509. Engine.prototype.initWebVRAsync = function () {
  13510. var _this = this;
  13511. var notifyObservers = function () {
  13512. var eventArgs = {
  13513. vrDisplay: _this._vrDisplay,
  13514. vrSupported: _this._vrSupported
  13515. };
  13516. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13517. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13518. };
  13519. if (!this._onVrDisplayConnect) {
  13520. this._onVrDisplayConnect = function (event) {
  13521. _this._vrDisplay = event.display;
  13522. notifyObservers();
  13523. };
  13524. this._onVrDisplayDisconnect = function () {
  13525. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13526. _this._vrDisplay = undefined;
  13527. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13528. notifyObservers();
  13529. };
  13530. this._onVrDisplayPresentChange = function () {
  13531. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13532. };
  13533. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13534. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13535. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13536. }
  13537. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13538. this._webVRInitPromise.then(notifyObservers);
  13539. return this._webVRInitPromise;
  13540. };
  13541. /**
  13542. * Call this function to switch to webVR mode
  13543. * Will do nothing if webVR is not supported or if there is no webVR device
  13544. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13545. */
  13546. Engine.prototype.enableVR = function () {
  13547. var _this = this;
  13548. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13549. var onResolved = function () {
  13550. _this.onVRRequestPresentComplete.notifyObservers(true);
  13551. _this._onVRFullScreenTriggered();
  13552. };
  13553. var onRejected = function () {
  13554. _this.onVRRequestPresentComplete.notifyObservers(false);
  13555. };
  13556. this.onVRRequestPresentStart.notifyObservers(this);
  13557. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13558. }
  13559. };
  13560. /**
  13561. * Call this function to leave webVR mode
  13562. * Will do nothing if webVR is not supported or if there is no webVR device
  13563. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13564. */
  13565. Engine.prototype.disableVR = function () {
  13566. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13567. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13568. }
  13569. };
  13570. Engine.prototype._getVRDisplaysAsync = function () {
  13571. var _this = this;
  13572. return new Promise(function (res, rej) {
  13573. if (navigator.getVRDisplays) {
  13574. navigator.getVRDisplays().then(function (devices) {
  13575. _this._vrSupported = true;
  13576. // note that devices may actually be an empty array. This is fine;
  13577. // we expect this._vrDisplay to be undefined in this case.
  13578. _this._vrDisplay = devices[0];
  13579. res({
  13580. vrDisplay: _this._vrDisplay,
  13581. vrSupported: _this._vrSupported
  13582. });
  13583. });
  13584. }
  13585. else {
  13586. _this._vrDisplay = undefined;
  13587. _this._vrSupported = false;
  13588. res({
  13589. vrDisplay: _this._vrDisplay,
  13590. vrSupported: _this._vrSupported
  13591. });
  13592. }
  13593. });
  13594. };
  13595. /**
  13596. * Binds the frame buffer to the specified texture.
  13597. * @param texture The texture to render to or null for the default canvas
  13598. * @param faceIndex The face of the texture to render to in case of cube texture
  13599. * @param requiredWidth The width of the target to render to
  13600. * @param requiredHeight The height of the target to render to
  13601. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13602. * @param depthStencilTexture The depth stencil texture to use to render
  13603. * @param lodLevel defines le lod level to bind to the frame buffer
  13604. */
  13605. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13606. if (lodLevel === void 0) { lodLevel = 0; }
  13607. if (this._currentRenderTarget) {
  13608. this.unBindFramebuffer(this._currentRenderTarget);
  13609. }
  13610. this._currentRenderTarget = texture;
  13611. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13612. var gl = this._gl;
  13613. if (texture.isCube) {
  13614. if (faceIndex === undefined) {
  13615. faceIndex = 0;
  13616. }
  13617. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13618. if (depthStencilTexture) {
  13619. if (depthStencilTexture._generateStencilBuffer) {
  13620. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13621. }
  13622. else {
  13623. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13624. }
  13625. }
  13626. }
  13627. if (this._cachedViewport && !forceFullscreenViewport) {
  13628. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13629. }
  13630. else {
  13631. if (!requiredWidth) {
  13632. requiredWidth = texture.width;
  13633. if (lodLevel) {
  13634. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13635. }
  13636. }
  13637. if (!requiredHeight) {
  13638. requiredHeight = texture.height;
  13639. if (lodLevel) {
  13640. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13641. }
  13642. }
  13643. this._viewport(0, 0, requiredWidth, requiredHeight);
  13644. }
  13645. this.wipeCaches();
  13646. };
  13647. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13648. if (this._currentFramebuffer !== framebuffer) {
  13649. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13650. this._currentFramebuffer = framebuffer;
  13651. }
  13652. };
  13653. /**
  13654. * Unbind the current render target texture from the webGL context
  13655. * @param texture defines the render target texture to unbind
  13656. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13657. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13658. */
  13659. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13660. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13661. this._currentRenderTarget = null;
  13662. // If MSAA, we need to bitblt back to main texture
  13663. var gl = this._gl;
  13664. if (texture._MSAAFramebuffer) {
  13665. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13666. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13667. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13668. }
  13669. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13670. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13671. gl.generateMipmap(gl.TEXTURE_2D);
  13672. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13673. }
  13674. if (onBeforeUnbind) {
  13675. if (texture._MSAAFramebuffer) {
  13676. // Bind the correct framebuffer
  13677. this.bindUnboundFramebuffer(texture._framebuffer);
  13678. }
  13679. onBeforeUnbind();
  13680. }
  13681. this.bindUnboundFramebuffer(null);
  13682. };
  13683. /**
  13684. * Unbind a list of render target textures from the webGL context
  13685. * This is used only when drawBuffer extension or webGL2 are active
  13686. * @param textures defines the render target textures to unbind
  13687. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13688. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13689. */
  13690. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13691. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13692. this._currentRenderTarget = null;
  13693. // If MSAA, we need to bitblt back to main texture
  13694. var gl = this._gl;
  13695. if (textures[0]._MSAAFramebuffer) {
  13696. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13697. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13698. var attachments = textures[0]._attachments;
  13699. if (!attachments) {
  13700. attachments = new Array(textures.length);
  13701. textures[0]._attachments = attachments;
  13702. }
  13703. for (var i = 0; i < textures.length; i++) {
  13704. var texture = textures[i];
  13705. for (var j = 0; j < attachments.length; j++) {
  13706. attachments[j] = gl.NONE;
  13707. }
  13708. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13709. gl.readBuffer(attachments[i]);
  13710. gl.drawBuffers(attachments);
  13711. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13712. }
  13713. for (var i = 0; i < attachments.length; i++) {
  13714. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13715. }
  13716. gl.drawBuffers(attachments);
  13717. }
  13718. for (var i = 0; i < textures.length; i++) {
  13719. var texture = textures[i];
  13720. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13721. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13722. gl.generateMipmap(gl.TEXTURE_2D);
  13723. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13724. }
  13725. }
  13726. if (onBeforeUnbind) {
  13727. if (textures[0]._MSAAFramebuffer) {
  13728. // Bind the correct framebuffer
  13729. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13730. }
  13731. onBeforeUnbind();
  13732. }
  13733. this.bindUnboundFramebuffer(null);
  13734. };
  13735. /**
  13736. * Force the mipmap generation for the given render target texture
  13737. * @param texture defines the render target texture to use
  13738. */
  13739. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13740. if (texture.generateMipMaps) {
  13741. var gl = this._gl;
  13742. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13743. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13744. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13745. }
  13746. };
  13747. /**
  13748. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13749. */
  13750. Engine.prototype.flushFramebuffer = function () {
  13751. this._gl.flush();
  13752. };
  13753. /**
  13754. * Unbind the current render target and bind the default framebuffer
  13755. */
  13756. Engine.prototype.restoreDefaultFramebuffer = function () {
  13757. if (this._currentRenderTarget) {
  13758. this.unBindFramebuffer(this._currentRenderTarget);
  13759. }
  13760. else {
  13761. this.bindUnboundFramebuffer(null);
  13762. }
  13763. if (this._cachedViewport) {
  13764. this.setViewport(this._cachedViewport);
  13765. }
  13766. this.wipeCaches();
  13767. };
  13768. // UBOs
  13769. /**
  13770. * Create an uniform buffer
  13771. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13772. * @param elements defines the content of the uniform buffer
  13773. * @returns the webGL uniform buffer
  13774. */
  13775. Engine.prototype.createUniformBuffer = function (elements) {
  13776. var ubo = this._gl.createBuffer();
  13777. if (!ubo) {
  13778. throw new Error("Unable to create uniform buffer");
  13779. }
  13780. this.bindUniformBuffer(ubo);
  13781. if (elements instanceof Float32Array) {
  13782. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13783. }
  13784. else {
  13785. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13786. }
  13787. this.bindUniformBuffer(null);
  13788. ubo.references = 1;
  13789. return ubo;
  13790. };
  13791. /**
  13792. * Create a dynamic uniform buffer
  13793. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13794. * @param elements defines the content of the uniform buffer
  13795. * @returns the webGL uniform buffer
  13796. */
  13797. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13798. var ubo = this._gl.createBuffer();
  13799. if (!ubo) {
  13800. throw new Error("Unable to create dynamic uniform buffer");
  13801. }
  13802. this.bindUniformBuffer(ubo);
  13803. if (elements instanceof Float32Array) {
  13804. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13805. }
  13806. else {
  13807. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13808. }
  13809. this.bindUniformBuffer(null);
  13810. ubo.references = 1;
  13811. return ubo;
  13812. };
  13813. /**
  13814. * Update an existing uniform buffer
  13815. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13816. * @param uniformBuffer defines the target uniform buffer
  13817. * @param elements defines the content to update
  13818. * @param offset defines the offset in the uniform buffer where update should start
  13819. * @param count defines the size of the data to update
  13820. */
  13821. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13822. this.bindUniformBuffer(uniformBuffer);
  13823. if (offset === undefined) {
  13824. offset = 0;
  13825. }
  13826. if (count === undefined) {
  13827. if (elements instanceof Float32Array) {
  13828. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13829. }
  13830. else {
  13831. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13832. }
  13833. }
  13834. else {
  13835. if (elements instanceof Float32Array) {
  13836. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13837. }
  13838. else {
  13839. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13840. }
  13841. }
  13842. this.bindUniformBuffer(null);
  13843. };
  13844. // VBOs
  13845. Engine.prototype._resetVertexBufferBinding = function () {
  13846. this.bindArrayBuffer(null);
  13847. this._cachedVertexBuffers = null;
  13848. };
  13849. /**
  13850. * Creates a vertex buffer
  13851. * @param data the data for the vertex buffer
  13852. * @returns the new WebGL static buffer
  13853. */
  13854. Engine.prototype.createVertexBuffer = function (data) {
  13855. var vbo = this._gl.createBuffer();
  13856. if (!vbo) {
  13857. throw new Error("Unable to create vertex buffer");
  13858. }
  13859. this.bindArrayBuffer(vbo);
  13860. if (data instanceof Array) {
  13861. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13862. }
  13863. else {
  13864. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13865. }
  13866. this._resetVertexBufferBinding();
  13867. vbo.references = 1;
  13868. return vbo;
  13869. };
  13870. /**
  13871. * Creates a dynamic vertex buffer
  13872. * @param data the data for the dynamic vertex buffer
  13873. * @returns the new WebGL dynamic buffer
  13874. */
  13875. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13876. var vbo = this._gl.createBuffer();
  13877. if (!vbo) {
  13878. throw new Error("Unable to create dynamic vertex buffer");
  13879. }
  13880. this.bindArrayBuffer(vbo);
  13881. if (data instanceof Array) {
  13882. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13883. }
  13884. else {
  13885. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13886. }
  13887. this._resetVertexBufferBinding();
  13888. vbo.references = 1;
  13889. return vbo;
  13890. };
  13891. /**
  13892. * Update a dynamic index buffer
  13893. * @param indexBuffer defines the target index buffer
  13894. * @param indices defines the data to update
  13895. * @param offset defines the offset in the target index buffer where update should start
  13896. */
  13897. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13898. if (offset === void 0) { offset = 0; }
  13899. // Force cache update
  13900. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13901. this.bindIndexBuffer(indexBuffer);
  13902. var arrayBuffer;
  13903. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13904. arrayBuffer = indices;
  13905. }
  13906. else {
  13907. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13908. }
  13909. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13910. this._resetIndexBufferBinding();
  13911. };
  13912. /**
  13913. * Updates a dynamic vertex buffer.
  13914. * @param vertexBuffer the vertex buffer to update
  13915. * @param data the data used to update the vertex buffer
  13916. * @param byteOffset the byte offset of the data
  13917. * @param byteLength the byte length of the data
  13918. */
  13919. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13920. this.bindArrayBuffer(vertexBuffer);
  13921. if (byteOffset === undefined) {
  13922. byteOffset = 0;
  13923. }
  13924. if (byteLength === undefined) {
  13925. if (data instanceof Array) {
  13926. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13927. }
  13928. else {
  13929. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13930. }
  13931. }
  13932. else {
  13933. if (data instanceof Array) {
  13934. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13935. }
  13936. else {
  13937. if (data instanceof ArrayBuffer) {
  13938. data = new Uint8Array(data, byteOffset, byteLength);
  13939. }
  13940. else {
  13941. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13942. }
  13943. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13944. }
  13945. }
  13946. this._resetVertexBufferBinding();
  13947. };
  13948. Engine.prototype._resetIndexBufferBinding = function () {
  13949. this.bindIndexBuffer(null);
  13950. this._cachedIndexBuffer = null;
  13951. };
  13952. /**
  13953. * Creates a new index buffer
  13954. * @param indices defines the content of the index buffer
  13955. * @param updatable defines if the index buffer must be updatable
  13956. * @returns a new webGL buffer
  13957. */
  13958. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13959. var vbo = this._gl.createBuffer();
  13960. if (!vbo) {
  13961. throw new Error("Unable to create index buffer");
  13962. }
  13963. this.bindIndexBuffer(vbo);
  13964. // Check for 32 bits indices
  13965. var arrayBuffer;
  13966. var need32Bits = false;
  13967. if (indices instanceof Uint16Array) {
  13968. arrayBuffer = indices;
  13969. }
  13970. else {
  13971. //check 32 bit support
  13972. if (this._caps.uintIndices) {
  13973. if (indices instanceof Uint32Array) {
  13974. arrayBuffer = indices;
  13975. need32Bits = true;
  13976. }
  13977. else {
  13978. //number[] or Int32Array, check if 32 bit is necessary
  13979. for (var index = 0; index < indices.length; index++) {
  13980. if (indices[index] > 65535) {
  13981. need32Bits = true;
  13982. break;
  13983. }
  13984. }
  13985. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13986. }
  13987. }
  13988. else {
  13989. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13990. arrayBuffer = new Uint16Array(indices);
  13991. }
  13992. }
  13993. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13994. this._resetIndexBufferBinding();
  13995. vbo.references = 1;
  13996. vbo.is32Bits = need32Bits;
  13997. return vbo;
  13998. };
  13999. /**
  14000. * Bind a webGL buffer to the webGL context
  14001. * @param buffer defines the buffer to bind
  14002. */
  14003. Engine.prototype.bindArrayBuffer = function (buffer) {
  14004. if (!this._vaoRecordInProgress) {
  14005. this._unbindVertexArrayObject();
  14006. }
  14007. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14008. };
  14009. /**
  14010. * Bind an uniform buffer to the current webGL context
  14011. * @param buffer defines the buffer to bind
  14012. */
  14013. Engine.prototype.bindUniformBuffer = function (buffer) {
  14014. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14015. };
  14016. /**
  14017. * Bind a buffer to the current webGL context at a given location
  14018. * @param buffer defines the buffer to bind
  14019. * @param location defines the index where to bind the buffer
  14020. */
  14021. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14022. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14023. };
  14024. /**
  14025. * Bind a specific block at a given index in a specific shader program
  14026. * @param shaderProgram defines the shader program
  14027. * @param blockName defines the block name
  14028. * @param index defines the index where to bind the block
  14029. */
  14030. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14031. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14032. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14033. };
  14034. ;
  14035. Engine.prototype.bindIndexBuffer = function (buffer) {
  14036. if (!this._vaoRecordInProgress) {
  14037. this._unbindVertexArrayObject();
  14038. }
  14039. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14040. };
  14041. Engine.prototype.bindBuffer = function (buffer, target) {
  14042. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14043. this._gl.bindBuffer(target, buffer);
  14044. this._currentBoundBuffer[target] = buffer;
  14045. }
  14046. };
  14047. /**
  14048. * update the bound buffer with the given data
  14049. * @param data defines the data to update
  14050. */
  14051. Engine.prototype.updateArrayBuffer = function (data) {
  14052. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14053. };
  14054. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14055. var pointer = this._currentBufferPointers[indx];
  14056. var changed = false;
  14057. if (!pointer.active) {
  14058. changed = true;
  14059. pointer.active = true;
  14060. pointer.index = indx;
  14061. pointer.size = size;
  14062. pointer.type = type;
  14063. pointer.normalized = normalized;
  14064. pointer.stride = stride;
  14065. pointer.offset = offset;
  14066. pointer.buffer = buffer;
  14067. }
  14068. else {
  14069. if (pointer.buffer !== buffer) {
  14070. pointer.buffer = buffer;
  14071. changed = true;
  14072. }
  14073. if (pointer.size !== size) {
  14074. pointer.size = size;
  14075. changed = true;
  14076. }
  14077. if (pointer.type !== type) {
  14078. pointer.type = type;
  14079. changed = true;
  14080. }
  14081. if (pointer.normalized !== normalized) {
  14082. pointer.normalized = normalized;
  14083. changed = true;
  14084. }
  14085. if (pointer.stride !== stride) {
  14086. pointer.stride = stride;
  14087. changed = true;
  14088. }
  14089. if (pointer.offset !== offset) {
  14090. pointer.offset = offset;
  14091. changed = true;
  14092. }
  14093. }
  14094. if (changed || this._vaoRecordInProgress) {
  14095. this.bindArrayBuffer(buffer);
  14096. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14097. }
  14098. };
  14099. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14100. if (indexBuffer == null) {
  14101. return;
  14102. }
  14103. if (this._cachedIndexBuffer !== indexBuffer) {
  14104. this._cachedIndexBuffer = indexBuffer;
  14105. this.bindIndexBuffer(indexBuffer);
  14106. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14107. }
  14108. };
  14109. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14110. var attributes = effect.getAttributesNames();
  14111. if (!this._vaoRecordInProgress) {
  14112. this._unbindVertexArrayObject();
  14113. }
  14114. this.unbindAllAttributes();
  14115. for (var index = 0; index < attributes.length; index++) {
  14116. var order = effect.getAttributeLocation(index);
  14117. if (order >= 0) {
  14118. var vertexBuffer = vertexBuffers[attributes[index]];
  14119. if (!vertexBuffer) {
  14120. continue;
  14121. }
  14122. this._gl.enableVertexAttribArray(order);
  14123. if (!this._vaoRecordInProgress) {
  14124. this._vertexAttribArraysEnabled[order] = true;
  14125. }
  14126. var buffer = vertexBuffer.getBuffer();
  14127. if (buffer) {
  14128. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14129. if (vertexBuffer.getIsInstanced()) {
  14130. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14131. if (!this._vaoRecordInProgress) {
  14132. this._currentInstanceLocations.push(order);
  14133. this._currentInstanceBuffers.push(buffer);
  14134. }
  14135. }
  14136. }
  14137. }
  14138. }
  14139. };
  14140. /**
  14141. * Records a vertex array object
  14142. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14143. * @param vertexBuffers defines the list of vertex buffers to store
  14144. * @param indexBuffer defines the index buffer to store
  14145. * @param effect defines the effect to store
  14146. * @returns the new vertex array object
  14147. */
  14148. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14149. var vao = this._gl.createVertexArray();
  14150. this._vaoRecordInProgress = true;
  14151. this._gl.bindVertexArray(vao);
  14152. this._mustWipeVertexAttributes = true;
  14153. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14154. this.bindIndexBuffer(indexBuffer);
  14155. this._vaoRecordInProgress = false;
  14156. this._gl.bindVertexArray(null);
  14157. return vao;
  14158. };
  14159. /**
  14160. * Bind a specific vertex array object
  14161. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14162. * @param vertexArrayObject defines the vertex array object to bind
  14163. * @param indexBuffer defines the index buffer to bind
  14164. */
  14165. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14166. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14167. this._cachedVertexArrayObject = vertexArrayObject;
  14168. this._gl.bindVertexArray(vertexArrayObject);
  14169. this._cachedVertexBuffers = null;
  14170. this._cachedIndexBuffer = null;
  14171. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14172. this._mustWipeVertexAttributes = true;
  14173. }
  14174. };
  14175. /**
  14176. * Bind webGl buffers directly to the webGL context
  14177. * @param vertexBuffer defines the vertex buffer to bind
  14178. * @param indexBuffer defines the index buffer to bind
  14179. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14180. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14181. * @param effect defines the effect associated with the vertex buffer
  14182. */
  14183. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14184. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14185. this._cachedVertexBuffers = vertexBuffer;
  14186. this._cachedEffectForVertexBuffers = effect;
  14187. var attributesCount = effect.getAttributesCount();
  14188. this._unbindVertexArrayObject();
  14189. this.unbindAllAttributes();
  14190. var offset = 0;
  14191. for (var index = 0; index < attributesCount; index++) {
  14192. if (index < vertexDeclaration.length) {
  14193. var order = effect.getAttributeLocation(index);
  14194. if (order >= 0) {
  14195. this._gl.enableVertexAttribArray(order);
  14196. this._vertexAttribArraysEnabled[order] = true;
  14197. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14198. }
  14199. offset += vertexDeclaration[index] * 4;
  14200. }
  14201. }
  14202. }
  14203. this._bindIndexBufferWithCache(indexBuffer);
  14204. };
  14205. Engine.prototype._unbindVertexArrayObject = function () {
  14206. if (!this._cachedVertexArrayObject) {
  14207. return;
  14208. }
  14209. this._cachedVertexArrayObject = null;
  14210. this._gl.bindVertexArray(null);
  14211. };
  14212. /**
  14213. * Bind a list of vertex buffers to the webGL context
  14214. * @param vertexBuffers defines the list of vertex buffers to bind
  14215. * @param indexBuffer defines the index buffer to bind
  14216. * @param effect defines the effect associated with the vertex buffers
  14217. */
  14218. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14219. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14220. this._cachedVertexBuffers = vertexBuffers;
  14221. this._cachedEffectForVertexBuffers = effect;
  14222. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14223. }
  14224. this._bindIndexBufferWithCache(indexBuffer);
  14225. };
  14226. /**
  14227. * Unbind all instance attributes
  14228. */
  14229. Engine.prototype.unbindInstanceAttributes = function () {
  14230. var boundBuffer;
  14231. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14232. var instancesBuffer = this._currentInstanceBuffers[i];
  14233. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14234. boundBuffer = instancesBuffer;
  14235. this.bindArrayBuffer(instancesBuffer);
  14236. }
  14237. var offsetLocation = this._currentInstanceLocations[i];
  14238. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14239. }
  14240. this._currentInstanceBuffers.length = 0;
  14241. this._currentInstanceLocations.length = 0;
  14242. };
  14243. /**
  14244. * Release and free the memory of a vertex array object
  14245. * @param vao defines the vertex array object to delete
  14246. */
  14247. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14248. this._gl.deleteVertexArray(vao);
  14249. };
  14250. /** @hidden */
  14251. Engine.prototype._releaseBuffer = function (buffer) {
  14252. buffer.references--;
  14253. if (buffer.references === 0) {
  14254. this._gl.deleteBuffer(buffer);
  14255. return true;
  14256. }
  14257. return false;
  14258. };
  14259. /**
  14260. * Creates a webGL buffer to use with instanciation
  14261. * @param capacity defines the size of the buffer
  14262. * @returns the webGL buffer
  14263. */
  14264. Engine.prototype.createInstancesBuffer = function (capacity) {
  14265. var buffer = this._gl.createBuffer();
  14266. if (!buffer) {
  14267. throw new Error("Unable to create instance buffer");
  14268. }
  14269. buffer.capacity = capacity;
  14270. this.bindArrayBuffer(buffer);
  14271. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14272. return buffer;
  14273. };
  14274. /**
  14275. * Delete a webGL buffer used with instanciation
  14276. * @param buffer defines the webGL buffer to delete
  14277. */
  14278. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14279. this._gl.deleteBuffer(buffer);
  14280. };
  14281. /**
  14282. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14283. * @param instancesBuffer defines the webGL buffer to update and bind
  14284. * @param data defines the data to store in the buffer
  14285. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14286. */
  14287. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14288. this.bindArrayBuffer(instancesBuffer);
  14289. if (data) {
  14290. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14291. }
  14292. if (offsetLocations[0].index !== undefined) {
  14293. var stride = 0;
  14294. for (var i = 0; i < offsetLocations.length; i++) {
  14295. var ai = offsetLocations[i];
  14296. stride += ai.attributeSize * 4;
  14297. }
  14298. for (var i = 0; i < offsetLocations.length; i++) {
  14299. var ai = offsetLocations[i];
  14300. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14301. this._gl.enableVertexAttribArray(ai.index);
  14302. this._vertexAttribArraysEnabled[ai.index] = true;
  14303. }
  14304. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14305. this._gl.vertexAttribDivisor(ai.index, 1);
  14306. this._currentInstanceLocations.push(ai.index);
  14307. this._currentInstanceBuffers.push(instancesBuffer);
  14308. }
  14309. }
  14310. else {
  14311. for (var index = 0; index < 4; index++) {
  14312. var offsetLocation = offsetLocations[index];
  14313. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14314. this._gl.enableVertexAttribArray(offsetLocation);
  14315. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14316. }
  14317. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14318. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14319. this._currentInstanceLocations.push(offsetLocation);
  14320. this._currentInstanceBuffers.push(instancesBuffer);
  14321. }
  14322. }
  14323. };
  14324. /**
  14325. * Apply all cached states (depth, culling, stencil and alpha)
  14326. */
  14327. Engine.prototype.applyStates = function () {
  14328. this._depthCullingState.apply(this._gl);
  14329. this._stencilState.apply(this._gl);
  14330. this._alphaState.apply(this._gl);
  14331. };
  14332. /**
  14333. * Send a draw order
  14334. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14335. * @param indexStart defines the starting index
  14336. * @param indexCount defines the number of index to draw
  14337. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14338. */
  14339. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14340. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14341. };
  14342. /**
  14343. * Draw a list of points
  14344. * @param verticesStart defines the index of first vertex to draw
  14345. * @param verticesCount defines the count of vertices to draw
  14346. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14347. */
  14348. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14349. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14350. };
  14351. /**
  14352. * Draw a list of unindexed primitives
  14353. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14354. * @param verticesStart defines the index of first vertex to draw
  14355. * @param verticesCount defines the count of vertices to draw
  14356. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14357. */
  14358. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14359. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14360. };
  14361. /**
  14362. * Draw a list of indexed primitives
  14363. * @param fillMode defines the primitive to use
  14364. * @param indexStart defines the starting index
  14365. * @param indexCount defines the number of index to draw
  14366. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14367. */
  14368. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14369. // Apply states
  14370. this.applyStates();
  14371. this._drawCalls.addCount(1, false);
  14372. // Render
  14373. var drawMode = this._drawMode(fillMode);
  14374. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14375. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14376. if (instancesCount) {
  14377. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14378. }
  14379. else {
  14380. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14381. }
  14382. };
  14383. /**
  14384. * Draw a list of unindexed primitives
  14385. * @param fillMode defines the primitive to use
  14386. * @param verticesStart defines the index of first vertex to draw
  14387. * @param verticesCount defines the count of vertices to draw
  14388. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14389. */
  14390. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14391. // Apply states
  14392. this.applyStates();
  14393. this._drawCalls.addCount(1, false);
  14394. var drawMode = this._drawMode(fillMode);
  14395. if (instancesCount) {
  14396. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14397. }
  14398. else {
  14399. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14400. }
  14401. };
  14402. Engine.prototype._drawMode = function (fillMode) {
  14403. switch (fillMode) {
  14404. // Triangle views
  14405. case BABYLON.Material.TriangleFillMode:
  14406. return this._gl.TRIANGLES;
  14407. case BABYLON.Material.PointFillMode:
  14408. return this._gl.POINTS;
  14409. case BABYLON.Material.WireFrameFillMode:
  14410. return this._gl.LINES;
  14411. // Draw modes
  14412. case BABYLON.Material.PointListDrawMode:
  14413. return this._gl.POINTS;
  14414. case BABYLON.Material.LineListDrawMode:
  14415. return this._gl.LINES;
  14416. case BABYLON.Material.LineLoopDrawMode:
  14417. return this._gl.LINE_LOOP;
  14418. case BABYLON.Material.LineStripDrawMode:
  14419. return this._gl.LINE_STRIP;
  14420. case BABYLON.Material.TriangleStripDrawMode:
  14421. return this._gl.TRIANGLE_STRIP;
  14422. case BABYLON.Material.TriangleFanDrawMode:
  14423. return this._gl.TRIANGLE_FAN;
  14424. default:
  14425. return this._gl.TRIANGLES;
  14426. }
  14427. };
  14428. // Shaders
  14429. /** @hidden */
  14430. Engine.prototype._releaseEffect = function (effect) {
  14431. if (this._compiledEffects[effect._key]) {
  14432. delete this._compiledEffects[effect._key];
  14433. this._deleteProgram(effect.getProgram());
  14434. }
  14435. };
  14436. /** @hidden */
  14437. Engine.prototype._deleteProgram = function (program) {
  14438. if (program) {
  14439. program.__SPECTOR_rebuildProgram = null;
  14440. if (program.transformFeedback) {
  14441. this.deleteTransformFeedback(program.transformFeedback);
  14442. program.transformFeedback = null;
  14443. }
  14444. this._gl.deleteProgram(program);
  14445. }
  14446. };
  14447. /**
  14448. * Create a new effect (used to store vertex/fragment shaders)
  14449. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14450. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14451. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14452. * @param samplers defines an array of string used to represent textures
  14453. * @param defines defines the string containing the defines to use to compile the shaders
  14454. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14455. * @param onCompiled defines a function to call when the effect creation is successful
  14456. * @param onError defines a function to call when the effect creation has failed
  14457. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14458. * @returns the new Effect
  14459. */
  14460. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14461. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14462. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14463. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14464. if (this._compiledEffects[name]) {
  14465. var compiledEffect = this._compiledEffects[name];
  14466. if (onCompiled && compiledEffect.isReady()) {
  14467. onCompiled(compiledEffect);
  14468. }
  14469. return compiledEffect;
  14470. }
  14471. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14472. effect._key = name;
  14473. this._compiledEffects[name] = effect;
  14474. return effect;
  14475. };
  14476. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14477. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14478. };
  14479. ;
  14480. Engine.prototype._compileRawShader = function (source, type) {
  14481. var gl = this._gl;
  14482. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14483. gl.shaderSource(shader, source);
  14484. gl.compileShader(shader);
  14485. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14486. var log = gl.getShaderInfoLog(shader);
  14487. if (log) {
  14488. throw new Error(log);
  14489. }
  14490. }
  14491. if (!shader) {
  14492. throw new Error("Something went wrong while compile the shader.");
  14493. }
  14494. return shader;
  14495. };
  14496. ;
  14497. /**
  14498. * Directly creates a webGL program
  14499. * @param vertexCode defines the vertex shader code to use
  14500. * @param fragmentCode defines the fragment shader code to use
  14501. * @param context defines the webGL context to use (if not set, the current one will be used)
  14502. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14503. * @returns the new webGL program
  14504. */
  14505. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14506. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14507. context = context || this._gl;
  14508. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14509. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14510. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14511. };
  14512. /**
  14513. * Creates a webGL program
  14514. * @param vertexCode defines the vertex shader code to use
  14515. * @param fragmentCode defines the fragment shader code to use
  14516. * @param defines defines the string containing the defines to use to compile the shaders
  14517. * @param context defines the webGL context to use (if not set, the current one will be used)
  14518. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14519. * @returns the new webGL program
  14520. */
  14521. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14522. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14523. context = context || this._gl;
  14524. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14525. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14526. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14527. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14528. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14529. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14530. return program;
  14531. };
  14532. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14533. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14534. var shaderProgram = context.createProgram();
  14535. if (!shaderProgram) {
  14536. throw new Error("Unable to create program");
  14537. }
  14538. context.attachShader(shaderProgram, vertexShader);
  14539. context.attachShader(shaderProgram, fragmentShader);
  14540. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14541. var transformFeedback = this.createTransformFeedback();
  14542. this.bindTransformFeedback(transformFeedback);
  14543. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14544. shaderProgram.transformFeedback = transformFeedback;
  14545. }
  14546. context.linkProgram(shaderProgram);
  14547. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14548. this.bindTransformFeedback(null);
  14549. }
  14550. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14551. if (!linked) {
  14552. var error = context.getProgramInfoLog(shaderProgram);
  14553. if (error) {
  14554. throw new Error(error);
  14555. }
  14556. }
  14557. if (this.validateShaderPrograms) {
  14558. context.validateProgram(shaderProgram);
  14559. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14560. if (!validated) {
  14561. var error = context.getProgramInfoLog(shaderProgram);
  14562. if (error) {
  14563. throw new Error(error);
  14564. }
  14565. }
  14566. }
  14567. context.deleteShader(vertexShader);
  14568. context.deleteShader(fragmentShader);
  14569. return shaderProgram;
  14570. };
  14571. /**
  14572. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14573. * @param shaderProgram defines the webGL program to use
  14574. * @param uniformsNames defines the list of uniform names
  14575. * @returns an array of webGL uniform locations
  14576. */
  14577. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14578. var results = new Array();
  14579. for (var index = 0; index < uniformsNames.length; index++) {
  14580. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14581. }
  14582. return results;
  14583. };
  14584. /**
  14585. * Gets the lsit of active attributes for a given webGL program
  14586. * @param shaderProgram defines the webGL program to use
  14587. * @param attributesNames defines the list of attribute names to get
  14588. * @returns an array of indices indicating the offset of each attribute
  14589. */
  14590. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14591. var results = [];
  14592. for (var index = 0; index < attributesNames.length; index++) {
  14593. try {
  14594. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14595. }
  14596. catch (e) {
  14597. results.push(-1);
  14598. }
  14599. }
  14600. return results;
  14601. };
  14602. /**
  14603. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14604. * @param effect defines the effect to activate
  14605. */
  14606. Engine.prototype.enableEffect = function (effect) {
  14607. if (!effect || effect === this._currentEffect) {
  14608. return;
  14609. }
  14610. // Use program
  14611. this.bindSamplers(effect);
  14612. this._currentEffect = effect;
  14613. if (effect.onBind) {
  14614. effect.onBind(effect);
  14615. }
  14616. if (effect._onBindObservable) {
  14617. effect._onBindObservable.notifyObservers(effect);
  14618. }
  14619. };
  14620. /**
  14621. * Set the value of an uniform to an array of int32
  14622. * @param uniform defines the webGL uniform location where to store the value
  14623. * @param array defines the array of int32 to store
  14624. */
  14625. Engine.prototype.setIntArray = function (uniform, array) {
  14626. if (!uniform)
  14627. return;
  14628. this._gl.uniform1iv(uniform, array);
  14629. };
  14630. /**
  14631. * Set the value of an uniform to an array of int32 (stored as vec2)
  14632. * @param uniform defines the webGL uniform location where to store the value
  14633. * @param array defines the array of int32 to store
  14634. */
  14635. Engine.prototype.setIntArray2 = function (uniform, array) {
  14636. if (!uniform || array.length % 2 !== 0)
  14637. return;
  14638. this._gl.uniform2iv(uniform, array);
  14639. };
  14640. /**
  14641. * Set the value of an uniform to an array of int32 (stored as vec3)
  14642. * @param uniform defines the webGL uniform location where to store the value
  14643. * @param array defines the array of int32 to store
  14644. */
  14645. Engine.prototype.setIntArray3 = function (uniform, array) {
  14646. if (!uniform || array.length % 3 !== 0)
  14647. return;
  14648. this._gl.uniform3iv(uniform, array);
  14649. };
  14650. /**
  14651. * Set the value of an uniform to an array of int32 (stored as vec4)
  14652. * @param uniform defines the webGL uniform location where to store the value
  14653. * @param array defines the array of int32 to store
  14654. */
  14655. Engine.prototype.setIntArray4 = function (uniform, array) {
  14656. if (!uniform || array.length % 4 !== 0)
  14657. return;
  14658. this._gl.uniform4iv(uniform, array);
  14659. };
  14660. /**
  14661. * Set the value of an uniform to an array of float32
  14662. * @param uniform defines the webGL uniform location where to store the value
  14663. * @param array defines the array of float32 to store
  14664. */
  14665. Engine.prototype.setFloatArray = function (uniform, array) {
  14666. if (!uniform)
  14667. return;
  14668. this._gl.uniform1fv(uniform, array);
  14669. };
  14670. /**
  14671. * Set the value of an uniform to an array of float32 (stored as vec2)
  14672. * @param uniform defines the webGL uniform location where to store the value
  14673. * @param array defines the array of float32 to store
  14674. */
  14675. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14676. if (!uniform || array.length % 2 !== 0)
  14677. return;
  14678. this._gl.uniform2fv(uniform, array);
  14679. };
  14680. /**
  14681. * Set the value of an uniform to an array of float32 (stored as vec3)
  14682. * @param uniform defines the webGL uniform location where to store the value
  14683. * @param array defines the array of float32 to store
  14684. */
  14685. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14686. if (!uniform || array.length % 3 !== 0)
  14687. return;
  14688. this._gl.uniform3fv(uniform, array);
  14689. };
  14690. /**
  14691. * Set the value of an uniform to an array of float32 (stored as vec4)
  14692. * @param uniform defines the webGL uniform location where to store the value
  14693. * @param array defines the array of float32 to store
  14694. */
  14695. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14696. if (!uniform || array.length % 4 !== 0)
  14697. return;
  14698. this._gl.uniform4fv(uniform, array);
  14699. };
  14700. /**
  14701. * Set the value of an uniform to an array of number
  14702. * @param uniform defines the webGL uniform location where to store the value
  14703. * @param array defines the array of number to store
  14704. */
  14705. Engine.prototype.setArray = function (uniform, array) {
  14706. if (!uniform)
  14707. return;
  14708. this._gl.uniform1fv(uniform, array);
  14709. };
  14710. /**
  14711. * Set the value of an uniform to an array of number (stored as vec2)
  14712. * @param uniform defines the webGL uniform location where to store the value
  14713. * @param array defines the array of number to store
  14714. */
  14715. Engine.prototype.setArray2 = function (uniform, array) {
  14716. if (!uniform || array.length % 2 !== 0)
  14717. return;
  14718. this._gl.uniform2fv(uniform, array);
  14719. };
  14720. /**
  14721. * Set the value of an uniform to an array of number (stored as vec3)
  14722. * @param uniform defines the webGL uniform location where to store the value
  14723. * @param array defines the array of number to store
  14724. */
  14725. Engine.prototype.setArray3 = function (uniform, array) {
  14726. if (!uniform || array.length % 3 !== 0)
  14727. return;
  14728. this._gl.uniform3fv(uniform, array);
  14729. };
  14730. /**
  14731. * Set the value of an uniform to an array of number (stored as vec4)
  14732. * @param uniform defines the webGL uniform location where to store the value
  14733. * @param array defines the array of number to store
  14734. */
  14735. Engine.prototype.setArray4 = function (uniform, array) {
  14736. if (!uniform || array.length % 4 !== 0)
  14737. return;
  14738. this._gl.uniform4fv(uniform, array);
  14739. };
  14740. /**
  14741. * Set the value of an uniform to an array of float32 (stored as matrices)
  14742. * @param uniform defines the webGL uniform location where to store the value
  14743. * @param matrices defines the array of float32 to store
  14744. */
  14745. Engine.prototype.setMatrices = function (uniform, matrices) {
  14746. if (!uniform)
  14747. return;
  14748. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14749. };
  14750. /**
  14751. * Set the value of an uniform to a matrix
  14752. * @param uniform defines the webGL uniform location where to store the value
  14753. * @param matrix defines the matrix to store
  14754. */
  14755. Engine.prototype.setMatrix = function (uniform, matrix) {
  14756. if (!uniform)
  14757. return;
  14758. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14759. };
  14760. /**
  14761. * Set the value of an uniform to a matrix (3x3)
  14762. * @param uniform defines the webGL uniform location where to store the value
  14763. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14764. */
  14765. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14766. if (!uniform)
  14767. return;
  14768. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14769. };
  14770. /**
  14771. * Set the value of an uniform to a matrix (2x2)
  14772. * @param uniform defines the webGL uniform location where to store the value
  14773. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14774. */
  14775. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14776. if (!uniform)
  14777. return;
  14778. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14779. };
  14780. /**
  14781. * Set the value of an uniform to a number (int)
  14782. * @param uniform defines the webGL uniform location where to store the value
  14783. * @param value defines the int number to store
  14784. */
  14785. Engine.prototype.setInt = function (uniform, value) {
  14786. if (!uniform)
  14787. return;
  14788. this._gl.uniform1i(uniform, value);
  14789. };
  14790. /**
  14791. * Set the value of an uniform to a number (float)
  14792. * @param uniform defines the webGL uniform location where to store the value
  14793. * @param value defines the float number to store
  14794. */
  14795. Engine.prototype.setFloat = function (uniform, value) {
  14796. if (!uniform)
  14797. return;
  14798. this._gl.uniform1f(uniform, value);
  14799. };
  14800. /**
  14801. * Set the value of an uniform to a vec2
  14802. * @param uniform defines the webGL uniform location where to store the value
  14803. * @param x defines the 1st component of the value
  14804. * @param y defines the 2nd component of the value
  14805. */
  14806. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14807. if (!uniform)
  14808. return;
  14809. this._gl.uniform2f(uniform, x, y);
  14810. };
  14811. /**
  14812. * Set the value of an uniform to a vec3
  14813. * @param uniform defines the webGL uniform location where to store the value
  14814. * @param x defines the 1st component of the value
  14815. * @param y defines the 2nd component of the value
  14816. * @param z defines the 3rd component of the value
  14817. */
  14818. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14819. if (!uniform)
  14820. return;
  14821. this._gl.uniform3f(uniform, x, y, z);
  14822. };
  14823. /**
  14824. * Set the value of an uniform to a boolean
  14825. * @param uniform defines the webGL uniform location where to store the value
  14826. * @param bool defines the boolean to store
  14827. */
  14828. Engine.prototype.setBool = function (uniform, bool) {
  14829. if (!uniform)
  14830. return;
  14831. this._gl.uniform1i(uniform, bool);
  14832. };
  14833. /**
  14834. * Set the value of an uniform to a vec4
  14835. * @param uniform defines the webGL uniform location where to store the value
  14836. * @param x defines the 1st component of the value
  14837. * @param y defines the 2nd component of the value
  14838. * @param z defines the 3rd component of the value
  14839. * @param w defines the 4th component of the value
  14840. */
  14841. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14842. if (!uniform)
  14843. return;
  14844. this._gl.uniform4f(uniform, x, y, z, w);
  14845. };
  14846. /**
  14847. * Set the value of an uniform to a Color3
  14848. * @param uniform defines the webGL uniform location where to store the value
  14849. * @param color3 defines the color to store
  14850. */
  14851. Engine.prototype.setColor3 = function (uniform, color3) {
  14852. if (!uniform)
  14853. return;
  14854. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14855. };
  14856. /**
  14857. * Set the value of an uniform to a Color3 and an alpha value
  14858. * @param uniform defines the webGL uniform location where to store the value
  14859. * @param color3 defines the color to store
  14860. * @param alpha defines the alpha component to store
  14861. */
  14862. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14863. if (!uniform)
  14864. return;
  14865. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14866. };
  14867. /**
  14868. * Sets a Color4 on a uniform variable
  14869. * @param uniform defines the uniform location
  14870. * @param color4 defines the value to be set
  14871. */
  14872. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14873. if (!uniform)
  14874. return;
  14875. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14876. };
  14877. // States
  14878. /**
  14879. * Set various states to the webGL context
  14880. * @param culling defines backface culling state
  14881. * @param zOffset defines the value to apply to zOffset (0 by default)
  14882. * @param force defines if states must be applied even if cache is up to date
  14883. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14884. */
  14885. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14886. if (zOffset === void 0) { zOffset = 0; }
  14887. if (reverseSide === void 0) { reverseSide = false; }
  14888. // Culling
  14889. if (this._depthCullingState.cull !== culling || force) {
  14890. this._depthCullingState.cull = culling;
  14891. }
  14892. // Cull face
  14893. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14894. if (this._depthCullingState.cullFace !== cullFace || force) {
  14895. this._depthCullingState.cullFace = cullFace;
  14896. }
  14897. // Z offset
  14898. this.setZOffset(zOffset);
  14899. // Front face
  14900. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14901. if (this._depthCullingState.frontFace !== frontFace || force) {
  14902. this._depthCullingState.frontFace = frontFace;
  14903. }
  14904. };
  14905. /**
  14906. * Set the z offset to apply to current rendering
  14907. * @param value defines the offset to apply
  14908. */
  14909. Engine.prototype.setZOffset = function (value) {
  14910. this._depthCullingState.zOffset = value;
  14911. };
  14912. /**
  14913. * Gets the current value of the zOffset
  14914. * @returns the current zOffset state
  14915. */
  14916. Engine.prototype.getZOffset = function () {
  14917. return this._depthCullingState.zOffset;
  14918. };
  14919. /**
  14920. * Enable or disable depth buffering
  14921. * @param enable defines the state to set
  14922. */
  14923. Engine.prototype.setDepthBuffer = function (enable) {
  14924. this._depthCullingState.depthTest = enable;
  14925. };
  14926. /**
  14927. * Gets a boolean indicating if depth writing is enabled
  14928. * @returns the current depth writing state
  14929. */
  14930. Engine.prototype.getDepthWrite = function () {
  14931. return this._depthCullingState.depthMask;
  14932. };
  14933. /**
  14934. * Enable or disable depth writing
  14935. * @param enable defines the state to set
  14936. */
  14937. Engine.prototype.setDepthWrite = function (enable) {
  14938. this._depthCullingState.depthMask = enable;
  14939. };
  14940. /**
  14941. * Enable or disable color writing
  14942. * @param enable defines the state to set
  14943. */
  14944. Engine.prototype.setColorWrite = function (enable) {
  14945. this._gl.colorMask(enable, enable, enable, enable);
  14946. this._colorWrite = enable;
  14947. };
  14948. /**
  14949. * Gets a boolean indicating if color writing is enabled
  14950. * @returns the current color writing state
  14951. */
  14952. Engine.prototype.getColorWrite = function () {
  14953. return this._colorWrite;
  14954. };
  14955. /**
  14956. * Sets alpha constants used by some alpha blending modes
  14957. * @param r defines the red component
  14958. * @param g defines the green component
  14959. * @param b defines the blue component
  14960. * @param a defines the alpha component
  14961. */
  14962. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14963. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14964. };
  14965. /**
  14966. * Sets the current alpha mode
  14967. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14968. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14969. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14970. */
  14971. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14972. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14973. if (this._alphaMode === mode) {
  14974. return;
  14975. }
  14976. switch (mode) {
  14977. case Engine.ALPHA_DISABLE:
  14978. this._alphaState.alphaBlend = false;
  14979. break;
  14980. case Engine.ALPHA_PREMULTIPLIED:
  14981. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14982. this._alphaState.alphaBlend = true;
  14983. break;
  14984. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14985. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14986. this._alphaState.alphaBlend = true;
  14987. break;
  14988. case Engine.ALPHA_COMBINE:
  14989. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14990. this._alphaState.alphaBlend = true;
  14991. break;
  14992. case Engine.ALPHA_ONEONE:
  14993. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14994. this._alphaState.alphaBlend = true;
  14995. break;
  14996. case Engine.ALPHA_ADD:
  14997. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14998. this._alphaState.alphaBlend = true;
  14999. break;
  15000. case Engine.ALPHA_SUBTRACT:
  15001. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15002. this._alphaState.alphaBlend = true;
  15003. break;
  15004. case Engine.ALPHA_MULTIPLY:
  15005. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15006. this._alphaState.alphaBlend = true;
  15007. break;
  15008. case Engine.ALPHA_MAXIMIZED:
  15009. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15010. this._alphaState.alphaBlend = true;
  15011. break;
  15012. case Engine.ALPHA_INTERPOLATE:
  15013. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15014. this._alphaState.alphaBlend = true;
  15015. break;
  15016. case Engine.ALPHA_SCREENMODE:
  15017. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15018. this._alphaState.alphaBlend = true;
  15019. break;
  15020. }
  15021. if (!noDepthWriteChange) {
  15022. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15023. }
  15024. this._alphaMode = mode;
  15025. };
  15026. /**
  15027. * Gets the current alpha mode
  15028. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15029. * @returns the current alpha mode
  15030. */
  15031. Engine.prototype.getAlphaMode = function () {
  15032. return this._alphaMode;
  15033. };
  15034. // Textures
  15035. /**
  15036. * Clears the list of texture accessible through engine.
  15037. * This can help preventing texture load conflict due to name collision.
  15038. */
  15039. Engine.prototype.clearInternalTexturesCache = function () {
  15040. this._internalTexturesCache = [];
  15041. };
  15042. /**
  15043. * Force the entire cache to be cleared
  15044. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15045. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15046. */
  15047. Engine.prototype.wipeCaches = function (bruteForce) {
  15048. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15049. return;
  15050. }
  15051. this._currentEffect = null;
  15052. this._viewportCached.x = 0;
  15053. this._viewportCached.y = 0;
  15054. this._viewportCached.z = 0;
  15055. this._viewportCached.w = 0;
  15056. if (bruteForce) {
  15057. this.resetTextureCache();
  15058. this._currentProgram = null;
  15059. this._stencilState.reset();
  15060. this._depthCullingState.reset();
  15061. this.setDepthFunctionToLessOrEqual();
  15062. this._alphaState.reset();
  15063. this._unpackFlipYCached = null;
  15064. }
  15065. this._resetVertexBufferBinding();
  15066. this._cachedIndexBuffer = null;
  15067. this._cachedEffectForVertexBuffers = null;
  15068. this._unbindVertexArrayObject();
  15069. this.bindIndexBuffer(null);
  15070. };
  15071. /**
  15072. * Set the compressed texture format to use, based on the formats you have, and the formats
  15073. * supported by the hardware / browser.
  15074. *
  15075. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15076. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15077. * to API arguments needed to compressed textures. This puts the burden on the container
  15078. * generator to house the arcane code for determining these for current & future formats.
  15079. *
  15080. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15081. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15082. *
  15083. * Note: The result of this call is not taken into account when a texture is base64.
  15084. *
  15085. * @param formatsAvailable defines the list of those format families you have created
  15086. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15087. *
  15088. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15089. * @returns The extension selected.
  15090. */
  15091. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15092. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15093. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15094. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15095. return this._textureFormatInUse = this._texturesSupported[i];
  15096. }
  15097. }
  15098. }
  15099. // actively set format to nothing, to allow this to be called more than once
  15100. // and possibly fail the 2nd time
  15101. this._textureFormatInUse = null;
  15102. return null;
  15103. };
  15104. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15105. var gl = this._gl;
  15106. var magFilter = gl.NEAREST;
  15107. var minFilter = gl.NEAREST;
  15108. switch (samplingMode) {
  15109. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15110. magFilter = gl.LINEAR;
  15111. if (generateMipMaps) {
  15112. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15113. }
  15114. else {
  15115. minFilter = gl.LINEAR;
  15116. }
  15117. break;
  15118. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15119. magFilter = gl.LINEAR;
  15120. if (generateMipMaps) {
  15121. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15122. }
  15123. else {
  15124. minFilter = gl.LINEAR;
  15125. }
  15126. break;
  15127. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15128. magFilter = gl.NEAREST;
  15129. if (generateMipMaps) {
  15130. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15131. }
  15132. else {
  15133. minFilter = gl.NEAREST;
  15134. }
  15135. break;
  15136. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15137. magFilter = gl.NEAREST;
  15138. if (generateMipMaps) {
  15139. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15140. }
  15141. else {
  15142. minFilter = gl.NEAREST;
  15143. }
  15144. break;
  15145. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15146. magFilter = gl.NEAREST;
  15147. if (generateMipMaps) {
  15148. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15149. }
  15150. else {
  15151. minFilter = gl.LINEAR;
  15152. }
  15153. break;
  15154. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15155. magFilter = gl.NEAREST;
  15156. if (generateMipMaps) {
  15157. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15158. }
  15159. else {
  15160. minFilter = gl.LINEAR;
  15161. }
  15162. break;
  15163. case Engine.TEXTURE_NEAREST_LINEAR:
  15164. magFilter = gl.NEAREST;
  15165. minFilter = gl.LINEAR;
  15166. break;
  15167. case Engine.TEXTURE_NEAREST_NEAREST:
  15168. magFilter = gl.NEAREST;
  15169. minFilter = gl.NEAREST;
  15170. break;
  15171. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15172. magFilter = gl.LINEAR;
  15173. if (generateMipMaps) {
  15174. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15175. }
  15176. else {
  15177. minFilter = gl.NEAREST;
  15178. }
  15179. break;
  15180. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15181. magFilter = gl.LINEAR;
  15182. if (generateMipMaps) {
  15183. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15184. }
  15185. else {
  15186. minFilter = gl.NEAREST;
  15187. }
  15188. break;
  15189. case Engine.TEXTURE_LINEAR_LINEAR:
  15190. magFilter = gl.LINEAR;
  15191. minFilter = gl.LINEAR;
  15192. break;
  15193. case Engine.TEXTURE_LINEAR_NEAREST:
  15194. magFilter = gl.LINEAR;
  15195. minFilter = gl.NEAREST;
  15196. break;
  15197. }
  15198. return {
  15199. min: minFilter,
  15200. mag: magFilter
  15201. };
  15202. };
  15203. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15204. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15205. var img;
  15206. var onload = function () {
  15207. loadedImages[index] = img;
  15208. loadedImages._internalCount++;
  15209. if (scene) {
  15210. scene._removePendingData(img);
  15211. }
  15212. if (loadedImages._internalCount === 6) {
  15213. onfinish(loadedImages);
  15214. }
  15215. };
  15216. var onerror = function (message, exception) {
  15217. if (scene) {
  15218. scene._removePendingData(img);
  15219. }
  15220. if (onErrorCallBack) {
  15221. onErrorCallBack(message, exception);
  15222. }
  15223. };
  15224. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15225. if (scene) {
  15226. scene._addPendingData(img);
  15227. }
  15228. };
  15229. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15230. if (onError === void 0) { onError = null; }
  15231. var loadedImages = [];
  15232. loadedImages._internalCount = 0;
  15233. for (var index = 0; index < 6; index++) {
  15234. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15235. }
  15236. };
  15237. ;
  15238. /** @hidden */
  15239. Engine.prototype._createTexture = function () {
  15240. var texture = this._gl.createTexture();
  15241. if (!texture) {
  15242. throw new Error("Unable to create texture");
  15243. }
  15244. return texture;
  15245. };
  15246. /**
  15247. * Usually called from BABYLON.Texture.ts.
  15248. * Passed information to create a WebGLTexture
  15249. * @param urlArg defines a value which contains one of the following:
  15250. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15251. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15252. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15253. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15254. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15255. * @param scene needed for loading to the correct scene
  15256. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15257. * @param onLoad optional callback to be called upon successful completion
  15258. * @param onError optional callback to be called upon failure
  15259. * @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
  15260. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15261. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15262. * @param forcedExtension defines the extension to use to pick the right loader
  15263. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15264. */
  15265. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15266. var _this = this;
  15267. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15268. if (onLoad === void 0) { onLoad = null; }
  15269. if (onError === void 0) { onError = null; }
  15270. if (buffer === void 0) { buffer = null; }
  15271. if (fallback === void 0) { fallback = null; }
  15272. if (format === void 0) { format = null; }
  15273. if (forcedExtension === void 0) { forcedExtension = null; }
  15274. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15275. var fromData = url.substr(0, 5) === "data:";
  15276. var fromBlob = url.substr(0, 5) === "blob:";
  15277. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15278. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15279. // establish the file extension, if possible
  15280. var lastDot = url.lastIndexOf('.');
  15281. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15282. var loader = null;
  15283. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15284. var availableLoader = _a[_i];
  15285. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15286. loader = availableLoader;
  15287. break;
  15288. }
  15289. }
  15290. if (loader) {
  15291. url = loader.transformUrl(url, this._textureFormatInUse);
  15292. }
  15293. if (scene) {
  15294. scene._addPendingData(texture);
  15295. }
  15296. texture.url = url;
  15297. texture.generateMipMaps = !noMipmap;
  15298. texture.samplingMode = samplingMode;
  15299. texture.invertY = invertY;
  15300. if (!this._doNotHandleContextLost) {
  15301. // Keep a link to the buffer only if we plan to handle context lost
  15302. texture._buffer = buffer;
  15303. }
  15304. var onLoadObserver = null;
  15305. if (onLoad && !fallback) {
  15306. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15307. }
  15308. if (!fallback)
  15309. this._internalTexturesCache.push(texture);
  15310. var onInternalError = function (message, exception) {
  15311. if (scene) {
  15312. scene._removePendingData(texture);
  15313. }
  15314. var customFallback = false;
  15315. if (loader) {
  15316. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15317. if (fallbackUrl) {
  15318. // Add Back
  15319. customFallback = true;
  15320. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15321. }
  15322. }
  15323. if (!customFallback) {
  15324. if (onLoadObserver) {
  15325. texture.onLoadedObservable.remove(onLoadObserver);
  15326. }
  15327. if (BABYLON.Tools.UseFallbackTexture) {
  15328. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15329. }
  15330. }
  15331. if (onError) {
  15332. onError(message || "Unknown error", exception);
  15333. }
  15334. };
  15335. // processing for non-image formats
  15336. if (loader) {
  15337. var callback = function (data) {
  15338. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15339. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15340. done();
  15341. return false;
  15342. }, samplingMode);
  15343. });
  15344. };
  15345. if (!buffer) {
  15346. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15347. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15348. });
  15349. }
  15350. else {
  15351. callback(buffer);
  15352. }
  15353. }
  15354. else {
  15355. var onload = function (img) {
  15356. if (fromBlob && !_this._doNotHandleContextLost) {
  15357. // We need to store the image if we need to rebuild the texture
  15358. // in case of a webgl context lost
  15359. texture._buffer = img;
  15360. }
  15361. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15362. var gl = _this._gl;
  15363. var isPot = (img.width === potWidth && img.height === potHeight);
  15364. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15365. if (isPot) {
  15366. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15367. return false;
  15368. }
  15369. var maxTextureSize = _this._caps.maxTextureSize;
  15370. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15371. _this._prepareWorkingCanvas();
  15372. if (!_this._workingCanvas || !_this._workingContext) {
  15373. return false;
  15374. }
  15375. _this._workingCanvas.width = potWidth;
  15376. _this._workingCanvas.height = potHeight;
  15377. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15378. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15379. texture.width = potWidth;
  15380. texture.height = potHeight;
  15381. return false;
  15382. }
  15383. else {
  15384. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15385. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15386. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15387. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15388. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15392. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15393. _this._releaseTexture(source_1);
  15394. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15395. continuationCallback();
  15396. });
  15397. }
  15398. return true;
  15399. }, samplingMode);
  15400. };
  15401. if (!fromData || isBase64) {
  15402. if (buffer instanceof HTMLImageElement) {
  15403. onload(buffer);
  15404. }
  15405. else {
  15406. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15407. }
  15408. }
  15409. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15410. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15411. }
  15412. else {
  15413. onload(buffer);
  15414. }
  15415. }
  15416. return texture;
  15417. };
  15418. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15419. var _this = this;
  15420. var rtt = this.createRenderTargetTexture({
  15421. width: destination.width,
  15422. height: destination.height,
  15423. }, {
  15424. generateMipMaps: false,
  15425. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15426. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15427. generateDepthBuffer: false,
  15428. generateStencilBuffer: false
  15429. });
  15430. if (!this._rescalePostProcess) {
  15431. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15432. }
  15433. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15434. _this._rescalePostProcess.onApply = function (effect) {
  15435. effect._bindTexture("textureSampler", source);
  15436. };
  15437. var hostingScene = scene;
  15438. if (!hostingScene) {
  15439. hostingScene = _this.scenes[_this.scenes.length - 1];
  15440. }
  15441. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15442. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15443. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15444. _this.unBindFramebuffer(rtt);
  15445. _this._releaseTexture(rtt);
  15446. if (onComplete) {
  15447. onComplete();
  15448. }
  15449. });
  15450. };
  15451. /**
  15452. * Update a raw texture
  15453. * @param texture defines the texture to update
  15454. * @param data defines the data to store in the texture
  15455. * @param format defines the format of the data
  15456. * @param invertY defines if data must be stored with Y axis inverted
  15457. * @param compression defines the compression used (null by default)
  15458. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15459. */
  15460. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15461. if (compression === void 0) { compression = null; }
  15462. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15463. if (!texture) {
  15464. return;
  15465. }
  15466. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15467. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15468. // babylon's internalFormat but gl's texImage2D format
  15469. var internalFormat = this._getInternalFormat(format);
  15470. var textureType = this._getWebGLTextureType(type);
  15471. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15472. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15473. if (!this._doNotHandleContextLost) {
  15474. texture._bufferView = data;
  15475. texture.format = format;
  15476. texture.type = type;
  15477. texture.invertY = invertY;
  15478. texture._compression = compression;
  15479. }
  15480. if (texture.width % 4 !== 0) {
  15481. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15482. }
  15483. if (compression && data) {
  15484. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15485. }
  15486. else {
  15487. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15488. }
  15489. if (texture.generateMipMaps) {
  15490. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15491. }
  15492. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15493. // this.resetTextureCache();
  15494. texture.isReady = true;
  15495. };
  15496. /**
  15497. * Creates a raw texture
  15498. * @param data defines the data to store in the texture
  15499. * @param width defines the width of the texture
  15500. * @param height defines the height of the texture
  15501. * @param format defines the format of the data
  15502. * @param generateMipMaps defines if the engine should generate the mip levels
  15503. * @param invertY defines if data must be stored with Y axis inverted
  15504. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15505. * @param compression defines the compression used (null by default)
  15506. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15507. * @returns the raw texture inside an InternalTexture
  15508. */
  15509. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15510. if (compression === void 0) { compression = null; }
  15511. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15512. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15513. texture.baseWidth = width;
  15514. texture.baseHeight = height;
  15515. texture.width = width;
  15516. texture.height = height;
  15517. texture.format = format;
  15518. texture.generateMipMaps = generateMipMaps;
  15519. texture.samplingMode = samplingMode;
  15520. texture.invertY = invertY;
  15521. texture._compression = compression;
  15522. texture.type = type;
  15523. if (!this._doNotHandleContextLost) {
  15524. texture._bufferView = data;
  15525. }
  15526. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15527. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15528. // Filters
  15529. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15530. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15531. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15532. if (generateMipMaps) {
  15533. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15534. }
  15535. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15536. this._internalTexturesCache.push(texture);
  15537. return texture;
  15538. };
  15539. /** @hidden */
  15540. Engine.prototype._unpackFlipY = function (value) {
  15541. if (this._unpackFlipYCached !== value) {
  15542. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15543. if (this.enableUnpackFlipYCached) {
  15544. this._unpackFlipYCached = value;
  15545. }
  15546. }
  15547. };
  15548. /** @hidden */
  15549. Engine.prototype._getUnpackAlignement = function () {
  15550. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15551. };
  15552. /**
  15553. * Creates a dynamic texture
  15554. * @param width defines the width of the texture
  15555. * @param height defines the height of the texture
  15556. * @param generateMipMaps defines if the engine should generate the mip levels
  15557. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15558. * @returns the dynamic texture inside an InternalTexture
  15559. */
  15560. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15561. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15562. texture.baseWidth = width;
  15563. texture.baseHeight = height;
  15564. if (generateMipMaps) {
  15565. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15566. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15567. }
  15568. // this.resetTextureCache();
  15569. texture.width = width;
  15570. texture.height = height;
  15571. texture.isReady = false;
  15572. texture.generateMipMaps = generateMipMaps;
  15573. texture.samplingMode = samplingMode;
  15574. this.updateTextureSamplingMode(samplingMode, texture);
  15575. this._internalTexturesCache.push(texture);
  15576. return texture;
  15577. };
  15578. /**
  15579. * Update the sampling mode of a given texture
  15580. * @param samplingMode defines the required sampling mode
  15581. * @param texture defines the texture to update
  15582. */
  15583. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15584. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15585. if (texture.isCube) {
  15586. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15587. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15588. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15589. }
  15590. else if (texture.is3D) {
  15591. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15592. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15593. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15594. }
  15595. else {
  15596. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15597. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15598. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15599. }
  15600. texture.samplingMode = samplingMode;
  15601. };
  15602. /**
  15603. * Update the content of a dynamic texture
  15604. * @param texture defines the texture to update
  15605. * @param canvas defines the canvas containing the source
  15606. * @param invertY defines if data must be stored with Y axis inverted
  15607. * @param premulAlpha defines if alpha is stored as premultiplied
  15608. * @param format defines the format of the data
  15609. */
  15610. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15611. if (premulAlpha === void 0) { premulAlpha = false; }
  15612. if (!texture) {
  15613. return;
  15614. }
  15615. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15616. this._unpackFlipY(invertY);
  15617. if (premulAlpha) {
  15618. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15619. }
  15620. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15621. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15622. if (texture.generateMipMaps) {
  15623. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15624. }
  15625. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15626. if (premulAlpha) {
  15627. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15628. }
  15629. texture.isReady = true;
  15630. };
  15631. /**
  15632. * Update a video texture
  15633. * @param texture defines the texture to update
  15634. * @param video defines the video element to use
  15635. * @param invertY defines if data must be stored with Y axis inverted
  15636. */
  15637. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15638. if (!texture || texture._isDisabled) {
  15639. return;
  15640. }
  15641. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15642. this._unpackFlipY(!invertY); // Video are upside down by default
  15643. try {
  15644. // Testing video texture support
  15645. if (this._videoTextureSupported === undefined) {
  15646. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15647. if (this._gl.getError() !== 0) {
  15648. this._videoTextureSupported = false;
  15649. }
  15650. else {
  15651. this._videoTextureSupported = true;
  15652. }
  15653. }
  15654. // Copy video through the current working canvas if video texture is not supported
  15655. if (!this._videoTextureSupported) {
  15656. if (!texture._workingCanvas) {
  15657. texture._workingCanvas = document.createElement("canvas");
  15658. var context = texture._workingCanvas.getContext("2d");
  15659. if (!context) {
  15660. throw new Error("Unable to get 2d context");
  15661. }
  15662. texture._workingContext = context;
  15663. texture._workingCanvas.width = texture.width;
  15664. texture._workingCanvas.height = texture.height;
  15665. }
  15666. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15667. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15668. }
  15669. else {
  15670. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15671. }
  15672. if (texture.generateMipMaps) {
  15673. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15674. }
  15675. if (!wasPreviouslyBound) {
  15676. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15677. }
  15678. // this.resetTextureCache();
  15679. texture.isReady = true;
  15680. }
  15681. catch (ex) {
  15682. // Something unexpected
  15683. // Let's disable the texture
  15684. texture._isDisabled = true;
  15685. }
  15686. };
  15687. /**
  15688. * Updates a depth texture Comparison Mode and Function.
  15689. * If the comparison Function is equal to 0, the mode will be set to none.
  15690. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15691. * @param texture The texture to set the comparison function for
  15692. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15693. */
  15694. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15695. if (this.webGLVersion === 1) {
  15696. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15697. return;
  15698. }
  15699. var gl = this._gl;
  15700. if (texture.isCube) {
  15701. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15702. if (comparisonFunction === 0) {
  15703. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15704. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15705. }
  15706. else {
  15707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15709. }
  15710. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15711. }
  15712. else {
  15713. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15714. if (comparisonFunction === 0) {
  15715. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15716. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15717. }
  15718. else {
  15719. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15720. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15721. }
  15722. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15723. }
  15724. texture._comparisonFunction = comparisonFunction;
  15725. };
  15726. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15727. var width = size.width || size;
  15728. var height = size.height || size;
  15729. internalTexture.baseWidth = width;
  15730. internalTexture.baseHeight = height;
  15731. internalTexture.width = width;
  15732. internalTexture.height = height;
  15733. internalTexture.isReady = true;
  15734. internalTexture.samples = 1;
  15735. internalTexture.generateMipMaps = false;
  15736. internalTexture._generateDepthBuffer = true;
  15737. internalTexture._generateStencilBuffer = generateStencil;
  15738. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15739. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15740. internalTexture._comparisonFunction = comparisonFunction;
  15741. var gl = this._gl;
  15742. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15743. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15744. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15745. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15746. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15747. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15748. if (comparisonFunction === 0) {
  15749. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15750. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15751. }
  15752. else {
  15753. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15754. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15755. }
  15756. };
  15757. /**
  15758. * Creates a depth stencil texture.
  15759. * This is only available in WebGL 2 or with the depth texture extension available.
  15760. * @param size The size of face edge in the texture.
  15761. * @param options The options defining the texture.
  15762. * @returns The texture
  15763. */
  15764. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15765. if (options.isCube) {
  15766. var width = size.width || size;
  15767. return this._createDepthStencilCubeTexture(width, options);
  15768. }
  15769. else {
  15770. return this._createDepthStencilTexture(size, options);
  15771. }
  15772. };
  15773. /**
  15774. * Creates a depth stencil texture.
  15775. * This is only available in WebGL 2 or with the depth texture extension available.
  15776. * @param size The size of face edge in the texture.
  15777. * @param options The options defining the texture.
  15778. * @returns The texture
  15779. */
  15780. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15781. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15782. if (!this._caps.depthTextureExtension) {
  15783. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15784. return internalTexture;
  15785. }
  15786. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15787. var gl = this._gl;
  15788. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15789. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15790. if (this.webGLVersion > 1) {
  15791. if (internalOptions.generateStencil) {
  15792. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15793. }
  15794. else {
  15795. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15796. }
  15797. }
  15798. else {
  15799. if (internalOptions.generateStencil) {
  15800. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15801. }
  15802. else {
  15803. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15804. }
  15805. }
  15806. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15807. return internalTexture;
  15808. };
  15809. /**
  15810. * Creates a depth stencil cube texture.
  15811. * This is only available in WebGL 2.
  15812. * @param size The size of face edge in the cube texture.
  15813. * @param options The options defining the cube texture.
  15814. * @returns The cube texture
  15815. */
  15816. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15817. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15818. internalTexture.isCube = true;
  15819. if (this.webGLVersion === 1) {
  15820. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15821. return internalTexture;
  15822. }
  15823. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15824. var gl = this._gl;
  15825. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15826. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15827. // Create the depth/stencil buffer
  15828. for (var face = 0; face < 6; face++) {
  15829. if (internalOptions.generateStencil) {
  15830. 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);
  15831. }
  15832. else {
  15833. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15834. }
  15835. }
  15836. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15837. return internalTexture;
  15838. };
  15839. /**
  15840. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15841. * @param renderTarget The render target to set the frame buffer for
  15842. */
  15843. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15844. // Create the framebuffer
  15845. var internalTexture = renderTarget.getInternalTexture();
  15846. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15847. return;
  15848. }
  15849. var gl = this._gl;
  15850. var depthStencilTexture = renderTarget.depthStencilTexture;
  15851. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15852. if (depthStencilTexture.isCube) {
  15853. if (depthStencilTexture._generateStencilBuffer) {
  15854. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15855. }
  15856. else {
  15857. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15858. }
  15859. }
  15860. else {
  15861. if (depthStencilTexture._generateStencilBuffer) {
  15862. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15863. }
  15864. else {
  15865. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15866. }
  15867. }
  15868. this.bindUnboundFramebuffer(null);
  15869. };
  15870. /**
  15871. * Creates a new render target texture
  15872. * @param size defines the size of the texture
  15873. * @param options defines the options used to create the texture
  15874. * @returns a new render target texture stored in an InternalTexture
  15875. */
  15876. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15877. var fullOptions = new RenderTargetCreationOptions();
  15878. if (options !== undefined && typeof options === "object") {
  15879. fullOptions.generateMipMaps = options.generateMipMaps;
  15880. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15881. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15882. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15883. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15884. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15885. }
  15886. else {
  15887. fullOptions.generateMipMaps = options;
  15888. fullOptions.generateDepthBuffer = true;
  15889. fullOptions.generateStencilBuffer = false;
  15890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15891. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15892. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15893. }
  15894. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15895. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15896. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15897. }
  15898. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15899. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15900. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15901. }
  15902. var gl = this._gl;
  15903. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15904. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15905. var width = size.width || size;
  15906. var height = size.height || size;
  15907. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15908. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15909. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15910. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15911. }
  15912. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15915. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15916. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15917. // Create the framebuffer
  15918. var currentFrameBuffer = this._currentFramebuffer;
  15919. var framebuffer = gl.createFramebuffer();
  15920. this.bindUnboundFramebuffer(framebuffer);
  15921. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15922. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15923. if (fullOptions.generateMipMaps) {
  15924. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15925. }
  15926. // Unbind
  15927. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15928. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15929. this.bindUnboundFramebuffer(currentFrameBuffer);
  15930. texture._framebuffer = framebuffer;
  15931. texture.baseWidth = width;
  15932. texture.baseHeight = height;
  15933. texture.width = width;
  15934. texture.height = height;
  15935. texture.isReady = true;
  15936. texture.samples = 1;
  15937. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15938. texture.samplingMode = fullOptions.samplingMode;
  15939. texture.type = fullOptions.type;
  15940. texture.format = fullOptions.format;
  15941. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15942. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15943. // this.resetTextureCache();
  15944. this._internalTexturesCache.push(texture);
  15945. return texture;
  15946. };
  15947. /**
  15948. * Create a multi render target texture
  15949. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15950. * @param size defines the size of the texture
  15951. * @param options defines the creation options
  15952. * @returns the cube texture as an InternalTexture
  15953. */
  15954. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15955. var generateMipMaps = false;
  15956. var generateDepthBuffer = true;
  15957. var generateStencilBuffer = false;
  15958. var generateDepthTexture = false;
  15959. var textureCount = 1;
  15960. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15961. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15962. var types = new Array();
  15963. var samplingModes = new Array();
  15964. if (options !== undefined) {
  15965. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15966. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15967. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15968. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15969. textureCount = options.textureCount || 1;
  15970. if (options.types) {
  15971. types = options.types;
  15972. }
  15973. if (options.samplingModes) {
  15974. samplingModes = options.samplingModes;
  15975. }
  15976. }
  15977. var gl = this._gl;
  15978. // Create the framebuffer
  15979. var framebuffer = gl.createFramebuffer();
  15980. this.bindUnboundFramebuffer(framebuffer);
  15981. var width = size.width || size;
  15982. var height = size.height || size;
  15983. var textures = [];
  15984. var attachments = [];
  15985. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15986. for (var i = 0; i < textureCount; i++) {
  15987. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15988. var type = types[i] || defaultType;
  15989. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15990. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15991. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15992. }
  15993. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15994. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15995. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15996. }
  15997. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15998. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15999. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16000. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16001. }
  16002. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16003. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16004. textures.push(texture);
  16005. attachments.push(attachment);
  16006. gl.activeTexture(gl["TEXTURE" + i]);
  16007. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16012. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16013. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16014. if (generateMipMaps) {
  16015. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16016. }
  16017. // Unbind
  16018. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16019. texture._framebuffer = framebuffer;
  16020. texture._depthStencilBuffer = depthStencilBuffer;
  16021. texture.baseWidth = width;
  16022. texture.baseHeight = height;
  16023. texture.width = width;
  16024. texture.height = height;
  16025. texture.isReady = true;
  16026. texture.samples = 1;
  16027. texture.generateMipMaps = generateMipMaps;
  16028. texture.samplingMode = samplingMode;
  16029. texture.type = type;
  16030. texture._generateDepthBuffer = generateDepthBuffer;
  16031. texture._generateStencilBuffer = generateStencilBuffer;
  16032. texture._attachments = attachments;
  16033. this._internalTexturesCache.push(texture);
  16034. }
  16035. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16036. // Depth texture
  16037. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16038. gl.activeTexture(gl.TEXTURE0);
  16039. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16040. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16041. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16042. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16043. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16044. 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);
  16045. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16046. depthTexture._framebuffer = framebuffer;
  16047. depthTexture.baseWidth = width;
  16048. depthTexture.baseHeight = height;
  16049. depthTexture.width = width;
  16050. depthTexture.height = height;
  16051. depthTexture.isReady = true;
  16052. depthTexture.samples = 1;
  16053. depthTexture.generateMipMaps = generateMipMaps;
  16054. depthTexture.samplingMode = gl.NEAREST;
  16055. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16056. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16057. textures.push(depthTexture);
  16058. this._internalTexturesCache.push(depthTexture);
  16059. }
  16060. gl.drawBuffers(attachments);
  16061. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16062. this.bindUnboundFramebuffer(null);
  16063. this.resetTextureCache();
  16064. return textures;
  16065. };
  16066. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16067. if (samples === void 0) { samples = 1; }
  16068. var depthStencilBuffer = null;
  16069. var gl = this._gl;
  16070. // Create the depth/stencil buffer
  16071. if (generateStencilBuffer) {
  16072. depthStencilBuffer = gl.createRenderbuffer();
  16073. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16074. if (samples > 1) {
  16075. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16076. }
  16077. else {
  16078. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16079. }
  16080. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16081. }
  16082. else if (generateDepthBuffer) {
  16083. depthStencilBuffer = gl.createRenderbuffer();
  16084. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16085. if (samples > 1) {
  16086. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16087. }
  16088. else {
  16089. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16090. }
  16091. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16092. }
  16093. return depthStencilBuffer;
  16094. };
  16095. /**
  16096. * Updates the sample count of a render target texture
  16097. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16098. * @param texture defines the texture to update
  16099. * @param samples defines the sample count to set
  16100. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16101. */
  16102. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16103. if (this.webGLVersion < 2 || !texture) {
  16104. return 1;
  16105. }
  16106. if (texture.samples === samples) {
  16107. return samples;
  16108. }
  16109. var gl = this._gl;
  16110. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16111. // Dispose previous render buffers
  16112. if (texture._depthStencilBuffer) {
  16113. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16114. texture._depthStencilBuffer = null;
  16115. }
  16116. if (texture._MSAAFramebuffer) {
  16117. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16118. texture._MSAAFramebuffer = null;
  16119. }
  16120. if (texture._MSAARenderBuffer) {
  16121. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16122. texture._MSAARenderBuffer = null;
  16123. }
  16124. if (samples > 1) {
  16125. var framebuffer = gl.createFramebuffer();
  16126. if (!framebuffer) {
  16127. throw new Error("Unable to create multi sampled framebuffer");
  16128. }
  16129. texture._MSAAFramebuffer = framebuffer;
  16130. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16131. var colorRenderbuffer = gl.createRenderbuffer();
  16132. if (!colorRenderbuffer) {
  16133. throw new Error("Unable to create multi sampled framebuffer");
  16134. }
  16135. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16136. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16137. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16138. texture._MSAARenderBuffer = colorRenderbuffer;
  16139. }
  16140. else {
  16141. this.bindUnboundFramebuffer(texture._framebuffer);
  16142. }
  16143. texture.samples = samples;
  16144. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16145. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16146. this.bindUnboundFramebuffer(null);
  16147. return samples;
  16148. };
  16149. /**
  16150. * Update the sample count for a given multiple render target texture
  16151. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16152. * @param textures defines the textures to update
  16153. * @param samples defines the sample count to set
  16154. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16155. */
  16156. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16157. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16158. return 1;
  16159. }
  16160. if (textures[0].samples === samples) {
  16161. return samples;
  16162. }
  16163. var gl = this._gl;
  16164. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16165. // Dispose previous render buffers
  16166. if (textures[0]._depthStencilBuffer) {
  16167. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16168. textures[0]._depthStencilBuffer = null;
  16169. }
  16170. if (textures[0]._MSAAFramebuffer) {
  16171. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16172. textures[0]._MSAAFramebuffer = null;
  16173. }
  16174. for (var i = 0; i < textures.length; i++) {
  16175. if (textures[i]._MSAARenderBuffer) {
  16176. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16177. textures[i]._MSAARenderBuffer = null;
  16178. }
  16179. }
  16180. if (samples > 1) {
  16181. var framebuffer = gl.createFramebuffer();
  16182. if (!framebuffer) {
  16183. throw new Error("Unable to create multi sampled framebuffer");
  16184. }
  16185. this.bindUnboundFramebuffer(framebuffer);
  16186. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16187. var attachments = [];
  16188. for (var i = 0; i < textures.length; i++) {
  16189. var texture = textures[i];
  16190. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16191. var colorRenderbuffer = gl.createRenderbuffer();
  16192. if (!colorRenderbuffer) {
  16193. throw new Error("Unable to create multi sampled framebuffer");
  16194. }
  16195. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16196. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16197. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16198. texture._MSAAFramebuffer = framebuffer;
  16199. texture._MSAARenderBuffer = colorRenderbuffer;
  16200. texture.samples = samples;
  16201. texture._depthStencilBuffer = depthStencilBuffer;
  16202. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16203. attachments.push(attachment);
  16204. }
  16205. gl.drawBuffers(attachments);
  16206. }
  16207. else {
  16208. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16209. }
  16210. this.bindUnboundFramebuffer(null);
  16211. return samples;
  16212. };
  16213. /** @hidden */
  16214. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16215. if (faceIndex === void 0) { faceIndex = 0; }
  16216. if (lod === void 0) { lod = 0; }
  16217. var gl = this._gl;
  16218. var target = gl.TEXTURE_2D;
  16219. if (texture.isCube) {
  16220. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16221. }
  16222. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16223. };
  16224. /** @hidden */
  16225. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16226. if (faceIndex === void 0) { faceIndex = 0; }
  16227. if (lod === void 0) { lod = 0; }
  16228. var gl = this._gl;
  16229. var textureType = this._getWebGLTextureType(texture.type);
  16230. var format = this._getInternalFormat(texture.format);
  16231. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16232. this._unpackFlipY(texture.invertY);
  16233. var target = gl.TEXTURE_2D;
  16234. if (texture.isCube) {
  16235. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16236. }
  16237. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16238. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16239. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16240. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16241. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16242. };
  16243. /** @hidden */
  16244. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16245. if (faceIndex === void 0) { faceIndex = 0; }
  16246. if (lod === void 0) { lod = 0; }
  16247. var gl = this._gl;
  16248. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16249. this._bindTextureDirectly(bindTarget, texture, true);
  16250. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16251. this._bindTextureDirectly(bindTarget, null, true);
  16252. };
  16253. /** @hidden */
  16254. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16255. if (faceIndex === void 0) { faceIndex = 0; }
  16256. if (lod === void 0) { lod = 0; }
  16257. var gl = this._gl;
  16258. var textureType = this._getWebGLTextureType(texture.type);
  16259. var format = this._getInternalFormat(texture.format);
  16260. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16261. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16262. this._bindTextureDirectly(bindTarget, texture, true);
  16263. this._unpackFlipY(texture.invertY);
  16264. var target = gl.TEXTURE_2D;
  16265. if (texture.isCube) {
  16266. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16267. }
  16268. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16269. this._bindTextureDirectly(bindTarget, null, true);
  16270. };
  16271. /**
  16272. * Creates a new render target cube texture
  16273. * @param size defines the size of the texture
  16274. * @param options defines the options used to create the texture
  16275. * @returns a new render target cube texture stored in an InternalTexture
  16276. */
  16277. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16278. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16279. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16280. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16281. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16282. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16283. }
  16284. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16285. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16286. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16287. }
  16288. var gl = this._gl;
  16289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16290. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16291. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16292. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16293. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16294. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16295. }
  16296. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16297. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16298. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16299. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16300. for (var face = 0; face < 6; face++) {
  16301. 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);
  16302. }
  16303. // Create the framebuffer
  16304. var framebuffer = gl.createFramebuffer();
  16305. this.bindUnboundFramebuffer(framebuffer);
  16306. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16307. // MipMaps
  16308. if (fullOptions.generateMipMaps) {
  16309. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16310. }
  16311. // Unbind
  16312. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16313. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16314. this.bindUnboundFramebuffer(null);
  16315. texture._framebuffer = framebuffer;
  16316. texture.width = size;
  16317. texture.height = size;
  16318. texture.isReady = true;
  16319. texture.isCube = true;
  16320. texture.samples = 1;
  16321. texture.generateMipMaps = fullOptions.generateMipMaps;
  16322. texture.samplingMode = fullOptions.samplingMode;
  16323. texture.type = fullOptions.type;
  16324. texture.format = fullOptions.format;
  16325. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16326. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16327. this._internalTexturesCache.push(texture);
  16328. return texture;
  16329. };
  16330. /**
  16331. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16332. * @param rootUrl defines the url where the file to load is located
  16333. * @param scene defines the current scene
  16334. * @param lodScale defines scale to apply to the mip map selection
  16335. * @param lodOffset defines offset to apply to the mip map selection
  16336. * @param onLoad defines an optional callback raised when the texture is loaded
  16337. * @param onError defines an optional callback raised if there is an issue to load the texture
  16338. * @param format defines the format of the data
  16339. * @param forcedExtension defines the extension to use to pick the right loader
  16340. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16341. * @returns the cube texture as an InternalTexture
  16342. */
  16343. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16344. var _this = this;
  16345. if (onLoad === void 0) { onLoad = null; }
  16346. if (onError === void 0) { onError = null; }
  16347. if (forcedExtension === void 0) { forcedExtension = null; }
  16348. if (createPolynomials === void 0) { createPolynomials = true; }
  16349. var callback = function (loadData) {
  16350. if (!loadData) {
  16351. if (onLoad) {
  16352. onLoad(null);
  16353. }
  16354. return;
  16355. }
  16356. var texture = loadData.texture;
  16357. if (!createPolynomials) {
  16358. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16359. }
  16360. else if (loadData.info.sphericalPolynomial) {
  16361. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16362. }
  16363. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16364. if (_this._caps.textureLOD) {
  16365. // Do not add extra process if texture lod is supported.
  16366. if (onLoad) {
  16367. onLoad(texture);
  16368. }
  16369. return;
  16370. }
  16371. var mipSlices = 3;
  16372. var gl = _this._gl;
  16373. var width = loadData.width;
  16374. if (!width) {
  16375. return;
  16376. }
  16377. var textures = [];
  16378. for (var i = 0; i < mipSlices; i++) {
  16379. //compute LOD from even spacing in smoothness (matching shader calculation)
  16380. var smoothness = i / (mipSlices - 1);
  16381. var roughness = 1 - smoothness;
  16382. var minLODIndex = lodOffset; // roughness = 0
  16383. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16384. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16385. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16386. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16387. glTextureFromLod.type = texture.type;
  16388. glTextureFromLod.format = texture.format;
  16389. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16390. glTextureFromLod.height = glTextureFromLod.width;
  16391. glTextureFromLod.isCube = true;
  16392. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16394. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16397. if (loadData.isDDS) {
  16398. var info = loadData.info;
  16399. var data = loadData.data;
  16400. _this._unpackFlipY(info.isCompressed);
  16401. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16402. }
  16403. else {
  16404. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16405. }
  16406. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16407. // Wrap in a base texture for easy binding.
  16408. var lodTexture = new BABYLON.BaseTexture(scene);
  16409. lodTexture.isCube = true;
  16410. lodTexture._texture = glTextureFromLod;
  16411. glTextureFromLod.isReady = true;
  16412. textures.push(lodTexture);
  16413. }
  16414. texture._lodTextureHigh = textures[2];
  16415. texture._lodTextureMid = textures[1];
  16416. texture._lodTextureLow = textures[0];
  16417. if (onLoad) {
  16418. onLoad(texture);
  16419. }
  16420. };
  16421. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16422. };
  16423. /**
  16424. * Creates a cube texture
  16425. * @param rootUrl defines the url where the files to load is located
  16426. * @param scene defines the current scene
  16427. * @param files defines the list of files to load (1 per face)
  16428. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16429. * @param onLoad defines an optional callback raised when the texture is loaded
  16430. * @param onError defines an optional callback raised if there is an issue to load the texture
  16431. * @param format defines the format of the data
  16432. * @param forcedExtension defines the extension to use to pick the right loader
  16433. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16434. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16435. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16436. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16437. * @returns the cube texture as an InternalTexture
  16438. */
  16439. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16440. var _this = this;
  16441. if (onLoad === void 0) { onLoad = null; }
  16442. if (onError === void 0) { onError = null; }
  16443. if (forcedExtension === void 0) { forcedExtension = null; }
  16444. if (createPolynomials === void 0) { createPolynomials = false; }
  16445. if (lodScale === void 0) { lodScale = 0; }
  16446. if (lodOffset === void 0) { lodOffset = 0; }
  16447. if (fallback === void 0) { fallback = null; }
  16448. var gl = this._gl;
  16449. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16450. texture.isCube = true;
  16451. texture.url = rootUrl;
  16452. texture.generateMipMaps = !noMipmap;
  16453. texture._lodGenerationScale = lodScale;
  16454. texture._lodGenerationOffset = lodOffset;
  16455. if (!this._doNotHandleContextLost) {
  16456. texture._extension = forcedExtension;
  16457. texture._files = files;
  16458. }
  16459. var lastDot = rootUrl.lastIndexOf('.');
  16460. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16461. var loader = null;
  16462. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16463. var availableLoader = _a[_i];
  16464. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16465. loader = availableLoader;
  16466. break;
  16467. }
  16468. }
  16469. var onInternalError = function (request, exception) {
  16470. if (loader) {
  16471. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16472. if (fallbackUrl) {
  16473. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16474. }
  16475. }
  16476. if (onError && request) {
  16477. onError(request.status + " " + request.statusText, exception);
  16478. }
  16479. };
  16480. if (loader) {
  16481. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16482. var onloaddata = function (data) {
  16483. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16484. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16485. };
  16486. if (files && files.length === 6) {
  16487. if (loader.supportCascades) {
  16488. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16489. }
  16490. else if (onError) {
  16491. onError("Textures type does not support cascades.");
  16492. }
  16493. }
  16494. else {
  16495. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16496. }
  16497. }
  16498. else {
  16499. if (!files) {
  16500. throw new Error("Cannot load cubemap because files were not defined");
  16501. }
  16502. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16503. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16504. var height = width;
  16505. _this._prepareWorkingCanvas();
  16506. if (!_this._workingCanvas || !_this._workingContext) {
  16507. return;
  16508. }
  16509. _this._workingCanvas.width = width;
  16510. _this._workingCanvas.height = height;
  16511. var faces = [
  16512. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16513. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16514. ];
  16515. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16516. _this._unpackFlipY(false);
  16517. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16518. for (var index = 0; index < faces.length; index++) {
  16519. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16520. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16521. }
  16522. if (!noMipmap) {
  16523. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16524. }
  16525. _this._setCubeMapTextureParams(!noMipmap);
  16526. texture.width = width;
  16527. texture.height = height;
  16528. texture.isReady = true;
  16529. if (format) {
  16530. texture.format = format;
  16531. }
  16532. texture.onLoadedObservable.notifyObservers(texture);
  16533. texture.onLoadedObservable.clear();
  16534. if (onLoad) {
  16535. onLoad();
  16536. }
  16537. }, files, onError);
  16538. }
  16539. this._internalTexturesCache.push(texture);
  16540. return texture;
  16541. };
  16542. /**
  16543. * @hidden
  16544. */
  16545. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16546. var gl = this._gl;
  16547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16551. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16552. // this.resetTextureCache();
  16553. };
  16554. /**
  16555. * Update a raw cube texture
  16556. * @param texture defines the texture to udpdate
  16557. * @param data defines the data to store
  16558. * @param format defines the data format
  16559. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16560. * @param invertY defines if data must be stored with Y axis inverted
  16561. * @param compression defines the compression used (null by default)
  16562. * @param level defines which level of the texture to update
  16563. */
  16564. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16565. if (compression === void 0) { compression = null; }
  16566. if (level === void 0) { level = 0; }
  16567. texture._bufferViewArray = data;
  16568. texture.format = format;
  16569. texture.type = type;
  16570. texture.invertY = invertY;
  16571. texture._compression = compression;
  16572. var gl = this._gl;
  16573. var textureType = this._getWebGLTextureType(type);
  16574. var internalFormat = this._getInternalFormat(format);
  16575. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16576. var needConversion = false;
  16577. if (internalFormat === gl.RGB) {
  16578. internalFormat = gl.RGBA;
  16579. needConversion = true;
  16580. }
  16581. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16582. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16583. if (texture.width % 4 !== 0) {
  16584. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16585. }
  16586. // Data are known to be in +X +Y +Z -X -Y -Z
  16587. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16588. var faceData = data[faceIndex];
  16589. if (compression) {
  16590. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16591. }
  16592. else {
  16593. if (needConversion) {
  16594. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16595. }
  16596. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16597. }
  16598. }
  16599. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16600. if (isPot && texture.generateMipMaps && level === 0) {
  16601. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16602. }
  16603. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16604. // this.resetTextureCache();
  16605. texture.isReady = true;
  16606. };
  16607. /**
  16608. * Creates a new raw cube texture
  16609. * @param data defines the array of data to use to create each face
  16610. * @param size defines the size of the textures
  16611. * @param format defines the format of the data
  16612. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16613. * @param generateMipMaps defines if the engine should generate the mip levels
  16614. * @param invertY defines if data must be stored with Y axis inverted
  16615. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16616. * @param compression defines the compression used (null by default)
  16617. * @returns the cube texture as an InternalTexture
  16618. */
  16619. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16620. if (compression === void 0) { compression = null; }
  16621. var gl = this._gl;
  16622. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16623. texture.isCube = true;
  16624. texture.format = format;
  16625. texture.type = type;
  16626. if (!this._doNotHandleContextLost) {
  16627. texture._bufferViewArray = data;
  16628. }
  16629. var textureType = this._getWebGLTextureType(type);
  16630. var internalFormat = this._getInternalFormat(format);
  16631. if (internalFormat === gl.RGB) {
  16632. internalFormat = gl.RGBA;
  16633. }
  16634. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16635. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16636. generateMipMaps = false;
  16637. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16638. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16639. }
  16640. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16641. generateMipMaps = false;
  16642. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16643. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16644. }
  16645. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16646. generateMipMaps = false;
  16647. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16648. }
  16649. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16650. generateMipMaps = false;
  16651. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16652. }
  16653. var width = size;
  16654. var height = width;
  16655. texture.width = width;
  16656. texture.height = height;
  16657. // Double check on POT to generate Mips.
  16658. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16659. if (!isPot) {
  16660. generateMipMaps = false;
  16661. }
  16662. // Upload data if needed. The texture won't be ready until then.
  16663. if (data) {
  16664. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16665. }
  16666. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16667. // Filters
  16668. if (data && generateMipMaps) {
  16669. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16670. }
  16671. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16673. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16674. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16675. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16676. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16677. texture.generateMipMaps = generateMipMaps;
  16678. return texture;
  16679. };
  16680. /**
  16681. * Creates a new raw cube texture from a specified url
  16682. * @param url defines the url where the data is located
  16683. * @param scene defines the current scene
  16684. * @param size defines the size of the textures
  16685. * @param format defines the format of the data
  16686. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16687. * @param noMipmap defines if the engine should avoid generating the mip levels
  16688. * @param callback defines a callback used to extract texture data from loaded data
  16689. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16690. * @param onLoad defines a callback called when texture is loaded
  16691. * @param onError defines a callback called if there is an error
  16692. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16693. * @param invertY defines if data must be stored with Y axis inverted
  16694. * @returns the cube texture as an InternalTexture
  16695. */
  16696. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16697. var _this = this;
  16698. if (onLoad === void 0) { onLoad = null; }
  16699. if (onError === void 0) { onError = null; }
  16700. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16701. if (invertY === void 0) { invertY = false; }
  16702. var gl = this._gl;
  16703. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16704. scene._addPendingData(texture);
  16705. texture.url = url;
  16706. this._internalTexturesCache.push(texture);
  16707. var onerror = function (request, exception) {
  16708. scene._removePendingData(texture);
  16709. if (onError && request) {
  16710. onError(request.status + " " + request.statusText, exception);
  16711. }
  16712. };
  16713. var internalCallback = function (data) {
  16714. var width = texture.width;
  16715. var faceDataArrays = callback(data);
  16716. if (!faceDataArrays) {
  16717. return;
  16718. }
  16719. if (mipmapGenerator) {
  16720. var textureType = _this._getWebGLTextureType(type);
  16721. var internalFormat = _this._getInternalFormat(format);
  16722. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16723. var needConversion = false;
  16724. if (internalFormat === gl.RGB) {
  16725. internalFormat = gl.RGBA;
  16726. needConversion = true;
  16727. }
  16728. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16729. _this._unpackFlipY(false);
  16730. var mipData = mipmapGenerator(faceDataArrays);
  16731. for (var level = 0; level < mipData.length; level++) {
  16732. var mipSize = width >> level;
  16733. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16734. var mipFaceData = mipData[level][faceIndex];
  16735. if (needConversion) {
  16736. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16737. }
  16738. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16739. }
  16740. }
  16741. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16742. }
  16743. else {
  16744. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16745. }
  16746. texture.isReady = true;
  16747. // this.resetTextureCache();
  16748. scene._removePendingData(texture);
  16749. if (onLoad) {
  16750. onLoad();
  16751. }
  16752. };
  16753. this._loadFile(url, function (data) {
  16754. internalCallback(data);
  16755. }, undefined, scene.database, true, onerror);
  16756. return texture;
  16757. };
  16758. ;
  16759. /**
  16760. * Update a raw 3D texture
  16761. * @param texture defines the texture to update
  16762. * @param data defines the data to store
  16763. * @param format defines the data format
  16764. * @param invertY defines if data must be stored with Y axis inverted
  16765. * @param compression defines the used compression (can be null)
  16766. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16767. */
  16768. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16769. if (compression === void 0) { compression = null; }
  16770. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16771. var internalType = this._getWebGLTextureType(textureType);
  16772. var internalFormat = this._getInternalFormat(format);
  16773. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16774. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16775. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16776. if (!this._doNotHandleContextLost) {
  16777. texture._bufferView = data;
  16778. texture.format = format;
  16779. texture.invertY = invertY;
  16780. texture._compression = compression;
  16781. }
  16782. if (texture.width % 4 !== 0) {
  16783. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16784. }
  16785. if (compression && data) {
  16786. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16787. }
  16788. else {
  16789. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16790. }
  16791. if (texture.generateMipMaps) {
  16792. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16793. }
  16794. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16795. // this.resetTextureCache();
  16796. texture.isReady = true;
  16797. };
  16798. /**
  16799. * Creates a new raw 3D texture
  16800. * @param data defines the data used to create the texture
  16801. * @param width defines the width of the texture
  16802. * @param height defines the height of the texture
  16803. * @param depth defines the depth of the texture
  16804. * @param format defines the format of the texture
  16805. * @param generateMipMaps defines if the engine must generate mip levels
  16806. * @param invertY defines if data must be stored with Y axis inverted
  16807. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16808. * @param compression defines the compressed used (can be null)
  16809. * @param textureType defines the compressed used (can be null)
  16810. * @returns a new raw 3D texture (stored in an InternalTexture)
  16811. */
  16812. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16813. if (compression === void 0) { compression = null; }
  16814. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16815. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16816. texture.baseWidth = width;
  16817. texture.baseHeight = height;
  16818. texture.baseDepth = depth;
  16819. texture.width = width;
  16820. texture.height = height;
  16821. texture.depth = depth;
  16822. texture.format = format;
  16823. texture.type = textureType;
  16824. texture.generateMipMaps = generateMipMaps;
  16825. texture.samplingMode = samplingMode;
  16826. texture.is3D = true;
  16827. if (!this._doNotHandleContextLost) {
  16828. texture._bufferView = data;
  16829. }
  16830. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16831. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16832. // Filters
  16833. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16834. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16835. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16836. if (generateMipMaps) {
  16837. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16838. }
  16839. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16840. this._internalTexturesCache.push(texture);
  16841. return texture;
  16842. };
  16843. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16844. var gl = this._gl;
  16845. if (!gl) {
  16846. return;
  16847. }
  16848. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16849. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16850. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16851. if (!noMipmap && !isCompressed) {
  16852. gl.generateMipmap(gl.TEXTURE_2D);
  16853. }
  16854. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16855. // this.resetTextureCache();
  16856. if (scene) {
  16857. scene._removePendingData(texture);
  16858. }
  16859. texture.onLoadedObservable.notifyObservers(texture);
  16860. texture.onLoadedObservable.clear();
  16861. };
  16862. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16863. var _this = this;
  16864. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16865. var maxTextureSize = this.getCaps().maxTextureSize;
  16866. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16867. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16868. var gl = this._gl;
  16869. if (!gl) {
  16870. return;
  16871. }
  16872. if (!texture._webGLTexture) {
  16873. // this.resetTextureCache();
  16874. if (scene) {
  16875. scene._removePendingData(texture);
  16876. }
  16877. return;
  16878. }
  16879. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16880. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16881. texture.baseWidth = width;
  16882. texture.baseHeight = height;
  16883. texture.width = potWidth;
  16884. texture.height = potHeight;
  16885. texture.isReady = true;
  16886. if (processFunction(potWidth, potHeight, function () {
  16887. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16888. })) {
  16889. // Returning as texture needs extra async steps
  16890. return;
  16891. }
  16892. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16893. };
  16894. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16895. // Create new RGBA data container.
  16896. var rgbaData;
  16897. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16898. rgbaData = new Float32Array(width * height * 4);
  16899. }
  16900. else {
  16901. rgbaData = new Uint32Array(width * height * 4);
  16902. }
  16903. // Convert each pixel.
  16904. for (var x = 0; x < width; x++) {
  16905. for (var y = 0; y < height; y++) {
  16906. var index = (y * width + x) * 3;
  16907. var newIndex = (y * width + x) * 4;
  16908. // Map Old Value to new value.
  16909. rgbaData[newIndex + 0] = rgbData[index + 0];
  16910. rgbaData[newIndex + 1] = rgbData[index + 1];
  16911. rgbaData[newIndex + 2] = rgbData[index + 2];
  16912. // Add fully opaque alpha channel.
  16913. rgbaData[newIndex + 3] = 1;
  16914. }
  16915. }
  16916. return rgbaData;
  16917. };
  16918. /** @hidden */
  16919. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16920. var gl = this._gl;
  16921. if (texture._framebuffer) {
  16922. gl.deleteFramebuffer(texture._framebuffer);
  16923. texture._framebuffer = null;
  16924. }
  16925. if (texture._depthStencilBuffer) {
  16926. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16927. texture._depthStencilBuffer = null;
  16928. }
  16929. if (texture._MSAAFramebuffer) {
  16930. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16931. texture._MSAAFramebuffer = null;
  16932. }
  16933. if (texture._MSAARenderBuffer) {
  16934. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16935. texture._MSAARenderBuffer = null;
  16936. }
  16937. };
  16938. /** @hidden */
  16939. Engine.prototype._releaseTexture = function (texture) {
  16940. var gl = this._gl;
  16941. this._releaseFramebufferObjects(texture);
  16942. gl.deleteTexture(texture._webGLTexture);
  16943. // Unbind channels
  16944. this.unbindAllTextures();
  16945. var index = this._internalTexturesCache.indexOf(texture);
  16946. if (index !== -1) {
  16947. this._internalTexturesCache.splice(index, 1);
  16948. }
  16949. // Integrated fixed lod samplers.
  16950. if (texture._lodTextureHigh) {
  16951. texture._lodTextureHigh.dispose();
  16952. }
  16953. if (texture._lodTextureMid) {
  16954. texture._lodTextureMid.dispose();
  16955. }
  16956. if (texture._lodTextureLow) {
  16957. texture._lodTextureLow.dispose();
  16958. }
  16959. // Set output texture of post process to null if the texture has been released/disposed
  16960. this.scenes.forEach(function (scene) {
  16961. scene.postProcesses.forEach(function (postProcess) {
  16962. if (postProcess._outputTexture == texture) {
  16963. postProcess._outputTexture = null;
  16964. }
  16965. });
  16966. scene.cameras.forEach(function (camera) {
  16967. camera._postProcesses.forEach(function (postProcess) {
  16968. if (postProcess) {
  16969. if (postProcess._outputTexture == texture) {
  16970. postProcess._outputTexture = null;
  16971. }
  16972. }
  16973. });
  16974. });
  16975. });
  16976. };
  16977. Engine.prototype.setProgram = function (program) {
  16978. if (this._currentProgram !== program) {
  16979. this._gl.useProgram(program);
  16980. this._currentProgram = program;
  16981. }
  16982. };
  16983. /**
  16984. * Binds an effect to the webGL context
  16985. * @param effect defines the effect to bind
  16986. */
  16987. Engine.prototype.bindSamplers = function (effect) {
  16988. this.setProgram(effect.getProgram());
  16989. var samplers = effect.getSamplers();
  16990. for (var index = 0; index < samplers.length; index++) {
  16991. var uniform = effect.getUniform(samplers[index]);
  16992. if (uniform) {
  16993. this._boundUniforms[index] = uniform;
  16994. }
  16995. }
  16996. this._currentEffect = null;
  16997. };
  16998. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16999. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17000. return;
  17001. }
  17002. // Remove
  17003. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17004. // Bind last to it
  17005. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17006. // Bind to dummy
  17007. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17008. };
  17009. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17010. if (!internalTexture) {
  17011. return -1;
  17012. }
  17013. internalTexture._initialSlot = channel;
  17014. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17015. if (channel !== internalTexture._designatedSlot) {
  17016. this._textureCollisions.addCount(1, false);
  17017. }
  17018. }
  17019. else {
  17020. if (channel !== internalTexture._designatedSlot) {
  17021. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17022. return internalTexture._designatedSlot;
  17023. }
  17024. else {
  17025. // No slot for this texture, let's pick a new one (if we find a free slot)
  17026. if (this._nextFreeTextureSlots.length) {
  17027. return this._nextFreeTextureSlots[0];
  17028. }
  17029. // We need to recycle the oldest bound texture, sorry.
  17030. this._textureCollisions.addCount(1, false);
  17031. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17032. }
  17033. }
  17034. }
  17035. return channel;
  17036. };
  17037. Engine.prototype._linkTrackers = function (previous, next) {
  17038. previous.next = next;
  17039. next.previous = previous;
  17040. };
  17041. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17042. var currentSlot = internalTexture._designatedSlot;
  17043. if (currentSlot === -1) {
  17044. return -1;
  17045. }
  17046. internalTexture._designatedSlot = -1;
  17047. if (this.disableTextureBindingOptimization) {
  17048. return -1;
  17049. }
  17050. // Remove from bound list
  17051. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17052. // Free the slot
  17053. this._boundTexturesCache[currentSlot] = null;
  17054. this._nextFreeTextureSlots.push(currentSlot);
  17055. return currentSlot;
  17056. };
  17057. Engine.prototype._activateCurrentTexture = function () {
  17058. if (this._currentTextureChannel !== this._activeChannel) {
  17059. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17060. this._currentTextureChannel = this._activeChannel;
  17061. }
  17062. };
  17063. /** @hidden */
  17064. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17065. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17066. if (force === void 0) { force = false; }
  17067. var wasPreviouslyBound = false;
  17068. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17069. this._activeChannel = texture._designatedSlot;
  17070. }
  17071. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17072. var isTextureForRendering = texture && texture._initialSlot > -1;
  17073. if (currentTextureBound !== texture || force) {
  17074. if (currentTextureBound) {
  17075. this._removeDesignatedSlot(currentTextureBound);
  17076. }
  17077. this._activateCurrentTexture();
  17078. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17079. this._boundTexturesCache[this._activeChannel] = texture;
  17080. if (texture) {
  17081. if (!this.disableTextureBindingOptimization) {
  17082. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17083. if (slotIndex > -1) {
  17084. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17085. }
  17086. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17087. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17088. }
  17089. texture._designatedSlot = this._activeChannel;
  17090. }
  17091. }
  17092. else if (forTextureDataUpdate) {
  17093. wasPreviouslyBound = true;
  17094. this._activateCurrentTexture();
  17095. }
  17096. if (isTextureForRendering && !forTextureDataUpdate) {
  17097. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17098. }
  17099. return wasPreviouslyBound;
  17100. };
  17101. /** @hidden */
  17102. Engine.prototype._bindTexture = function (channel, texture) {
  17103. if (channel < 0) {
  17104. return;
  17105. }
  17106. if (texture) {
  17107. channel = this._getCorrectTextureChannel(channel, texture);
  17108. }
  17109. this._activeChannel = channel;
  17110. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17111. };
  17112. /**
  17113. * Sets a texture to the webGL context from a postprocess
  17114. * @param channel defines the channel to use
  17115. * @param postProcess defines the source postprocess
  17116. */
  17117. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17118. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17119. };
  17120. /**
  17121. * Binds the output of the passed in post process to the texture channel specified
  17122. * @param channel The channel the texture should be bound to
  17123. * @param postProcess The post process which's output should be bound
  17124. */
  17125. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17126. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17127. };
  17128. /**
  17129. * Unbind all textures from the webGL context
  17130. */
  17131. Engine.prototype.unbindAllTextures = function () {
  17132. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17133. this._activeChannel = channel;
  17134. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17135. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17136. if (this.webGLVersion > 1) {
  17137. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17138. }
  17139. }
  17140. };
  17141. /**
  17142. * Sets a texture to the according uniform.
  17143. * @param channel The texture channel
  17144. * @param uniform The uniform to set
  17145. * @param texture The texture to apply
  17146. */
  17147. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17148. if (channel < 0) {
  17149. return;
  17150. }
  17151. if (uniform) {
  17152. this._boundUniforms[channel] = uniform;
  17153. }
  17154. this._setTexture(channel, texture);
  17155. };
  17156. /**
  17157. * Sets a depth stencil texture from a render target to the according uniform.
  17158. * @param channel The texture channel
  17159. * @param uniform The uniform to set
  17160. * @param texture The render target texture containing the depth stencil texture to apply
  17161. */
  17162. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17163. if (channel < 0) {
  17164. return;
  17165. }
  17166. if (uniform) {
  17167. this._boundUniforms[channel] = uniform;
  17168. }
  17169. if (!texture || !texture.depthStencilTexture) {
  17170. this._setTexture(channel, null);
  17171. }
  17172. else {
  17173. this._setTexture(channel, texture, false, true);
  17174. }
  17175. };
  17176. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17177. var uniform = this._boundUniforms[sourceSlot];
  17178. if (uniform._currentState === destination) {
  17179. return;
  17180. }
  17181. this._gl.uniform1i(uniform, destination);
  17182. uniform._currentState = destination;
  17183. };
  17184. Engine.prototype._getTextureWrapMode = function (mode) {
  17185. switch (mode) {
  17186. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17187. return this._gl.REPEAT;
  17188. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17189. return this._gl.CLAMP_TO_EDGE;
  17190. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17191. return this._gl.MIRRORED_REPEAT;
  17192. }
  17193. return this._gl.REPEAT;
  17194. };
  17195. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17196. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17197. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17198. // Not ready?
  17199. if (!texture) {
  17200. if (this._boundTexturesCache[channel] != null) {
  17201. this._activeChannel = channel;
  17202. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17203. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17204. if (this.webGLVersion > 1) {
  17205. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17206. }
  17207. }
  17208. return false;
  17209. }
  17210. // Video
  17211. if (texture.video) {
  17212. this._activeChannel = channel;
  17213. texture.update();
  17214. }
  17215. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17216. texture.delayLoad();
  17217. return false;
  17218. }
  17219. var internalTexture;
  17220. if (depthStencilTexture) {
  17221. internalTexture = texture.depthStencilTexture;
  17222. }
  17223. else if (texture.isReady()) {
  17224. internalTexture = texture.getInternalTexture();
  17225. }
  17226. else if (texture.isCube) {
  17227. internalTexture = this.emptyCubeTexture;
  17228. }
  17229. else if (texture.is3D) {
  17230. internalTexture = this.emptyTexture3D;
  17231. }
  17232. else {
  17233. internalTexture = this.emptyTexture;
  17234. }
  17235. if (!isPartOfTextureArray) {
  17236. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17237. }
  17238. var needToBind = true;
  17239. if (this._boundTexturesCache[channel] === internalTexture) {
  17240. this._moveBoundTextureOnTop(internalTexture);
  17241. if (!isPartOfTextureArray) {
  17242. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17243. }
  17244. needToBind = false;
  17245. }
  17246. this._activeChannel = channel;
  17247. if (internalTexture && internalTexture.is3D) {
  17248. if (needToBind) {
  17249. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17250. }
  17251. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17252. internalTexture._cachedWrapU = texture.wrapU;
  17253. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17254. }
  17255. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17256. internalTexture._cachedWrapV = texture.wrapV;
  17257. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17258. }
  17259. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17260. internalTexture._cachedWrapR = texture.wrapR;
  17261. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17262. }
  17263. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17264. }
  17265. else if (internalTexture && internalTexture.isCube) {
  17266. if (needToBind) {
  17267. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17268. }
  17269. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17270. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17271. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17272. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17273. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17274. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17275. }
  17276. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17277. }
  17278. else {
  17279. if (needToBind) {
  17280. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17281. }
  17282. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17283. internalTexture._cachedWrapU = texture.wrapU;
  17284. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17285. }
  17286. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17287. internalTexture._cachedWrapV = texture.wrapV;
  17288. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17289. }
  17290. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17291. }
  17292. return true;
  17293. };
  17294. /**
  17295. * Sets an array of texture to the webGL context
  17296. * @param channel defines the channel where the texture array must be set
  17297. * @param uniform defines the associated uniform location
  17298. * @param textures defines the array of textures to bind
  17299. */
  17300. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17301. if (channel < 0 || !uniform) {
  17302. return;
  17303. }
  17304. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17305. this._textureUnits = new Int32Array(textures.length);
  17306. }
  17307. for (var i = 0; i < textures.length; i++) {
  17308. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17309. }
  17310. this._gl.uniform1iv(uniform, this._textureUnits);
  17311. for (var index = 0; index < textures.length; index++) {
  17312. this._setTexture(this._textureUnits[index], textures[index], true);
  17313. }
  17314. };
  17315. /** @hidden */
  17316. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17317. var internalTexture = texture.getInternalTexture();
  17318. if (!internalTexture) {
  17319. return;
  17320. }
  17321. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17322. var value = texture.anisotropicFilteringLevel;
  17323. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17324. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17325. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17326. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17327. }
  17328. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17329. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17330. internalTexture._cachedAnisotropicFilteringLevel = value;
  17331. }
  17332. };
  17333. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17334. this._bindTextureDirectly(target, texture, true, true);
  17335. this._gl.texParameterf(target, parameter, value);
  17336. };
  17337. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17338. if (texture) {
  17339. this._bindTextureDirectly(target, texture, true, true);
  17340. }
  17341. this._gl.texParameteri(target, parameter, value);
  17342. };
  17343. /**
  17344. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17345. * @param x defines the x coordinate of the rectangle where pixels must be read
  17346. * @param y defines the y coordinate of the rectangle where pixels must be read
  17347. * @param width defines the width of the rectangle where pixels must be read
  17348. * @param height defines the height of the rectangle where pixels must be read
  17349. * @returns a Uint8Array containing RGBA colors
  17350. */
  17351. Engine.prototype.readPixels = function (x, y, width, height) {
  17352. var data = new Uint8Array(height * width * 4);
  17353. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17354. return data;
  17355. };
  17356. /**
  17357. * Add an externaly attached data from its key.
  17358. * This method call will fail and return false, if such key already exists.
  17359. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17360. * @param key the unique key that identifies the data
  17361. * @param data the data object to associate to the key for this Engine instance
  17362. * @return true if no such key were already present and the data was added successfully, false otherwise
  17363. */
  17364. Engine.prototype.addExternalData = function (key, data) {
  17365. if (!this._externalData) {
  17366. this._externalData = new BABYLON.StringDictionary();
  17367. }
  17368. return this._externalData.add(key, data);
  17369. };
  17370. /**
  17371. * Get an externaly attached data from its key
  17372. * @param key the unique key that identifies the data
  17373. * @return the associated data, if present (can be null), or undefined if not present
  17374. */
  17375. Engine.prototype.getExternalData = function (key) {
  17376. if (!this._externalData) {
  17377. this._externalData = new BABYLON.StringDictionary();
  17378. }
  17379. return this._externalData.get(key);
  17380. };
  17381. /**
  17382. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17383. * @param key the unique key that identifies the data
  17384. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17385. * @return the associated data, can be null if the factory returned null.
  17386. */
  17387. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17388. if (!this._externalData) {
  17389. this._externalData = new BABYLON.StringDictionary();
  17390. }
  17391. return this._externalData.getOrAddWithFactory(key, factory);
  17392. };
  17393. /**
  17394. * Remove an externaly attached data from the Engine instance
  17395. * @param key the unique key that identifies the data
  17396. * @return true if the data was successfully removed, false if it doesn't exist
  17397. */
  17398. Engine.prototype.removeExternalData = function (key) {
  17399. if (!this._externalData) {
  17400. this._externalData = new BABYLON.StringDictionary();
  17401. }
  17402. return this._externalData.remove(key);
  17403. };
  17404. /**
  17405. * Unbind all vertex attributes from the webGL context
  17406. */
  17407. Engine.prototype.unbindAllAttributes = function () {
  17408. if (this._mustWipeVertexAttributes) {
  17409. this._mustWipeVertexAttributes = false;
  17410. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17411. this._gl.disableVertexAttribArray(i);
  17412. this._vertexAttribArraysEnabled[i] = false;
  17413. this._currentBufferPointers[i].active = false;
  17414. }
  17415. return;
  17416. }
  17417. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17418. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17419. continue;
  17420. }
  17421. this._gl.disableVertexAttribArray(i);
  17422. this._vertexAttribArraysEnabled[i] = false;
  17423. this._currentBufferPointers[i].active = false;
  17424. }
  17425. };
  17426. /**
  17427. * 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
  17428. */
  17429. Engine.prototype.releaseEffects = function () {
  17430. for (var name in this._compiledEffects) {
  17431. this._deleteProgram(this._compiledEffects[name]._program);
  17432. }
  17433. this._compiledEffects = {};
  17434. };
  17435. /**
  17436. * Dispose and release all associated resources
  17437. */
  17438. Engine.prototype.dispose = function () {
  17439. this.hideLoadingUI();
  17440. this.stopRenderLoop();
  17441. // Release postProcesses
  17442. while (this.postProcesses.length) {
  17443. this.postProcesses[0].dispose();
  17444. }
  17445. // Empty texture
  17446. if (this._emptyTexture) {
  17447. this._releaseTexture(this._emptyTexture);
  17448. this._emptyTexture = null;
  17449. }
  17450. if (this._emptyCubeTexture) {
  17451. this._releaseTexture(this._emptyCubeTexture);
  17452. this._emptyCubeTexture = null;
  17453. }
  17454. // Rescale PP
  17455. if (this._rescalePostProcess) {
  17456. this._rescalePostProcess.dispose();
  17457. }
  17458. // Release scenes
  17459. while (this.scenes.length) {
  17460. this.scenes[0].dispose();
  17461. }
  17462. // Release audio engine
  17463. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17464. Engine.audioEngine.dispose();
  17465. }
  17466. // Release effects
  17467. this.releaseEffects();
  17468. // Unbind
  17469. this.unbindAllAttributes();
  17470. this._boundUniforms = [];
  17471. if (this._dummyFramebuffer) {
  17472. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17473. }
  17474. //WebVR
  17475. this.disableVR();
  17476. // Events
  17477. if (BABYLON.Tools.IsWindowObjectExist()) {
  17478. window.removeEventListener("blur", this._onBlur);
  17479. window.removeEventListener("focus", this._onFocus);
  17480. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17481. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17482. if (this._renderingCanvas) {
  17483. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17484. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17485. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17486. if (!this._doNotHandleContextLost) {
  17487. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17488. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17489. }
  17490. }
  17491. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17492. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17493. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17494. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17495. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17496. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17497. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17498. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17499. if (this._onVrDisplayConnect) {
  17500. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17501. if (this._onVrDisplayDisconnect) {
  17502. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17503. }
  17504. if (this._onVrDisplayPresentChange) {
  17505. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17506. }
  17507. this._onVrDisplayConnect = null;
  17508. this._onVrDisplayDisconnect = null;
  17509. }
  17510. }
  17511. // Remove from Instances
  17512. var index = Engine.Instances.indexOf(this);
  17513. if (index >= 0) {
  17514. Engine.Instances.splice(index, 1);
  17515. }
  17516. this._workingCanvas = null;
  17517. this._workingContext = null;
  17518. this._currentBufferPointers = [];
  17519. this._renderingCanvas = null;
  17520. this._currentProgram = null;
  17521. this._bindedRenderFunction = null;
  17522. this.onResizeObservable.clear();
  17523. this.onCanvasBlurObservable.clear();
  17524. this.onCanvasFocusObservable.clear();
  17525. this.onCanvasPointerOutObservable.clear();
  17526. this.onBeginFrameObservable.clear();
  17527. this.onEndFrameObservable.clear();
  17528. BABYLON.Effect.ResetCache();
  17529. // Abort active requests
  17530. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17531. var request = _a[_i];
  17532. request.abort();
  17533. }
  17534. };
  17535. // Loading screen
  17536. /**
  17537. * Display the loading screen
  17538. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17539. */
  17540. Engine.prototype.displayLoadingUI = function () {
  17541. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17542. return;
  17543. }
  17544. var loadingScreen = this.loadingScreen;
  17545. if (loadingScreen) {
  17546. loadingScreen.displayLoadingUI();
  17547. }
  17548. };
  17549. /**
  17550. * Hide the loading screen
  17551. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17552. */
  17553. Engine.prototype.hideLoadingUI = function () {
  17554. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17555. return;
  17556. }
  17557. var loadingScreen = this.loadingScreen;
  17558. if (loadingScreen) {
  17559. loadingScreen.hideLoadingUI();
  17560. }
  17561. };
  17562. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17563. /**
  17564. * Gets the current loading screen object
  17565. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17566. */
  17567. get: function () {
  17568. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17569. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17570. return this._loadingScreen;
  17571. },
  17572. /**
  17573. * Sets the current loading screen object
  17574. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17575. */
  17576. set: function (loadingScreen) {
  17577. this._loadingScreen = loadingScreen;
  17578. },
  17579. enumerable: true,
  17580. configurable: true
  17581. });
  17582. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17583. /**
  17584. * Sets the current loading screen text
  17585. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17586. */
  17587. set: function (text) {
  17588. this.loadingScreen.loadingUIText = text;
  17589. },
  17590. enumerable: true,
  17591. configurable: true
  17592. });
  17593. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17594. /**
  17595. * Sets the current loading screen background color
  17596. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17597. */
  17598. set: function (color) {
  17599. this.loadingScreen.loadingUIBackgroundColor = color;
  17600. },
  17601. enumerable: true,
  17602. configurable: true
  17603. });
  17604. /**
  17605. * Attach a new callback raised when context lost event is fired
  17606. * @param callback defines the callback to call
  17607. */
  17608. Engine.prototype.attachContextLostEvent = function (callback) {
  17609. if (this._renderingCanvas) {
  17610. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17611. }
  17612. };
  17613. /**
  17614. * Attach a new callback raised when context restored event is fired
  17615. * @param callback defines the callback to call
  17616. */
  17617. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17618. if (this._renderingCanvas) {
  17619. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17620. }
  17621. };
  17622. /**
  17623. * Gets the source code of the vertex shader associated with a specific webGL program
  17624. * @param program defines the program to use
  17625. * @returns a string containing the source code of the vertex shader associated with the program
  17626. */
  17627. Engine.prototype.getVertexShaderSource = function (program) {
  17628. var shaders = this._gl.getAttachedShaders(program);
  17629. if (!shaders) {
  17630. return null;
  17631. }
  17632. return this._gl.getShaderSource(shaders[0]);
  17633. };
  17634. /**
  17635. * Gets the source code of the fragment shader associated with a specific webGL program
  17636. * @param program defines the program to use
  17637. * @returns a string containing the source code of the fragment shader associated with the program
  17638. */
  17639. Engine.prototype.getFragmentShaderSource = function (program) {
  17640. var shaders = this._gl.getAttachedShaders(program);
  17641. if (!shaders) {
  17642. return null;
  17643. }
  17644. return this._gl.getShaderSource(shaders[1]);
  17645. };
  17646. /**
  17647. * Get the current error code of the webGL context
  17648. * @returns the error code
  17649. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17650. */
  17651. Engine.prototype.getError = function () {
  17652. return this._gl.getError();
  17653. };
  17654. // FPS
  17655. /**
  17656. * Gets the current framerate
  17657. * @returns a number representing the framerate
  17658. */
  17659. Engine.prototype.getFps = function () {
  17660. return this._fps;
  17661. };
  17662. /**
  17663. * Gets the time spent between current and previous frame
  17664. * @returns a number representing the delta time in ms
  17665. */
  17666. Engine.prototype.getDeltaTime = function () {
  17667. return this._deltaTime;
  17668. };
  17669. Engine.prototype._measureFps = function () {
  17670. this._performanceMonitor.sampleFrame();
  17671. this._fps = this._performanceMonitor.averageFPS;
  17672. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17673. };
  17674. /** @hidden */
  17675. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17676. if (faceIndex === void 0) { faceIndex = -1; }
  17677. if (level === void 0) { level = 0; }
  17678. if (buffer === void 0) { buffer = null; }
  17679. var gl = this._gl;
  17680. if (!this._dummyFramebuffer) {
  17681. var dummy = gl.createFramebuffer();
  17682. if (!dummy) {
  17683. throw new Error("Unable to create dummy framebuffer");
  17684. }
  17685. this._dummyFramebuffer = dummy;
  17686. }
  17687. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17688. if (faceIndex > -1) {
  17689. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17690. }
  17691. else {
  17692. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17693. }
  17694. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17695. switch (readType) {
  17696. case gl.UNSIGNED_BYTE:
  17697. if (!buffer) {
  17698. buffer = new Uint8Array(4 * width * height);
  17699. }
  17700. readType = gl.UNSIGNED_BYTE;
  17701. break;
  17702. default:
  17703. if (!buffer) {
  17704. buffer = new Float32Array(4 * width * height);
  17705. }
  17706. readType = gl.FLOAT;
  17707. break;
  17708. }
  17709. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17710. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17711. return buffer;
  17712. };
  17713. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17714. if (this._webGLVersion > 1) {
  17715. return this._caps.colorBufferFloat;
  17716. }
  17717. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17718. };
  17719. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17720. if (this._webGLVersion > 1) {
  17721. return this._caps.colorBufferFloat;
  17722. }
  17723. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17724. };
  17725. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17726. Engine.prototype._canRenderToFramebuffer = function (type) {
  17727. var gl = this._gl;
  17728. //clear existing errors
  17729. while (gl.getError() !== gl.NO_ERROR) { }
  17730. var successful = true;
  17731. var texture = gl.createTexture();
  17732. gl.bindTexture(gl.TEXTURE_2D, texture);
  17733. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17736. var fb = gl.createFramebuffer();
  17737. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17738. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17739. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17740. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17741. successful = successful && (gl.getError() === gl.NO_ERROR);
  17742. //try render by clearing frame buffer's color buffer
  17743. if (successful) {
  17744. gl.clear(gl.COLOR_BUFFER_BIT);
  17745. successful = successful && (gl.getError() === gl.NO_ERROR);
  17746. }
  17747. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17748. if (successful) {
  17749. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17750. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17751. var readFormat = gl.RGBA;
  17752. var readType = gl.UNSIGNED_BYTE;
  17753. var buffer = new Uint8Array(4);
  17754. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17755. successful = successful && (gl.getError() === gl.NO_ERROR);
  17756. }
  17757. //clean up
  17758. gl.deleteTexture(texture);
  17759. gl.deleteFramebuffer(fb);
  17760. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17761. //clear accumulated errors
  17762. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17763. return successful;
  17764. };
  17765. /** @hidden */
  17766. Engine.prototype._getWebGLTextureType = function (type) {
  17767. if (this._webGLVersion === 1) {
  17768. switch (type) {
  17769. case Engine.TEXTURETYPE_FLOAT:
  17770. return this._gl.FLOAT;
  17771. case Engine.TEXTURETYPE_HALF_FLOAT:
  17772. return this._gl.HALF_FLOAT_OES;
  17773. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17774. return this._gl.UNSIGNED_BYTE;
  17775. }
  17776. return this._gl.UNSIGNED_BYTE;
  17777. }
  17778. switch (type) {
  17779. case Engine.TEXTURETYPE_BYTE:
  17780. return this._gl.BYTE;
  17781. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17782. return this._gl.UNSIGNED_BYTE;
  17783. case Engine.TEXTURETYPE_SHORT:
  17784. return this._gl.SHORT;
  17785. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17786. return this._gl.UNSIGNED_SHORT;
  17787. case Engine.TEXTURETYPE_INT:
  17788. return this._gl.INT;
  17789. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17790. return this._gl.UNSIGNED_INT;
  17791. case Engine.TEXTURETYPE_FLOAT:
  17792. return this._gl.FLOAT;
  17793. case Engine.TEXTURETYPE_HALF_FLOAT:
  17794. return this._gl.HALF_FLOAT;
  17795. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17796. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17797. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17798. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17799. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17800. return this._gl.UNSIGNED_SHORT_5_6_5;
  17801. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17802. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17803. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17804. return this._gl.UNSIGNED_INT_24_8;
  17805. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17806. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17807. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17808. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17809. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17810. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17811. }
  17812. return this._gl.UNSIGNED_BYTE;
  17813. };
  17814. ;
  17815. Engine.prototype._getInternalFormat = function (format) {
  17816. var internalFormat = this._gl.RGBA;
  17817. switch (format) {
  17818. case Engine.TEXTUREFORMAT_ALPHA:
  17819. internalFormat = this._gl.ALPHA;
  17820. break;
  17821. case Engine.TEXTUREFORMAT_LUMINANCE:
  17822. internalFormat = this._gl.LUMINANCE;
  17823. break;
  17824. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17825. internalFormat = this._gl.LUMINANCE_ALPHA;
  17826. break;
  17827. case Engine.TEXTUREFORMAT_RED:
  17828. internalFormat = this._gl.RED;
  17829. break;
  17830. case Engine.TEXTUREFORMAT_RG:
  17831. internalFormat = this._gl.RG;
  17832. break;
  17833. case Engine.TEXTUREFORMAT_RGB:
  17834. internalFormat = this._gl.RGB;
  17835. break;
  17836. case Engine.TEXTUREFORMAT_RGBA:
  17837. internalFormat = this._gl.RGBA;
  17838. break;
  17839. }
  17840. if (this._webGLVersion > 1) {
  17841. switch (format) {
  17842. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17843. internalFormat = this._gl.RED_INTEGER;
  17844. break;
  17845. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17846. internalFormat = this._gl.RG_INTEGER;
  17847. break;
  17848. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17849. internalFormat = this._gl.RGB_INTEGER;
  17850. break;
  17851. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17852. internalFormat = this._gl.RGBA_INTEGER;
  17853. break;
  17854. }
  17855. }
  17856. return internalFormat;
  17857. };
  17858. /** @hidden */
  17859. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17860. if (this._webGLVersion === 1) {
  17861. if (format !== undefined) {
  17862. switch (format) {
  17863. case Engine.TEXTUREFORMAT_ALPHA:
  17864. return this._gl.ALPHA;
  17865. case Engine.TEXTUREFORMAT_LUMINANCE:
  17866. return this._gl.LUMINANCE;
  17867. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17868. return this._gl.LUMINANCE_ALPHA;
  17869. }
  17870. }
  17871. return this._gl.RGBA;
  17872. }
  17873. switch (type) {
  17874. case Engine.TEXTURETYPE_BYTE:
  17875. switch (format) {
  17876. case Engine.TEXTUREFORMAT_RED:
  17877. return this._gl.R8_SNORM;
  17878. case Engine.TEXTUREFORMAT_RG:
  17879. return this._gl.RG8_SNORM;
  17880. case Engine.TEXTUREFORMAT_RGB:
  17881. return this._gl.RGB8_SNORM;
  17882. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17883. return this._gl.R8I;
  17884. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17885. return this._gl.RG8I;
  17886. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17887. return this._gl.RGB8I;
  17888. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17889. return this._gl.RGBA8I;
  17890. default:
  17891. return this._gl.RGBA8_SNORM;
  17892. }
  17893. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17894. switch (format) {
  17895. case Engine.TEXTUREFORMAT_RED:
  17896. return this._gl.R8;
  17897. case Engine.TEXTUREFORMAT_RG:
  17898. return this._gl.RG8;
  17899. case Engine.TEXTUREFORMAT_RGB:
  17900. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17901. case Engine.TEXTUREFORMAT_RGBA:
  17902. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17903. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17904. return this._gl.R8UI;
  17905. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17906. return this._gl.RG8UI;
  17907. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17908. return this._gl.RGB8UI;
  17909. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17910. return this._gl.RGBA8UI;
  17911. default:
  17912. return this._gl.RGBA8;
  17913. }
  17914. case Engine.TEXTURETYPE_SHORT:
  17915. switch (format) {
  17916. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17917. return this._gl.R16I;
  17918. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17919. return this._gl.RG16I;
  17920. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17921. return this._gl.RGB16I;
  17922. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17923. return this._gl.RGBA16I;
  17924. default:
  17925. return this._gl.RGBA16I;
  17926. }
  17927. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17928. switch (format) {
  17929. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17930. return this._gl.R16UI;
  17931. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17932. return this._gl.RG16UI;
  17933. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17934. return this._gl.RGB16UI;
  17935. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17936. return this._gl.RGBA16UI;
  17937. default:
  17938. return this._gl.RGBA16UI;
  17939. }
  17940. case Engine.TEXTURETYPE_INT:
  17941. switch (format) {
  17942. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17943. return this._gl.R32I;
  17944. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17945. return this._gl.RG32I;
  17946. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17947. return this._gl.RGB32I;
  17948. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17949. return this._gl.RGBA32I;
  17950. default:
  17951. return this._gl.RGBA32I;
  17952. }
  17953. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17954. switch (format) {
  17955. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17956. return this._gl.R32UI;
  17957. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17958. return this._gl.RG32UI;
  17959. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17960. return this._gl.RGB32UI;
  17961. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17962. return this._gl.RGBA32UI;
  17963. default:
  17964. return this._gl.RGBA32UI;
  17965. }
  17966. case Engine.TEXTURETYPE_FLOAT:
  17967. switch (format) {
  17968. case Engine.TEXTUREFORMAT_RED:
  17969. return this._gl.R32F; // By default. Other possibility is R16F.
  17970. case Engine.TEXTUREFORMAT_RG:
  17971. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17972. case Engine.TEXTUREFORMAT_RGB:
  17973. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  17974. case Engine.TEXTUREFORMAT_RGBA:
  17975. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  17976. default:
  17977. return this._gl.RGBA32F;
  17978. }
  17979. case Engine.TEXTURETYPE_HALF_FLOAT:
  17980. switch (format) {
  17981. case Engine.TEXTUREFORMAT_RED:
  17982. return this._gl.R16F;
  17983. case Engine.TEXTUREFORMAT_RG:
  17984. return this._gl.RG16F;
  17985. case Engine.TEXTUREFORMAT_RGB:
  17986. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  17987. case Engine.TEXTUREFORMAT_RGBA:
  17988. return this._gl.RGBA16F;
  17989. default:
  17990. return this._gl.RGBA16F;
  17991. }
  17992. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17993. return this._gl.RGB565;
  17994. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17995. return this._gl.R11F_G11F_B10F;
  17996. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17997. return this._gl.RGB9_E5;
  17998. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17999. return this._gl.RGBA4;
  18000. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18001. return this._gl.RGB5_A1;
  18002. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18003. switch (format) {
  18004. case Engine.TEXTUREFORMAT_RGBA:
  18005. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18006. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18007. return this._gl.RGB10_A2UI;
  18008. default:
  18009. return this._gl.RGB10_A2;
  18010. }
  18011. }
  18012. return this._gl.RGBA8;
  18013. };
  18014. ;
  18015. /** @hidden */
  18016. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18017. if (type === Engine.TEXTURETYPE_FLOAT) {
  18018. return this._gl.RGBA32F;
  18019. }
  18020. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18021. return this._gl.RGBA16F;
  18022. }
  18023. return this._gl.RGBA8;
  18024. };
  18025. ;
  18026. /** @hidden */
  18027. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18028. var _this = this;
  18029. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18030. this._activeRequests.push(request);
  18031. request.onCompleteObservable.add(function (request) {
  18032. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18033. });
  18034. return request;
  18035. };
  18036. /** @hidden */
  18037. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18038. var _this = this;
  18039. return new Promise(function (resolve, reject) {
  18040. _this._loadFile(url, function (data) {
  18041. resolve(data);
  18042. }, undefined, database, useArrayBuffer, function (request, exception) {
  18043. reject(exception);
  18044. });
  18045. });
  18046. };
  18047. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18048. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18049. var onload = function (data) {
  18050. loadedFiles[index] = data;
  18051. loadedFiles._internalCount++;
  18052. if (loadedFiles._internalCount === 6) {
  18053. onfinish(loadedFiles);
  18054. }
  18055. };
  18056. var onerror = function (request, exception) {
  18057. if (onErrorCallBack && request) {
  18058. onErrorCallBack(request.status + " " + request.statusText, exception);
  18059. }
  18060. };
  18061. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18062. };
  18063. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18064. if (onError === void 0) { onError = null; }
  18065. var loadedFiles = [];
  18066. loadedFiles._internalCount = 0;
  18067. for (var index = 0; index < 6; index++) {
  18068. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18069. }
  18070. };
  18071. // Statics
  18072. /**
  18073. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18074. * @returns true if the engine can be created
  18075. * @ignorenaming
  18076. */
  18077. Engine.isSupported = function () {
  18078. try {
  18079. var tempcanvas = document.createElement("canvas");
  18080. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18081. return gl != null && !!window.WebGLRenderingContext;
  18082. }
  18083. catch (e) {
  18084. return false;
  18085. }
  18086. };
  18087. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18088. Engine.ExceptionList = [
  18089. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18090. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18091. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18092. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18093. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18094. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18095. ];
  18096. /** Gets the list of created engines */
  18097. Engine.Instances = new Array();
  18098. /**
  18099. * Hidden
  18100. */
  18101. Engine._TextureLoaders = [];
  18102. // Const statics
  18103. /** Defines that alpha blending is disabled */
  18104. Engine.ALPHA_DISABLE = 0;
  18105. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18106. Engine.ALPHA_ADD = 1;
  18107. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18108. Engine.ALPHA_COMBINE = 2;
  18109. /** Defines that alpha blending to DEST - SRC * DEST */
  18110. Engine.ALPHA_SUBTRACT = 3;
  18111. /** Defines that alpha blending to SRC * DEST */
  18112. Engine.ALPHA_MULTIPLY = 4;
  18113. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18114. Engine.ALPHA_MAXIMIZED = 5;
  18115. /** Defines that alpha blending to SRC + DEST */
  18116. Engine.ALPHA_ONEONE = 6;
  18117. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18118. Engine.ALPHA_PREMULTIPLIED = 7;
  18119. /**
  18120. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18121. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18122. */
  18123. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18124. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18125. Engine.ALPHA_INTERPOLATE = 9;
  18126. /**
  18127. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18128. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18129. */
  18130. Engine.ALPHA_SCREENMODE = 10;
  18131. /** Defines that the ressource is not delayed*/
  18132. Engine.DELAYLOADSTATE_NONE = 0;
  18133. /** Defines that the ressource was successfully delay loaded */
  18134. Engine.DELAYLOADSTATE_LOADED = 1;
  18135. /** Defines that the ressource is currently delay loading */
  18136. Engine.DELAYLOADSTATE_LOADING = 2;
  18137. /** Defines that the ressource is delayed and has not started loading */
  18138. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18139. // Depht or Stencil test Constants.
  18140. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18141. Engine.NEVER = 0x0200;
  18142. /** 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 */
  18143. Engine.ALWAYS = 0x0207;
  18144. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18145. Engine.LESS = 0x0201;
  18146. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18147. Engine.EQUAL = 0x0202;
  18148. /** 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 */
  18149. Engine.LEQUAL = 0x0203;
  18150. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18151. Engine.GREATER = 0x0204;
  18152. /** 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 */
  18153. Engine.GEQUAL = 0x0206;
  18154. /** 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 */
  18155. Engine.NOTEQUAL = 0x0205;
  18156. // Stencil Actions Constants.
  18157. /** Passed to stencilOperation to specify that stencil value must be kept */
  18158. Engine.KEEP = 0x1E00;
  18159. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18160. Engine.REPLACE = 0x1E01;
  18161. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18162. Engine.INCR = 0x1E02;
  18163. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18164. Engine.DECR = 0x1E03;
  18165. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18166. Engine.INVERT = 0x150A;
  18167. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18168. Engine.INCR_WRAP = 0x8507;
  18169. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18170. Engine.DECR_WRAP = 0x8508;
  18171. /** Texture is not repeating outside of 0..1 UVs */
  18172. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18173. /** Texture is repeating outside of 0..1 UVs */
  18174. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18175. /** Texture is repeating and mirrored */
  18176. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18177. /** ALPHA */
  18178. Engine.TEXTUREFORMAT_ALPHA = 0;
  18179. /** LUMINANCE */
  18180. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18181. /** LUMINANCE_ALPHA */
  18182. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18183. /** RGB */
  18184. Engine.TEXTUREFORMAT_RGB = 4;
  18185. /** RGBA */
  18186. Engine.TEXTUREFORMAT_RGBA = 5;
  18187. /** RED */
  18188. Engine.TEXTUREFORMAT_RED = 6;
  18189. /** RED (2nd reference) */
  18190. Engine.TEXTUREFORMAT_R = 6;
  18191. /** RG */
  18192. Engine.TEXTUREFORMAT_RG = 7;
  18193. /** RED_INTEGER */
  18194. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18195. /** RED_INTEGER (2nd reference) */
  18196. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18197. /** RG_INTEGER */
  18198. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18199. /** RGB_INTEGER */
  18200. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18201. /** RGBA_INTEGER */
  18202. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18203. /** UNSIGNED_BYTE */
  18204. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18205. /** UNSIGNED_BYTE (2nd reference) */
  18206. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18207. /** FLOAT */
  18208. Engine.TEXTURETYPE_FLOAT = 1;
  18209. /** HALF_FLOAT */
  18210. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18211. /** BYTE */
  18212. Engine.TEXTURETYPE_BYTE = 3;
  18213. /** SHORT */
  18214. Engine.TEXTURETYPE_SHORT = 4;
  18215. /** UNSIGNED_SHORT */
  18216. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18217. /** INT */
  18218. Engine.TEXTURETYPE_INT = 6;
  18219. /** UNSIGNED_INT */
  18220. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18221. /** UNSIGNED_SHORT_4_4_4_4 */
  18222. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18223. /** UNSIGNED_SHORT_5_5_5_1 */
  18224. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18225. /** UNSIGNED_SHORT_5_6_5 */
  18226. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18227. /** UNSIGNED_INT_2_10_10_10_REV */
  18228. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18229. /** UNSIGNED_INT_24_8 */
  18230. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18231. /** UNSIGNED_INT_10F_11F_11F_REV */
  18232. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18233. /** UNSIGNED_INT_5_9_9_9_REV */
  18234. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18235. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18236. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18237. /** nearest is mag = nearest and min = nearest and mip = linear */
  18238. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18239. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18240. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18241. /** Trilinear is mag = linear and min = linear and mip = linear */
  18242. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18243. /** nearest is mag = nearest and min = nearest and mip = linear */
  18244. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18245. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18246. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18247. /** Trilinear is mag = linear and min = linear and mip = linear */
  18248. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18249. /** mag = nearest and min = nearest and mip = nearest */
  18250. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18251. /** mag = nearest and min = linear and mip = nearest */
  18252. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18253. /** mag = nearest and min = linear and mip = linear */
  18254. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18255. /** mag = nearest and min = linear and mip = none */
  18256. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18257. /** mag = nearest and min = nearest and mip = none */
  18258. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18259. /** mag = linear and min = nearest and mip = nearest */
  18260. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18261. /** mag = linear and min = nearest and mip = linear */
  18262. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18263. /** mag = linear and min = linear and mip = none */
  18264. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18265. /** mag = linear and min = nearest and mip = none */
  18266. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18267. /** Explicit coordinates mode */
  18268. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18269. /** Spherical coordinates mode */
  18270. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18271. /** Planar coordinates mode */
  18272. Engine.TEXTURE_PLANAR_MODE = 2;
  18273. /** Cubic coordinates mode */
  18274. Engine.TEXTURE_CUBIC_MODE = 3;
  18275. /** Projection coordinates mode */
  18276. Engine.TEXTURE_PROJECTION_MODE = 4;
  18277. /** Skybox coordinates mode */
  18278. Engine.TEXTURE_SKYBOX_MODE = 5;
  18279. /** Inverse Cubic coordinates mode */
  18280. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18281. /** Equirectangular coordinates mode */
  18282. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18283. /** Equirectangular Fixed coordinates mode */
  18284. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18285. /** Equirectangular Fixed Mirrored coordinates mode */
  18286. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18287. // Texture rescaling mode
  18288. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18289. Engine.SCALEMODE_FLOOR = 1;
  18290. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18291. Engine.SCALEMODE_NEAREST = 2;
  18292. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18293. Engine.SCALEMODE_CEILING = 3;
  18294. // Updatable statics so stick with vars here
  18295. /**
  18296. * Gets or sets the epsilon value used by collision engine
  18297. */
  18298. Engine.CollisionsEpsilon = 0.001;
  18299. /**
  18300. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18301. */
  18302. Engine.CodeRepository = "src/";
  18303. /**
  18304. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18305. */
  18306. Engine.ShadersRepository = "src/Shaders/";
  18307. return Engine;
  18308. }());
  18309. BABYLON.Engine = Engine;
  18310. })(BABYLON || (BABYLON = {}));
  18311. //# sourceMappingURL=babylon.engine.js.map
  18312. var BABYLON;
  18313. (function (BABYLON) {
  18314. /**
  18315. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18316. */
  18317. var Node = /** @class */ (function () {
  18318. /**
  18319. * Creates a new Node
  18320. * @param name the name and id to be given to this node
  18321. * @param scene the scene this node will be added to
  18322. */
  18323. function Node(name, scene) {
  18324. if (scene === void 0) { scene = null; }
  18325. /**
  18326. * Gets or sets a string used to store user defined state for the node
  18327. */
  18328. this.state = "";
  18329. /**
  18330. * Gets or sets an object used to store user defined information for the node
  18331. */
  18332. this.metadata = null;
  18333. /**
  18334. * Gets or sets a boolean used to define if the node must be serialized
  18335. */
  18336. this.doNotSerialize = false;
  18337. /** @hidden */
  18338. this._isDisposed = false;
  18339. /**
  18340. * Gets a list of Animations associated with the node
  18341. */
  18342. this.animations = new Array();
  18343. this._ranges = {};
  18344. this._isEnabled = true;
  18345. this._isParentEnabled = true;
  18346. this._isReady = true;
  18347. /** @hidden */
  18348. this._currentRenderId = -1;
  18349. this._parentRenderId = -1;
  18350. this._childRenderId = -1;
  18351. /** @hidden */
  18352. this._worldMatrix = BABYLON.Matrix.Identity();
  18353. /** @hidden */
  18354. this._worldMatrixDeterminant = 0;
  18355. /** @hidden */
  18356. this._sceneRootNodesIndex = -1;
  18357. this._animationPropertiesOverride = null;
  18358. /**
  18359. * An event triggered when the mesh is disposed
  18360. */
  18361. this.onDisposeObservable = new BABYLON.Observable();
  18362. // Behaviors
  18363. this._behaviors = new Array();
  18364. this.name = name;
  18365. this.id = name;
  18366. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18367. this.uniqueId = this._scene.getUniqueId();
  18368. this._initCache();
  18369. this.addToSceneRootNodes();
  18370. }
  18371. /**
  18372. * Add a new node constructor
  18373. * @param type defines the type name of the node to construct
  18374. * @param constructorFunc defines the constructor function
  18375. */
  18376. Node.AddNodeConstructor = function (type, constructorFunc) {
  18377. this._NodeConstructors[type] = constructorFunc;
  18378. };
  18379. /**
  18380. * Returns a node constructor based on type name
  18381. * @param type defines the type name
  18382. * @param name defines the new node name
  18383. * @param scene defines the hosting scene
  18384. * @param options defines optional options to transmit to constructors
  18385. * @returns the new constructor or null
  18386. */
  18387. Node.Construct = function (type, name, scene, options) {
  18388. var constructorFunc = this._NodeConstructors[type];
  18389. if (!constructorFunc) {
  18390. return null;
  18391. }
  18392. return constructorFunc(name, scene, options);
  18393. };
  18394. /**
  18395. * Gets a boolean indicating if the node has been disposed
  18396. * @returns true if the node was disposed
  18397. */
  18398. Node.prototype.isDisposed = function () {
  18399. return this._isDisposed;
  18400. };
  18401. Object.defineProperty(Node.prototype, "parent", {
  18402. get: function () {
  18403. return this._parentNode;
  18404. },
  18405. /**
  18406. * Gets or sets the parent of the node
  18407. */
  18408. set: function (parent) {
  18409. if (this._parentNode === parent) {
  18410. return;
  18411. }
  18412. var previousParentNode = this._parentNode;
  18413. // Remove self from list of children of parent
  18414. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18415. var index = this._parentNode._children.indexOf(this);
  18416. if (index !== -1) {
  18417. this._parentNode._children.splice(index, 1);
  18418. }
  18419. if (!parent) {
  18420. this.addToSceneRootNodes();
  18421. }
  18422. }
  18423. // Store new parent
  18424. this._parentNode = parent;
  18425. // Add as child to new parent
  18426. if (this._parentNode) {
  18427. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18428. this._parentNode._children = new Array();
  18429. }
  18430. this._parentNode._children.push(this);
  18431. if (!previousParentNode) {
  18432. this.removeFromSceneRootNodes();
  18433. }
  18434. }
  18435. // Enabled state
  18436. this._syncParentEnabledState();
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Node.prototype.addToSceneRootNodes = function () {
  18442. if (this._sceneRootNodesIndex === -1) {
  18443. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18444. this._scene.rootNodes.push(this);
  18445. }
  18446. };
  18447. Node.prototype.removeFromSceneRootNodes = function () {
  18448. if (this._sceneRootNodesIndex !== -1) {
  18449. var rootNodes = this._scene.rootNodes;
  18450. var lastIdx = rootNodes.length - 1;
  18451. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18452. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18453. this._scene.rootNodes.pop();
  18454. this._sceneRootNodesIndex = -1;
  18455. }
  18456. };
  18457. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18458. /**
  18459. * Gets or sets the animation properties override
  18460. */
  18461. get: function () {
  18462. if (!this._animationPropertiesOverride) {
  18463. return this._scene.animationPropertiesOverride;
  18464. }
  18465. return this._animationPropertiesOverride;
  18466. },
  18467. set: function (value) {
  18468. this._animationPropertiesOverride = value;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. /**
  18474. * Gets a string idenfifying the name of the class
  18475. * @returns "Node" string
  18476. */
  18477. Node.prototype.getClassName = function () {
  18478. return "Node";
  18479. };
  18480. Object.defineProperty(Node.prototype, "onDispose", {
  18481. /**
  18482. * Sets a callback that will be raised when the node will be disposed
  18483. */
  18484. set: function (callback) {
  18485. if (this._onDisposeObserver) {
  18486. this.onDisposeObservable.remove(this._onDisposeObserver);
  18487. }
  18488. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18489. },
  18490. enumerable: true,
  18491. configurable: true
  18492. });
  18493. /**
  18494. * Gets the scene of the node
  18495. * @returns a scene
  18496. */
  18497. Node.prototype.getScene = function () {
  18498. return this._scene;
  18499. };
  18500. /**
  18501. * Gets the engine of the node
  18502. * @returns a Engine
  18503. */
  18504. Node.prototype.getEngine = function () {
  18505. return this._scene.getEngine();
  18506. };
  18507. /**
  18508. * Attach a behavior to the node
  18509. * @see http://doc.babylonjs.com/features/behaviour
  18510. * @param behavior defines the behavior to attach
  18511. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18512. * @returns the current Node
  18513. */
  18514. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18515. var _this = this;
  18516. if (attachImmediately === void 0) { attachImmediately = false; }
  18517. var index = this._behaviors.indexOf(behavior);
  18518. if (index !== -1) {
  18519. return this;
  18520. }
  18521. behavior.init();
  18522. if (this._scene.isLoading && !attachImmediately) {
  18523. // We defer the attach when the scene will be loaded
  18524. this._scene.onDataLoadedObservable.addOnce(function () {
  18525. behavior.attach(_this);
  18526. });
  18527. }
  18528. else {
  18529. behavior.attach(this);
  18530. }
  18531. this._behaviors.push(behavior);
  18532. return this;
  18533. };
  18534. /**
  18535. * Remove an attached behavior
  18536. * @see http://doc.babylonjs.com/features/behaviour
  18537. * @param behavior defines the behavior to attach
  18538. * @returns the current Node
  18539. */
  18540. Node.prototype.removeBehavior = function (behavior) {
  18541. var index = this._behaviors.indexOf(behavior);
  18542. if (index === -1) {
  18543. return this;
  18544. }
  18545. this._behaviors[index].detach();
  18546. this._behaviors.splice(index, 1);
  18547. return this;
  18548. };
  18549. Object.defineProperty(Node.prototype, "behaviors", {
  18550. /**
  18551. * Gets the list of attached behaviors
  18552. * @see http://doc.babylonjs.com/features/behaviour
  18553. */
  18554. get: function () {
  18555. return this._behaviors;
  18556. },
  18557. enumerable: true,
  18558. configurable: true
  18559. });
  18560. /**
  18561. * Gets an attached behavior by name
  18562. * @param name defines the name of the behavior to look for
  18563. * @see http://doc.babylonjs.com/features/behaviour
  18564. * @returns null if behavior was not found else the requested behavior
  18565. */
  18566. Node.prototype.getBehaviorByName = function (name) {
  18567. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18568. var behavior = _a[_i];
  18569. if (behavior.name === name) {
  18570. return behavior;
  18571. }
  18572. }
  18573. return null;
  18574. };
  18575. /**
  18576. * Returns the latest update of the World matrix
  18577. * @returns a Matrix
  18578. */
  18579. Node.prototype.getWorldMatrix = function () {
  18580. if (this._currentRenderId !== this._scene.getRenderId()) {
  18581. this.computeWorldMatrix();
  18582. }
  18583. return this._worldMatrix;
  18584. };
  18585. /** @hidden */
  18586. Node.prototype._getWorldMatrixDeterminant = function () {
  18587. return this._worldMatrixDeterminant;
  18588. };
  18589. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18590. /**
  18591. * Returns directly the latest state of the mesh World matrix.
  18592. * A Matrix is returned.
  18593. */
  18594. get: function () {
  18595. return this._worldMatrix;
  18596. },
  18597. enumerable: true,
  18598. configurable: true
  18599. });
  18600. // override it in derived class if you add new variables to the cache
  18601. // and call the parent class method
  18602. /** @hidden */
  18603. Node.prototype._initCache = function () {
  18604. this._cache = {};
  18605. this._cache.parent = undefined;
  18606. };
  18607. /** @hidden */
  18608. Node.prototype.updateCache = function (force) {
  18609. if (!force && this.isSynchronized())
  18610. return;
  18611. this._cache.parent = this.parent;
  18612. this._updateCache();
  18613. };
  18614. // override it in derived class if you add new variables to the cache
  18615. // and call the parent class method if !ignoreParentClass
  18616. /** @hidden */
  18617. Node.prototype._updateCache = function (ignoreParentClass) {
  18618. };
  18619. // override it in derived class if you add new variables to the cache
  18620. /** @hidden */
  18621. Node.prototype._isSynchronized = function () {
  18622. return true;
  18623. };
  18624. /** @hidden */
  18625. Node.prototype._markSyncedWithParent = function () {
  18626. if (this._parentNode) {
  18627. this._parentRenderId = this._parentNode._childRenderId;
  18628. }
  18629. };
  18630. /** @hidden */
  18631. Node.prototype.isSynchronizedWithParent = function () {
  18632. if (!this._parentNode) {
  18633. return true;
  18634. }
  18635. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18636. return false;
  18637. }
  18638. return this._parentNode.isSynchronized();
  18639. };
  18640. /** @hidden */
  18641. Node.prototype.isSynchronized = function () {
  18642. if (this._cache.parent != this._parentNode) {
  18643. this._cache.parent = this._parentNode;
  18644. return false;
  18645. }
  18646. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18647. return false;
  18648. }
  18649. return this._isSynchronized();
  18650. };
  18651. /**
  18652. * Is this node ready to be used/rendered
  18653. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18654. * @return true if the node is ready
  18655. */
  18656. Node.prototype.isReady = function (completeCheck) {
  18657. if (completeCheck === void 0) { completeCheck = false; }
  18658. return this._isReady;
  18659. };
  18660. /**
  18661. * Is this node enabled?
  18662. * 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
  18663. * @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
  18664. * @return whether this node (and its parent) is enabled
  18665. */
  18666. Node.prototype.isEnabled = function (checkAncestors) {
  18667. if (checkAncestors === void 0) { checkAncestors = true; }
  18668. if (checkAncestors === false) {
  18669. return this._isEnabled;
  18670. }
  18671. if (!this._isEnabled) {
  18672. return false;
  18673. }
  18674. return this._isParentEnabled;
  18675. };
  18676. /** @hidden */
  18677. Node.prototype._syncParentEnabledState = function () {
  18678. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18679. if (this._children) {
  18680. this._children.forEach(function (c) {
  18681. c._syncParentEnabledState(); // Force children to update accordingly
  18682. });
  18683. }
  18684. };
  18685. /**
  18686. * Set the enabled state of this node
  18687. * @param value defines the new enabled state
  18688. */
  18689. Node.prototype.setEnabled = function (value) {
  18690. this._isEnabled = value;
  18691. this._syncParentEnabledState();
  18692. };
  18693. /**
  18694. * Is this node a descendant of the given node?
  18695. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18696. * @param ancestor defines the parent node to inspect
  18697. * @returns a boolean indicating if this node is a descendant of the given node
  18698. */
  18699. Node.prototype.isDescendantOf = function (ancestor) {
  18700. if (this.parent) {
  18701. if (this.parent === ancestor) {
  18702. return true;
  18703. }
  18704. return this.parent.isDescendantOf(ancestor);
  18705. }
  18706. return false;
  18707. };
  18708. /** @hidden */
  18709. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18710. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18711. if (!this._children) {
  18712. return;
  18713. }
  18714. for (var index = 0; index < this._children.length; index++) {
  18715. var item = this._children[index];
  18716. if (!predicate || predicate(item)) {
  18717. results.push(item);
  18718. }
  18719. if (!directDescendantsOnly) {
  18720. item._getDescendants(results, false, predicate);
  18721. }
  18722. }
  18723. };
  18724. /**
  18725. * Will return all nodes that have this node as ascendant
  18726. * @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
  18727. * @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
  18728. * @return all children nodes of all types
  18729. */
  18730. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18731. var results = new Array();
  18732. this._getDescendants(results, directDescendantsOnly, predicate);
  18733. return results;
  18734. };
  18735. /**
  18736. * Get all child-meshes of this node
  18737. * @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
  18738. * @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
  18739. * @returns an array of AbstractMesh
  18740. */
  18741. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18742. var results = [];
  18743. this._getDescendants(results, directDescendantsOnly, function (node) {
  18744. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18745. });
  18746. return results;
  18747. };
  18748. /**
  18749. * Get all child-transformNodes of this node
  18750. * @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
  18751. * @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
  18752. * @returns an array of TransformNode
  18753. */
  18754. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18755. var results = [];
  18756. this._getDescendants(results, directDescendantsOnly, function (node) {
  18757. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18758. });
  18759. return results;
  18760. };
  18761. /**
  18762. * Get all direct children of this node
  18763. * @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
  18764. * @returns an array of Node
  18765. */
  18766. Node.prototype.getChildren = function (predicate) {
  18767. return this.getDescendants(true, predicate);
  18768. };
  18769. /** @hidden */
  18770. Node.prototype._setReady = function (state) {
  18771. if (state === this._isReady) {
  18772. return;
  18773. }
  18774. if (!state) {
  18775. this._isReady = false;
  18776. return;
  18777. }
  18778. if (this.onReady) {
  18779. this.onReady(this);
  18780. }
  18781. this._isReady = true;
  18782. };
  18783. /**
  18784. * Get an animation by name
  18785. * @param name defines the name of the animation to look for
  18786. * @returns null if not found else the requested animation
  18787. */
  18788. Node.prototype.getAnimationByName = function (name) {
  18789. for (var i = 0; i < this.animations.length; i++) {
  18790. var animation = this.animations[i];
  18791. if (animation.name === name) {
  18792. return animation;
  18793. }
  18794. }
  18795. return null;
  18796. };
  18797. /**
  18798. * Creates an animation range for this node
  18799. * @param name defines the name of the range
  18800. * @param from defines the starting key
  18801. * @param to defines the end key
  18802. */
  18803. Node.prototype.createAnimationRange = function (name, from, to) {
  18804. // check name not already in use
  18805. if (!this._ranges[name]) {
  18806. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18807. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18808. if (this.animations[i]) {
  18809. this.animations[i].createRange(name, from, to);
  18810. }
  18811. }
  18812. }
  18813. };
  18814. /**
  18815. * Delete a specific animation range
  18816. * @param name defines the name of the range to delete
  18817. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18818. */
  18819. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18820. if (deleteFrames === void 0) { deleteFrames = true; }
  18821. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18822. if (this.animations[i]) {
  18823. this.animations[i].deleteRange(name, deleteFrames);
  18824. }
  18825. }
  18826. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18827. };
  18828. /**
  18829. * Get an animation range by name
  18830. * @param name defines the name of the animation range to look for
  18831. * @returns null if not found else the requested animation range
  18832. */
  18833. Node.prototype.getAnimationRange = function (name) {
  18834. return this._ranges[name];
  18835. };
  18836. /**
  18837. * Will start the animation sequence
  18838. * @param name defines the range frames for animation sequence
  18839. * @param loop defines if the animation should loop (false by default)
  18840. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18841. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18842. * @returns the object created for this animation. If range does not exist, it will return null
  18843. */
  18844. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18845. var range = this.getAnimationRange(name);
  18846. if (!range) {
  18847. return null;
  18848. }
  18849. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18850. };
  18851. /**
  18852. * Serialize animation ranges into a JSON compatible object
  18853. * @returns serialization object
  18854. */
  18855. Node.prototype.serializeAnimationRanges = function () {
  18856. var serializationRanges = [];
  18857. for (var name in this._ranges) {
  18858. var localRange = this._ranges[name];
  18859. if (!localRange) {
  18860. continue;
  18861. }
  18862. var range = {};
  18863. range.name = name;
  18864. range.from = localRange.from;
  18865. range.to = localRange.to;
  18866. serializationRanges.push(range);
  18867. }
  18868. return serializationRanges;
  18869. };
  18870. /**
  18871. * Computes the world matrix of the node
  18872. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18873. * @returns the world matrix
  18874. */
  18875. Node.prototype.computeWorldMatrix = function (force) {
  18876. if (!this._worldMatrix) {
  18877. this._worldMatrix = BABYLON.Matrix.Identity();
  18878. }
  18879. return this._worldMatrix;
  18880. };
  18881. /**
  18882. * Releases resources associated with this node.
  18883. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18884. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18885. */
  18886. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18887. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18888. if (!doNotRecurse) {
  18889. var nodes = this.getDescendants(true);
  18890. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18891. var node = nodes_1[_i];
  18892. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18893. }
  18894. }
  18895. else {
  18896. var transformNodes = this.getChildTransformNodes(true);
  18897. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18898. var transformNode = transformNodes_1[_a];
  18899. transformNode.parent = null;
  18900. transformNode.computeWorldMatrix(true);
  18901. }
  18902. }
  18903. if (!this.parent) {
  18904. this.removeFromSceneRootNodes();
  18905. }
  18906. else {
  18907. this.parent = null;
  18908. }
  18909. // Callback
  18910. this.onDisposeObservable.notifyObservers(this);
  18911. this.onDisposeObservable.clear();
  18912. // Behaviors
  18913. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18914. var behavior = _c[_b];
  18915. behavior.detach();
  18916. }
  18917. this._behaviors = [];
  18918. this._isDisposed = true;
  18919. };
  18920. /**
  18921. * Parse animation range data from a serialization object and store them into a given node
  18922. * @param node defines where to store the animation ranges
  18923. * @param parsedNode defines the serialization object to read data from
  18924. * @param scene defines the hosting scene
  18925. */
  18926. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18927. if (parsedNode.ranges) {
  18928. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18929. var data = parsedNode.ranges[index];
  18930. node.createAnimationRange(data.name, data.from, data.to);
  18931. }
  18932. }
  18933. };
  18934. Node._NodeConstructors = {};
  18935. __decorate([
  18936. BABYLON.serialize()
  18937. ], Node.prototype, "name", void 0);
  18938. __decorate([
  18939. BABYLON.serialize()
  18940. ], Node.prototype, "id", void 0);
  18941. __decorate([
  18942. BABYLON.serialize()
  18943. ], Node.prototype, "uniqueId", void 0);
  18944. __decorate([
  18945. BABYLON.serialize()
  18946. ], Node.prototype, "state", void 0);
  18947. __decorate([
  18948. BABYLON.serialize()
  18949. ], Node.prototype, "metadata", void 0);
  18950. return Node;
  18951. }());
  18952. BABYLON.Node = Node;
  18953. })(BABYLON || (BABYLON = {}));
  18954. //# sourceMappingURL=babylon.node.js.map
  18955. var BABYLON;
  18956. (function (BABYLON) {
  18957. // This matrix is used as a value to reset the bounding box.
  18958. var _identityMatrix = BABYLON.Matrix.Identity();
  18959. /**
  18960. * Class used to store bounding sphere information
  18961. */
  18962. var BoundingSphere = /** @class */ (function () {
  18963. /**
  18964. * Creates a new bounding sphere
  18965. * @param min defines the minimum vector (in local space)
  18966. * @param max defines the maximum vector (in local space)
  18967. */
  18968. function BoundingSphere(min, max) {
  18969. /**
  18970. * Gets the center of the bounding sphere in local space
  18971. */
  18972. this.center = BABYLON.Vector3.Zero();
  18973. /**
  18974. * Gets the center of the bounding sphere in world space
  18975. */
  18976. this.centerWorld = BABYLON.Vector3.Zero();
  18977. /**
  18978. * Gets the minimum vector in local space
  18979. */
  18980. this.minimum = BABYLON.Vector3.Zero();
  18981. /**
  18982. * Gets the maximum vector in local space
  18983. */
  18984. this.maximum = BABYLON.Vector3.Zero();
  18985. this.reConstruct(min, max);
  18986. }
  18987. /**
  18988. * Recreates the entire bounding sphere from scratch
  18989. * @param min defines the new minimum vector (in local space)
  18990. * @param max defines the new maximum vector (in local space)
  18991. */
  18992. BoundingSphere.prototype.reConstruct = function (min, max) {
  18993. this.minimum.copyFrom(min);
  18994. this.maximum.copyFrom(max);
  18995. var distance = BABYLON.Vector3.Distance(min, max);
  18996. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  18997. this.radius = distance * 0.5;
  18998. this.centerWorld.set(0, 0, 0);
  18999. this._update(_identityMatrix);
  19000. };
  19001. /**
  19002. * Scale the current bounding sphere by applying a scale factor
  19003. * @param factor defines the scale factor to apply
  19004. * @returns the current bounding box
  19005. */
  19006. BoundingSphere.prototype.scale = function (factor) {
  19007. var newRadius = this.radius * factor;
  19008. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  19009. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  19010. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19011. this.reConstruct(min, max);
  19012. return this;
  19013. };
  19014. // Methods
  19015. /** @hidden */
  19016. BoundingSphere.prototype._update = function (world) {
  19017. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19018. var tempVector = BABYLON.Tmp.Vector3[0];
  19019. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19020. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19021. };
  19022. /**
  19023. * Tests if the bounding sphere is intersecting the frustum planes
  19024. * @param frustumPlanes defines the frustum planes to test
  19025. * @returns true if there is an intersection
  19026. */
  19027. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19028. for (var i = 0; i < 6; i++) {
  19029. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  19030. return false;
  19031. }
  19032. return true;
  19033. };
  19034. /**
  19035. * Tests if a point is inside the bounding sphere
  19036. * @param point defines the point to test
  19037. * @returns true if the point is inside the bounding sphere
  19038. */
  19039. BoundingSphere.prototype.intersectsPoint = function (point) {
  19040. var x = this.centerWorld.x - point.x;
  19041. var y = this.centerWorld.y - point.y;
  19042. var z = this.centerWorld.z - point.z;
  19043. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19044. if (this.radiusWorld < distance)
  19045. return false;
  19046. return true;
  19047. };
  19048. // Statics
  19049. /**
  19050. * Checks if two sphere intersct
  19051. * @param sphere0 sphere 0
  19052. * @param sphere1 sphere 1
  19053. * @returns true if the speres intersect
  19054. */
  19055. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19056. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19057. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19058. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19059. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19060. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  19061. return false;
  19062. return true;
  19063. };
  19064. return BoundingSphere;
  19065. }());
  19066. BABYLON.BoundingSphere = BoundingSphere;
  19067. })(BABYLON || (BABYLON = {}));
  19068. //# sourceMappingURL=babylon.boundingSphere.js.map
  19069. var BABYLON;
  19070. (function (BABYLON) {
  19071. /**
  19072. * Class used to store bounding box information
  19073. */
  19074. var BoundingBox = /** @class */ (function () {
  19075. /**
  19076. * Creates a new bounding box
  19077. * @param min defines the minimum vector (in local space)
  19078. * @param max defines the maximum vector (in local space)
  19079. */
  19080. function BoundingBox(min, max) {
  19081. /**
  19082. * Gets the 8 vectors representing the bounding box in local space
  19083. */
  19084. this.vectors = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19085. /**
  19086. * Gets the center of the bounding box in local space
  19087. */
  19088. this.center = BABYLON.Vector3.Zero();
  19089. /**
  19090. * Gets the center of the bounding box in world space
  19091. */
  19092. this.centerWorld = BABYLON.Vector3.Zero();
  19093. /**
  19094. * Gets the extend size in local space
  19095. */
  19096. this.extendSize = BABYLON.Vector3.Zero();
  19097. /**
  19098. * Gets the extend size in world space
  19099. */
  19100. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19101. /**
  19102. * Gets the OBB (object bounding box) directions
  19103. */
  19104. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19105. /**
  19106. * Gets the 8 vectors representing the bounding box in world space
  19107. */
  19108. this.vectorsWorld = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19109. /**
  19110. * Gets the minimum vector in world space
  19111. */
  19112. this.minimumWorld = BABYLON.Vector3.Zero();
  19113. /**
  19114. * Gets the maximum vector in world space
  19115. */
  19116. this.maximumWorld = BABYLON.Vector3.Zero();
  19117. /**
  19118. * Gets the minimum vector in local space
  19119. */
  19120. this.minimum = BABYLON.Vector3.Zero();
  19121. /**
  19122. * Gets the maximum vector in local space
  19123. */
  19124. this.maximum = BABYLON.Vector3.Zero();
  19125. this.reConstruct(min, max);
  19126. }
  19127. ;
  19128. // Methods
  19129. /**
  19130. * Recreates the entire bounding box from scratch
  19131. * @param min defines the new minimum vector (in local space)
  19132. * @param max defines the new maximum vector (in local space)
  19133. */
  19134. BoundingBox.prototype.reConstruct = function (min, max) {
  19135. this.minimum.copyFrom(min);
  19136. this.maximum.copyFrom(max);
  19137. // Bounding vectors
  19138. this.vectors[0].copyFrom(this.minimum);
  19139. this.vectors[1].copyFrom(this.maximum);
  19140. this.vectors[2].copyFrom(this.minimum);
  19141. this.vectors[3].copyFrom(this.minimum);
  19142. this.vectors[4].copyFrom(this.minimum);
  19143. this.vectors[5].copyFrom(this.maximum);
  19144. this.vectors[6].copyFrom(this.maximum);
  19145. this.vectors[7].copyFrom(this.maximum);
  19146. this.vectors[2].x = this.maximum.x;
  19147. this.vectors[3].y = this.maximum.y;
  19148. this.vectors[4].z = this.maximum.z;
  19149. this.vectors[5].z = this.minimum.z;
  19150. this.vectors[6].x = this.minimum.x;
  19151. this.vectors[7].y = this.minimum.y;
  19152. // OBB
  19153. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19154. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19155. for (var index = 0; index < 3; index++) {
  19156. this.directions[index].copyFromFloats(0, 0, 0);
  19157. }
  19158. // World
  19159. for (var index = 0; index < 8; index++) {
  19160. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19161. }
  19162. this.minimumWorld.copyFromFloats(0, 0, 0);
  19163. this.maximumWorld.copyFromFloats(0, 0, 0);
  19164. this.centerWorld.copyFromFloats(0, 0, 0);
  19165. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19166. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19167. };
  19168. /**
  19169. * Scale the current bounding box by applying a scale factor
  19170. * @param factor defines the scale factor to apply
  19171. * @returns the current bounding box
  19172. */
  19173. BoundingBox.prototype.scale = function (factor) {
  19174. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19175. var distance = diff.length() * factor;
  19176. diff.normalize();
  19177. var newRadius = diff.scaleInPlace(distance * 0.5);
  19178. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19179. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19180. this.reConstruct(min, max);
  19181. return this;
  19182. };
  19183. /**
  19184. * Gets the world matrix of the bounding box
  19185. * @returns a matrix
  19186. */
  19187. BoundingBox.prototype.getWorldMatrix = function () {
  19188. return this._worldMatrix;
  19189. };
  19190. /**
  19191. * Sets the world matrix stored in the bounding box
  19192. * @param matrix defines the matrix to store
  19193. * @returns current bounding box
  19194. */
  19195. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19196. this._worldMatrix.copyFrom(matrix);
  19197. return this;
  19198. };
  19199. /** @hidden */
  19200. BoundingBox.prototype._update = function (world) {
  19201. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19202. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19203. for (var index = 0; index < 8; index++) {
  19204. var v = this.vectorsWorld[index];
  19205. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19206. this.minimumWorld.minimizeInPlace(v);
  19207. this.maximumWorld.maximizeInPlace(v);
  19208. }
  19209. // Extend
  19210. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19211. this.extendSizeWorld.scaleInPlace(0.5);
  19212. // OBB
  19213. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19214. this.centerWorld.scaleInPlace(0.5);
  19215. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19216. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19217. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19218. this._worldMatrix = world;
  19219. };
  19220. /**
  19221. * Tests if the bounding box is intersecting the frustum planes
  19222. * @param frustumPlanes defines the frustum planes to test
  19223. * @returns true if there is an intersection
  19224. */
  19225. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19226. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19227. };
  19228. /**
  19229. * Tests if the bounding box is entirely inside the frustum planes
  19230. * @param frustumPlanes defines the frustum planes to test
  19231. * @returns true if there is an inclusion
  19232. */
  19233. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19234. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19235. };
  19236. /**
  19237. * Tests if a point is inside the bounding box
  19238. * @param point defines the point to test
  19239. * @returns true if the point is inside the bounding box
  19240. */
  19241. BoundingBox.prototype.intersectsPoint = function (point) {
  19242. var delta = -BABYLON.Epsilon;
  19243. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19244. return false;
  19245. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19246. return false;
  19247. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19248. return false;
  19249. return true;
  19250. };
  19251. /**
  19252. * Tests if the bounding box intersects with a bounding sphere
  19253. * @param sphere defines the sphere to test
  19254. * @returns true if there is an intersection
  19255. */
  19256. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19257. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19258. };
  19259. /**
  19260. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19261. * @param min defines the min vector to use
  19262. * @param max defines the max vector to use
  19263. * @returns true if there is an intersection
  19264. */
  19265. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19266. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19267. return false;
  19268. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19269. return false;
  19270. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19271. return false;
  19272. return true;
  19273. };
  19274. // Statics
  19275. /**
  19276. * Tests if two bounding boxes are intersections
  19277. * @param box0 defines the first box to test
  19278. * @param box1 defines the second box to test
  19279. * @returns true if there is an intersection
  19280. */
  19281. BoundingBox.Intersects = function (box0, box1) {
  19282. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19283. return false;
  19284. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19285. return false;
  19286. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19287. return false;
  19288. return true;
  19289. };
  19290. /**
  19291. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19292. * @param minPoint defines the minimum vector of the bounding box
  19293. * @param maxPoint defines the maximum vector of the bounding box
  19294. * @param sphereCenter defines the sphere center
  19295. * @param sphereRadius defines the sphere radius
  19296. * @returns true if there is an intersection
  19297. */
  19298. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19299. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19300. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19301. return (num <= (sphereRadius * sphereRadius));
  19302. };
  19303. /**
  19304. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19305. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19306. * @param frustumPlanes defines the frustum planes to test
  19307. * @return true if there is an inclusion
  19308. */
  19309. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19310. for (var p = 0; p < 6; p++) {
  19311. for (var i = 0; i < 8; i++) {
  19312. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19313. return false;
  19314. }
  19315. }
  19316. }
  19317. return true;
  19318. };
  19319. /**
  19320. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19321. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19322. * @param frustumPlanes defines the frustum planes to test
  19323. * @return true if there is an intersection
  19324. */
  19325. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19326. for (var p = 0; p < 6; p++) {
  19327. var inCount = 8;
  19328. for (var i = 0; i < 8; i++) {
  19329. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19330. --inCount;
  19331. }
  19332. else {
  19333. break;
  19334. }
  19335. }
  19336. if (inCount === 0)
  19337. return false;
  19338. }
  19339. return true;
  19340. };
  19341. return BoundingBox;
  19342. }());
  19343. BABYLON.BoundingBox = BoundingBox;
  19344. })(BABYLON || (BABYLON = {}));
  19345. //# sourceMappingURL=babylon.boundingBox.js.map
  19346. var BABYLON;
  19347. (function (BABYLON) {
  19348. var computeBoxExtents = function (axis, box) {
  19349. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19350. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19351. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19352. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19353. var r = r0 + r1 + r2;
  19354. return {
  19355. min: p - r,
  19356. max: p + r
  19357. };
  19358. };
  19359. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19360. var axisOverlap = function (axis, box0, box1) {
  19361. var result0 = computeBoxExtents(axis, box0);
  19362. var result1 = computeBoxExtents(axis, box1);
  19363. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19364. };
  19365. /**
  19366. * Info for a bounding data of a mesh
  19367. */
  19368. var BoundingInfo = /** @class */ (function () {
  19369. /**
  19370. * Constructs bounding info
  19371. * @param minimum min vector of the bounding box/sphere
  19372. * @param maximum max vector of the bounding box/sphere
  19373. */
  19374. function BoundingInfo(minimum, maximum) {
  19375. this._isLocked = false;
  19376. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19377. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19378. }
  19379. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19380. /**
  19381. * min vector of the bounding box/sphere
  19382. */
  19383. get: function () {
  19384. return this.boundingBox.minimum;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19390. /**
  19391. * max vector of the bounding box/sphere
  19392. */
  19393. get: function () {
  19394. return this.boundingBox.maximum;
  19395. },
  19396. enumerable: true,
  19397. configurable: true
  19398. });
  19399. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19400. /**
  19401. * If the info is locked and won't be updated to avoid perf overhead
  19402. */
  19403. get: function () {
  19404. return this._isLocked;
  19405. },
  19406. set: function (value) {
  19407. this._isLocked = value;
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. // Methods
  19413. /**
  19414. * Updates the boudning sphere and box
  19415. * @param world world matrix to be used to update
  19416. */
  19417. BoundingInfo.prototype.update = function (world) {
  19418. if (this._isLocked) {
  19419. return;
  19420. }
  19421. this.boundingBox._update(world);
  19422. this.boundingSphere._update(world);
  19423. };
  19424. /**
  19425. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19426. * @param center New center of the bounding info
  19427. * @param extend New extend of the bounding info
  19428. * @returns the current bounding info
  19429. */
  19430. BoundingInfo.prototype.centerOn = function (center, extend) {
  19431. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19432. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19433. this.boundingBox.reConstruct(minimum, maximum);
  19434. this.boundingSphere.reConstruct(minimum, maximum);
  19435. return this;
  19436. };
  19437. /**
  19438. * Scale the current bounding info by applying a scale factor
  19439. * @param factor defines the scale factor to apply
  19440. * @returns the current bounding info
  19441. */
  19442. BoundingInfo.prototype.scale = function (factor) {
  19443. this.boundingBox.scale(factor);
  19444. this.boundingSphere.scale(factor);
  19445. return this;
  19446. };
  19447. /**
  19448. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19449. * @param frustumPlanes defines the frustum to test
  19450. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19451. * @returns true if the bounding info is in the frustum planes
  19452. */
  19453. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19454. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19455. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19456. return false;
  19457. }
  19458. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19459. return true;
  19460. }
  19461. return this.boundingBox.isInFrustum(frustumPlanes);
  19462. };
  19463. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19464. /**
  19465. * Gets the world distance between the min and max points of the bounding box
  19466. */
  19467. get: function () {
  19468. var boundingBox = this.boundingBox;
  19469. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19470. return size.length();
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. /**
  19476. * Checks if a cullable object (mesh...) is in the camera frustum
  19477. * Unlike isInFrustum this cheks the full bounding box
  19478. * @param frustumPlanes Camera near/planes
  19479. * @returns true if the object is in frustum otherwise false
  19480. */
  19481. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19482. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19483. };
  19484. /** @hidden */
  19485. BoundingInfo.prototype._checkCollision = function (collider) {
  19486. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19487. };
  19488. /**
  19489. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19490. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19491. * @param point the point to check intersection with
  19492. * @returns if the point intersects
  19493. */
  19494. BoundingInfo.prototype.intersectsPoint = function (point) {
  19495. if (!this.boundingSphere.centerWorld) {
  19496. return false;
  19497. }
  19498. if (!this.boundingSphere.intersectsPoint(point)) {
  19499. return false;
  19500. }
  19501. if (!this.boundingBox.intersectsPoint(point)) {
  19502. return false;
  19503. }
  19504. return true;
  19505. };
  19506. /**
  19507. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19508. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19509. * @param boundingInfo the bounding info to check intersection with
  19510. * @param precise if the intersection should be done using OBB
  19511. * @returns if the bounding info intersects
  19512. */
  19513. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19514. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19515. return false;
  19516. }
  19517. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19518. return false;
  19519. }
  19520. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19521. return false;
  19522. }
  19523. if (!precise) {
  19524. return true;
  19525. }
  19526. var box0 = this.boundingBox;
  19527. var box1 = boundingInfo.boundingBox;
  19528. if (!axisOverlap(box0.directions[0], box0, box1))
  19529. return false;
  19530. if (!axisOverlap(box0.directions[1], box0, box1))
  19531. return false;
  19532. if (!axisOverlap(box0.directions[2], box0, box1))
  19533. return false;
  19534. if (!axisOverlap(box1.directions[0], box0, box1))
  19535. return false;
  19536. if (!axisOverlap(box1.directions[1], box0, box1))
  19537. return false;
  19538. if (!axisOverlap(box1.directions[2], box0, box1))
  19539. return false;
  19540. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19541. return false;
  19542. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19543. return false;
  19544. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19545. return false;
  19546. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19547. return false;
  19548. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19549. return false;
  19550. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19551. return false;
  19552. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19553. return false;
  19554. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19555. return false;
  19556. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19557. return false;
  19558. return true;
  19559. };
  19560. return BoundingInfo;
  19561. }());
  19562. BABYLON.BoundingInfo = BoundingInfo;
  19563. })(BABYLON || (BABYLON = {}));
  19564. //# sourceMappingURL=babylon.boundingInfo.js.map
  19565. var BABYLON;
  19566. (function (BABYLON) {
  19567. /**
  19568. * 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.
  19569. * @see https://doc.babylonjs.com/how_to/transformnode
  19570. */
  19571. var TransformNode = /** @class */ (function (_super) {
  19572. __extends(TransformNode, _super);
  19573. function TransformNode(name, scene, isPure) {
  19574. if (scene === void 0) { scene = null; }
  19575. if (isPure === void 0) { isPure = true; }
  19576. var _this = _super.call(this, name, scene) || this;
  19577. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19578. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19579. _this._up = new BABYLON.Vector3(0, 1, 0);
  19580. _this._right = new BABYLON.Vector3(1, 0, 0);
  19581. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19582. // Properties
  19583. _this._position = BABYLON.Vector3.Zero();
  19584. _this._rotation = BABYLON.Vector3.Zero();
  19585. _this._scaling = BABYLON.Vector3.One();
  19586. _this._isDirty = false;
  19587. /**
  19588. * Set the billboard mode. Default is 0.
  19589. *
  19590. * | Value | Type | Description |
  19591. * | --- | --- | --- |
  19592. * | 0 | BILLBOARDMODE_NONE | |
  19593. * | 1 | BILLBOARDMODE_X | |
  19594. * | 2 | BILLBOARDMODE_Y | |
  19595. * | 4 | BILLBOARDMODE_Z | |
  19596. * | 7 | BILLBOARDMODE_ALL | |
  19597. *
  19598. */
  19599. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19600. /**
  19601. * 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
  19602. */
  19603. _this.scalingDeterminant = 1;
  19604. /**
  19605. * Sets the distance of the object to max, often used by skybox
  19606. */
  19607. _this.infiniteDistance = false;
  19608. /**
  19609. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19610. * By default the system will update normals to compensate
  19611. */
  19612. _this.ignoreNonUniformScaling = false;
  19613. _this._localWorld = BABYLON.Matrix.Zero();
  19614. _this._absolutePosition = BABYLON.Vector3.Zero();
  19615. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19616. _this._postMultiplyPivotMatrix = false;
  19617. _this._isWorldMatrixFrozen = false;
  19618. /**
  19619. * An event triggered after the world matrix is updated
  19620. */
  19621. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19622. _this._nonUniformScaling = false;
  19623. if (isPure) {
  19624. _this.getScene().addTransformNode(_this);
  19625. }
  19626. return _this;
  19627. }
  19628. /**
  19629. * Gets a string identifying the name of the class
  19630. * @returns "TransformNode" string
  19631. */
  19632. TransformNode.prototype.getClassName = function () {
  19633. return "TransformNode";
  19634. };
  19635. Object.defineProperty(TransformNode.prototype, "position", {
  19636. /**
  19637. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19638. */
  19639. get: function () {
  19640. return this._position;
  19641. },
  19642. set: function (newPosition) {
  19643. this._position = newPosition;
  19644. this._isDirty = true;
  19645. },
  19646. enumerable: true,
  19647. configurable: true
  19648. });
  19649. Object.defineProperty(TransformNode.prototype, "rotation", {
  19650. /**
  19651. * 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)).
  19652. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19653. */
  19654. get: function () {
  19655. return this._rotation;
  19656. },
  19657. set: function (newRotation) {
  19658. this._rotation = newRotation;
  19659. this._isDirty = true;
  19660. },
  19661. enumerable: true,
  19662. configurable: true
  19663. });
  19664. Object.defineProperty(TransformNode.prototype, "scaling", {
  19665. /**
  19666. * 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)).
  19667. */
  19668. get: function () {
  19669. return this._scaling;
  19670. },
  19671. set: function (newScaling) {
  19672. this._scaling = newScaling;
  19673. this._isDirty = true;
  19674. },
  19675. enumerable: true,
  19676. configurable: true
  19677. });
  19678. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19679. /**
  19680. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19681. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19682. */
  19683. get: function () {
  19684. return this._rotationQuaternion;
  19685. },
  19686. set: function (quaternion) {
  19687. this._rotationQuaternion = quaternion;
  19688. //reset the rotation vector.
  19689. if (quaternion && this.rotation.length()) {
  19690. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19691. }
  19692. },
  19693. enumerable: true,
  19694. configurable: true
  19695. });
  19696. Object.defineProperty(TransformNode.prototype, "forward", {
  19697. /**
  19698. * The forward direction of that transform in world space.
  19699. */
  19700. get: function () {
  19701. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. Object.defineProperty(TransformNode.prototype, "up", {
  19707. /**
  19708. * The up direction of that transform in world space.
  19709. */
  19710. get: function () {
  19711. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19712. },
  19713. enumerable: true,
  19714. configurable: true
  19715. });
  19716. Object.defineProperty(TransformNode.prototype, "right", {
  19717. /**
  19718. * The right direction of that transform in world space.
  19719. */
  19720. get: function () {
  19721. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. /**
  19727. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19728. * @param matrix the matrix to copy the pose from
  19729. * @returns this TransformNode.
  19730. */
  19731. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19732. this._poseMatrix.copyFrom(matrix);
  19733. return this;
  19734. };
  19735. /**
  19736. * Returns the mesh Pose matrix.
  19737. * @returns the pose matrix
  19738. */
  19739. TransformNode.prototype.getPoseMatrix = function () {
  19740. return this._poseMatrix;
  19741. };
  19742. /** @hidden */
  19743. TransformNode.prototype._isSynchronized = function () {
  19744. if (this._isDirty) {
  19745. return false;
  19746. }
  19747. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19748. return false;
  19749. if (this._cache.pivotMatrixUpdated) {
  19750. return false;
  19751. }
  19752. if (this.infiniteDistance) {
  19753. return false;
  19754. }
  19755. if (!this._cache.position.equals(this._position))
  19756. return false;
  19757. if (this._rotationQuaternion) {
  19758. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19759. return false;
  19760. }
  19761. if (!this._cache.rotation.equals(this._rotation))
  19762. return false;
  19763. if (!this._cache.scaling.equals(this._scaling))
  19764. return false;
  19765. return true;
  19766. };
  19767. /** @hidden */
  19768. TransformNode.prototype._initCache = function () {
  19769. _super.prototype._initCache.call(this);
  19770. this._cache.localMatrixUpdated = false;
  19771. this._cache.position = BABYLON.Vector3.Zero();
  19772. this._cache.scaling = BABYLON.Vector3.Zero();
  19773. this._cache.rotation = BABYLON.Vector3.Zero();
  19774. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19775. this._cache.billboardMode = -1;
  19776. };
  19777. /**
  19778. * Flag the transform node as dirty (Forcing it to update everything)
  19779. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19780. * @returns this transform node
  19781. */
  19782. TransformNode.prototype.markAsDirty = function (property) {
  19783. if (property === "rotation") {
  19784. this.rotationQuaternion = null;
  19785. }
  19786. this._currentRenderId = Number.MAX_VALUE;
  19787. this._isDirty = true;
  19788. return this;
  19789. };
  19790. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19791. /**
  19792. * Returns the current mesh absolute position.
  19793. * Returns a Vector3.
  19794. */
  19795. get: function () {
  19796. return this._absolutePosition;
  19797. },
  19798. enumerable: true,
  19799. configurable: true
  19800. });
  19801. /**
  19802. * Sets a new matrix to apply before all other transformation
  19803. * @param matrix defines the transform matrix
  19804. * @returns the current TransformNode
  19805. */
  19806. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19807. return this.setPivotMatrix(matrix, false);
  19808. };
  19809. /**
  19810. * Sets a new pivot matrix to the current node
  19811. * @param matrix defines the new pivot matrix to use
  19812. * @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
  19813. * @returns the current TransformNode
  19814. */
  19815. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19816. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19817. this._pivotMatrix = matrix.clone();
  19818. this._cache.pivotMatrixUpdated = true;
  19819. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19820. if (this._postMultiplyPivotMatrix) {
  19821. if (!this._pivotMatrixInverse) {
  19822. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19823. }
  19824. else {
  19825. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19826. }
  19827. }
  19828. return this;
  19829. };
  19830. /**
  19831. * Returns the mesh pivot matrix.
  19832. * Default : Identity.
  19833. * @returns the matrix
  19834. */
  19835. TransformNode.prototype.getPivotMatrix = function () {
  19836. return this._pivotMatrix;
  19837. };
  19838. /**
  19839. * Prevents the World matrix to be computed any longer.
  19840. * @returns the TransformNode.
  19841. */
  19842. TransformNode.prototype.freezeWorldMatrix = function () {
  19843. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19844. this.computeWorldMatrix(true);
  19845. this._isWorldMatrixFrozen = true;
  19846. return this;
  19847. };
  19848. /**
  19849. * Allows back the World matrix computation.
  19850. * @returns the TransformNode.
  19851. */
  19852. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19853. this._isWorldMatrixFrozen = false;
  19854. this.computeWorldMatrix(true);
  19855. return this;
  19856. };
  19857. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19858. /**
  19859. * True if the World matrix has been frozen.
  19860. */
  19861. get: function () {
  19862. return this._isWorldMatrixFrozen;
  19863. },
  19864. enumerable: true,
  19865. configurable: true
  19866. });
  19867. /**
  19868. * Retuns the mesh absolute position in the World.
  19869. * @returns a Vector3.
  19870. */
  19871. TransformNode.prototype.getAbsolutePosition = function () {
  19872. this.computeWorldMatrix();
  19873. return this._absolutePosition;
  19874. };
  19875. /**
  19876. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19877. * @param absolutePosition the absolute position to set
  19878. * @returns the TransformNode.
  19879. */
  19880. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19881. if (!absolutePosition) {
  19882. return this;
  19883. }
  19884. var absolutePositionX;
  19885. var absolutePositionY;
  19886. var absolutePositionZ;
  19887. if (absolutePosition.x === undefined) {
  19888. if (arguments.length < 3) {
  19889. return this;
  19890. }
  19891. absolutePositionX = arguments[0];
  19892. absolutePositionY = arguments[1];
  19893. absolutePositionZ = arguments[2];
  19894. }
  19895. else {
  19896. absolutePositionX = absolutePosition.x;
  19897. absolutePositionY = absolutePosition.y;
  19898. absolutePositionZ = absolutePosition.z;
  19899. }
  19900. if (this.parent) {
  19901. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19902. invertParentWorldMatrix.invert();
  19903. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19904. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19905. }
  19906. else {
  19907. this.position.x = absolutePositionX;
  19908. this.position.y = absolutePositionY;
  19909. this.position.z = absolutePositionZ;
  19910. }
  19911. return this;
  19912. };
  19913. /**
  19914. * Sets the mesh position in its local space.
  19915. * @param vector3 the position to set in localspace
  19916. * @returns the TransformNode.
  19917. */
  19918. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19919. this.computeWorldMatrix();
  19920. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19921. return this;
  19922. };
  19923. /**
  19924. * Returns the mesh position in the local space from the current World matrix values.
  19925. * @returns a new Vector3.
  19926. */
  19927. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19928. this.computeWorldMatrix();
  19929. var invLocalWorldMatrix = this._localWorld.clone();
  19930. invLocalWorldMatrix.invert();
  19931. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19932. };
  19933. /**
  19934. * Translates the mesh along the passed Vector3 in its local space.
  19935. * @param vector3 the distance to translate in localspace
  19936. * @returns the TransformNode.
  19937. */
  19938. TransformNode.prototype.locallyTranslate = function (vector3) {
  19939. this.computeWorldMatrix(true);
  19940. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19941. return this;
  19942. };
  19943. /**
  19944. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19945. * @param targetPoint the position (must be in same space as current mesh) to look at
  19946. * @param yawCor optional yaw (y-axis) correction in radians
  19947. * @param pitchCor optional pitch (x-axis) correction in radians
  19948. * @param rollCor optional roll (z-axis) correction in radians
  19949. * @param space the choosen space of the target
  19950. * @returns the TransformNode.
  19951. */
  19952. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19953. if (yawCor === void 0) { yawCor = 0; }
  19954. if (pitchCor === void 0) { pitchCor = 0; }
  19955. if (rollCor === void 0) { rollCor = 0; }
  19956. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19957. var dv = TransformNode._lookAtVectorCache;
  19958. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19959. targetPoint.subtractToRef(pos, dv);
  19960. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19961. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19962. var pitch = Math.atan2(dv.y, len);
  19963. if (this.rotationQuaternion) {
  19964. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19965. }
  19966. else {
  19967. this.rotation.x = pitch + pitchCor;
  19968. this.rotation.y = yaw + yawCor;
  19969. this.rotation.z = rollCor;
  19970. }
  19971. return this;
  19972. };
  19973. /**
  19974. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19975. * This Vector3 is expressed in the World space.
  19976. * @param localAxis axis to rotate
  19977. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19978. */
  19979. TransformNode.prototype.getDirection = function (localAxis) {
  19980. var result = BABYLON.Vector3.Zero();
  19981. this.getDirectionToRef(localAxis, result);
  19982. return result;
  19983. };
  19984. /**
  19985. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19986. * localAxis is expressed in the mesh local space.
  19987. * result is computed in the Wordl space from the mesh World matrix.
  19988. * @param localAxis axis to rotate
  19989. * @param result the resulting transformnode
  19990. * @returns this TransformNode.
  19991. */
  19992. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19993. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19994. return this;
  19995. };
  19996. /**
  19997. * Sets a new pivot point to the current node
  19998. * @param point defines the new pivot point to use
  19999. * @param space defines if the point is in world or local space (local by default)
  20000. * @returns the current TransformNode
  20001. */
  20002. TransformNode.prototype.setPivotPoint = function (point, space) {
  20003. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20004. if (this.getScene().getRenderId() == 0) {
  20005. this.computeWorldMatrix(true);
  20006. }
  20007. var wm = this.getWorldMatrix();
  20008. if (space == BABYLON.Space.WORLD) {
  20009. var tmat = BABYLON.Tmp.Matrix[0];
  20010. wm.invertToRef(tmat);
  20011. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20012. }
  20013. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20014. };
  20015. /**
  20016. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20017. * @returns the pivot point
  20018. */
  20019. TransformNode.prototype.getPivotPoint = function () {
  20020. var point = BABYLON.Vector3.Zero();
  20021. this.getPivotPointToRef(point);
  20022. return point;
  20023. };
  20024. /**
  20025. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20026. * @param result the vector3 to store the result
  20027. * @returns this TransformNode.
  20028. */
  20029. TransformNode.prototype.getPivotPointToRef = function (result) {
  20030. result.x = -this._pivotMatrix.m[12];
  20031. result.y = -this._pivotMatrix.m[13];
  20032. result.z = -this._pivotMatrix.m[14];
  20033. return this;
  20034. };
  20035. /**
  20036. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20037. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20038. */
  20039. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20040. var point = BABYLON.Vector3.Zero();
  20041. this.getAbsolutePivotPointToRef(point);
  20042. return point;
  20043. };
  20044. /**
  20045. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20046. * @param result vector3 to store the result
  20047. * @returns this TransformNode.
  20048. */
  20049. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20050. result.x = this._pivotMatrix.m[12];
  20051. result.y = this._pivotMatrix.m[13];
  20052. result.z = this._pivotMatrix.m[14];
  20053. this.getPivotPointToRef(result);
  20054. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20055. return this;
  20056. };
  20057. /**
  20058. * Defines the passed node as the parent of the current node.
  20059. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20060. * @param node the node ot set as the parent
  20061. * @returns this TransformNode.
  20062. */
  20063. TransformNode.prototype.setParent = function (node) {
  20064. if (!node && !this.parent) {
  20065. return this;
  20066. }
  20067. if (!node) {
  20068. var rotation = BABYLON.Tmp.Quaternion[0];
  20069. var position = BABYLON.Tmp.Vector3[0];
  20070. var scale = BABYLON.Tmp.Vector3[1];
  20071. if (this.parent && this.parent.computeWorldMatrix) {
  20072. this.parent.computeWorldMatrix(true);
  20073. }
  20074. this.computeWorldMatrix(true);
  20075. this.getWorldMatrix().decompose(scale, rotation, position);
  20076. if (this.rotationQuaternion) {
  20077. this.rotationQuaternion.copyFrom(rotation);
  20078. }
  20079. else {
  20080. rotation.toEulerAnglesToRef(this.rotation);
  20081. }
  20082. this.scaling.x = scale.x;
  20083. this.scaling.y = scale.y;
  20084. this.scaling.z = scale.z;
  20085. this.position.x = position.x;
  20086. this.position.y = position.y;
  20087. this.position.z = position.z;
  20088. }
  20089. else {
  20090. var rotation = BABYLON.Tmp.Quaternion[0];
  20091. var position = BABYLON.Tmp.Vector3[0];
  20092. var scale = BABYLON.Tmp.Vector3[1];
  20093. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20094. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20095. this.computeWorldMatrix(true);
  20096. node.computeWorldMatrix(true);
  20097. node.getWorldMatrix().invertToRef(invParentMatrix);
  20098. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20099. diffMatrix.decompose(scale, rotation, position);
  20100. if (this.rotationQuaternion) {
  20101. this.rotationQuaternion.copyFrom(rotation);
  20102. }
  20103. else {
  20104. rotation.toEulerAnglesToRef(this.rotation);
  20105. }
  20106. this.position.x = position.x;
  20107. this.position.y = position.y;
  20108. this.position.z = position.z;
  20109. this.scaling.x = scale.x;
  20110. this.scaling.y = scale.y;
  20111. this.scaling.z = scale.z;
  20112. }
  20113. this.parent = node;
  20114. return this;
  20115. };
  20116. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20117. /**
  20118. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20119. */
  20120. get: function () {
  20121. return this._nonUniformScaling;
  20122. },
  20123. enumerable: true,
  20124. configurable: true
  20125. });
  20126. /** @hidden */
  20127. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20128. if (this._nonUniformScaling === value) {
  20129. return false;
  20130. }
  20131. this._nonUniformScaling = value;
  20132. return true;
  20133. };
  20134. /**
  20135. * Attach the current TransformNode to another TransformNode associated with a bone
  20136. * @param bone Bone affecting the TransformNode
  20137. * @param affectedTransformNode TransformNode associated with the bone
  20138. * @returns this object
  20139. */
  20140. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20141. this._transformToBoneReferal = affectedTransformNode;
  20142. this.parent = bone;
  20143. if (bone.getWorldMatrix().determinant() < 0) {
  20144. this.scalingDeterminant *= -1;
  20145. }
  20146. return this;
  20147. };
  20148. /**
  20149. * Detach the transform node if its associated with a bone
  20150. * @returns this object
  20151. */
  20152. TransformNode.prototype.detachFromBone = function () {
  20153. if (!this.parent) {
  20154. return this;
  20155. }
  20156. if (this.parent.getWorldMatrix().determinant() < 0) {
  20157. this.scalingDeterminant *= -1;
  20158. }
  20159. this._transformToBoneReferal = null;
  20160. this.parent = null;
  20161. return this;
  20162. };
  20163. /**
  20164. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20165. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20166. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20167. * The passed axis is also normalized.
  20168. * @param axis the axis to rotate around
  20169. * @param amount the amount to rotate in radians
  20170. * @param space Space to rotate in (Default: local)
  20171. * @returns the TransformNode.
  20172. */
  20173. TransformNode.prototype.rotate = function (axis, amount, space) {
  20174. axis.normalize();
  20175. if (!this.rotationQuaternion) {
  20176. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20177. this.rotation = BABYLON.Vector3.Zero();
  20178. }
  20179. var rotationQuaternion;
  20180. if (!space || space === BABYLON.Space.LOCAL) {
  20181. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20182. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20183. }
  20184. else {
  20185. if (this.parent) {
  20186. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20187. invertParentWorldMatrix.invert();
  20188. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20189. }
  20190. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20191. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20192. }
  20193. return this;
  20194. };
  20195. /**
  20196. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20197. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20198. * The passed axis is also normalized. .
  20199. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20200. * @param point the point to rotate around
  20201. * @param axis the axis to rotate around
  20202. * @param amount the amount to rotate in radians
  20203. * @returns the TransformNode
  20204. */
  20205. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20206. axis.normalize();
  20207. if (!this.rotationQuaternion) {
  20208. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20209. this.rotation.copyFromFloats(0, 0, 0);
  20210. }
  20211. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20212. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20213. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20214. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20215. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20216. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20217. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20218. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20219. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20220. return this;
  20221. };
  20222. /**
  20223. * Translates the mesh along the axis vector for the passed distance in the given space.
  20224. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20225. * @param axis the axis to translate in
  20226. * @param distance the distance to translate
  20227. * @param space Space to rotate in (Default: local)
  20228. * @returns the TransformNode.
  20229. */
  20230. TransformNode.prototype.translate = function (axis, distance, space) {
  20231. var displacementVector = axis.scale(distance);
  20232. if (!space || space === BABYLON.Space.LOCAL) {
  20233. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20234. this.setPositionWithLocalVector(tempV3);
  20235. }
  20236. else {
  20237. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20238. }
  20239. return this;
  20240. };
  20241. /**
  20242. * Adds a rotation step to the mesh current rotation.
  20243. * x, y, z are Euler angles expressed in radians.
  20244. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20245. * This means this rotation is made in the mesh local space only.
  20246. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20247. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20248. * ```javascript
  20249. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20250. * ```
  20251. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20252. * 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.
  20253. * @param x Rotation to add
  20254. * @param y Rotation to add
  20255. * @param z Rotation to add
  20256. * @returns the TransformNode.
  20257. */
  20258. TransformNode.prototype.addRotation = function (x, y, z) {
  20259. var rotationQuaternion;
  20260. if (this.rotationQuaternion) {
  20261. rotationQuaternion = this.rotationQuaternion;
  20262. }
  20263. else {
  20264. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20265. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20266. }
  20267. var accumulation = BABYLON.Tmp.Quaternion[0];
  20268. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20269. rotationQuaternion.multiplyInPlace(accumulation);
  20270. if (!this.rotationQuaternion) {
  20271. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20272. }
  20273. return this;
  20274. };
  20275. /**
  20276. * Computes the world matrix of the node
  20277. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20278. * @returns the world matrix
  20279. */
  20280. TransformNode.prototype.computeWorldMatrix = function (force) {
  20281. if (this._isWorldMatrixFrozen) {
  20282. return this._worldMatrix;
  20283. }
  20284. if (!force && this.isSynchronized()) {
  20285. this._currentRenderId = this.getScene().getRenderId();
  20286. return this._worldMatrix;
  20287. }
  20288. this._updateCache();
  20289. this._cache.position.copyFrom(this.position);
  20290. this._cache.scaling.copyFrom(this.scaling);
  20291. this._cache.pivotMatrixUpdated = false;
  20292. this._cache.billboardMode = this.billboardMode;
  20293. this._currentRenderId = this.getScene().getRenderId();
  20294. this._childRenderId = this.getScene().getRenderId();
  20295. this._isDirty = false;
  20296. // Scaling
  20297. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20298. // Rotation
  20299. //rotate, if quaternion is set and rotation was used
  20300. if (this.rotationQuaternion) {
  20301. var len = this.rotation.length();
  20302. if (len) {
  20303. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20304. this.rotation.copyFromFloats(0, 0, 0);
  20305. }
  20306. }
  20307. if (this.rotationQuaternion) {
  20308. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20309. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20310. }
  20311. else {
  20312. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20313. this._cache.rotation.copyFrom(this.rotation);
  20314. }
  20315. // Translation
  20316. var camera = this.getScene().activeCamera;
  20317. if (this.infiniteDistance && !this.parent && camera) {
  20318. var cameraWorldMatrix = camera.getWorldMatrix();
  20319. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20320. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20321. }
  20322. else {
  20323. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20324. }
  20325. // Composing transformations
  20326. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20327. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20328. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20329. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20330. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20331. // Need to decompose each rotation here
  20332. var currentPosition = BABYLON.Tmp.Vector3[3];
  20333. if (this.parent && this.parent.getWorldMatrix) {
  20334. if (this._transformToBoneReferal) {
  20335. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20336. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20337. }
  20338. else {
  20339. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20340. }
  20341. }
  20342. else {
  20343. currentPosition.copyFrom(this.position);
  20344. }
  20345. currentPosition.subtractInPlace(camera.globalPosition);
  20346. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20347. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20348. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20349. }
  20350. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20351. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20352. }
  20353. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20354. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20355. }
  20356. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20357. }
  20358. else {
  20359. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20360. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20361. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20362. }
  20363. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20364. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20365. }
  20366. // Post multiply inverse of pivotMatrix
  20367. if (this._postMultiplyPivotMatrix) {
  20368. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20369. }
  20370. // Local world
  20371. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20372. // Parent
  20373. if (this.parent && this.parent.getWorldMatrix) {
  20374. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20375. if (this._transformToBoneReferal) {
  20376. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20377. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20378. }
  20379. else {
  20380. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20381. }
  20382. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20383. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20384. this._worldMatrix.copyFrom(this._localWorld);
  20385. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20386. }
  20387. else {
  20388. if (this._transformToBoneReferal) {
  20389. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20390. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20391. }
  20392. else {
  20393. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20394. }
  20395. }
  20396. this._markSyncedWithParent();
  20397. }
  20398. else {
  20399. this._worldMatrix.copyFrom(this._localWorld);
  20400. }
  20401. // Normal matrix
  20402. if (!this.ignoreNonUniformScaling) {
  20403. if (this.scaling.isNonUniform) {
  20404. this._updateNonUniformScalingState(true);
  20405. }
  20406. else if (this.parent && this.parent._nonUniformScaling) {
  20407. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20408. }
  20409. else {
  20410. this._updateNonUniformScalingState(false);
  20411. }
  20412. }
  20413. else {
  20414. this._updateNonUniformScalingState(false);
  20415. }
  20416. this._afterComputeWorldMatrix();
  20417. // Absolute position
  20418. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20419. // Callbacks
  20420. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20421. if (!this._poseMatrix) {
  20422. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20423. }
  20424. // Cache the determinant
  20425. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20426. return this._worldMatrix;
  20427. };
  20428. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20429. };
  20430. /**
  20431. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20432. * @param func callback function to add
  20433. *
  20434. * @returns the TransformNode.
  20435. */
  20436. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20437. this.onAfterWorldMatrixUpdateObservable.add(func);
  20438. return this;
  20439. };
  20440. /**
  20441. * Removes a registered callback function.
  20442. * @param func callback function to remove
  20443. * @returns the TransformNode.
  20444. */
  20445. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20446. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20447. return this;
  20448. };
  20449. /**
  20450. * Clone the current transform node
  20451. * @param name Name of the new clone
  20452. * @param newParent New parent for the clone
  20453. * @param doNotCloneChildren Do not clone children hierarchy
  20454. * @returns the new transform node
  20455. */
  20456. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20457. var _this = this;
  20458. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20459. result.name = name;
  20460. result.id = name;
  20461. if (newParent) {
  20462. result.parent = newParent;
  20463. }
  20464. if (!doNotCloneChildren) {
  20465. // Children
  20466. var directDescendants = this.getDescendants(true);
  20467. for (var index = 0; index < directDescendants.length; index++) {
  20468. var child = directDescendants[index];
  20469. if (child.clone) {
  20470. child.clone(name + "." + child.name, result);
  20471. }
  20472. }
  20473. }
  20474. return result;
  20475. };
  20476. /**
  20477. * Serializes the objects information.
  20478. * @param currentSerializationObject defines the object to serialize in
  20479. * @returns the serialized object
  20480. */
  20481. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20482. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20483. serializationObject.type = this.getClassName();
  20484. // Parent
  20485. if (this.parent) {
  20486. serializationObject.parentId = this.parent.id;
  20487. }
  20488. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20489. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20490. }
  20491. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20492. serializationObject.isEnabled = this.isEnabled();
  20493. // Parent
  20494. if (this.parent) {
  20495. serializationObject.parentId = this.parent.id;
  20496. }
  20497. return serializationObject;
  20498. };
  20499. // Statics
  20500. /**
  20501. * Returns a new TransformNode object parsed from the source provided.
  20502. * @param parsedTransformNode is the source.
  20503. * @param scene the scne the object belongs to
  20504. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20505. * @returns a new TransformNode object parsed from the source provided.
  20506. */
  20507. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20508. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20509. if (BABYLON.Tags) {
  20510. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20511. }
  20512. if (parsedTransformNode.localMatrix) {
  20513. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20514. }
  20515. else if (parsedTransformNode.pivotMatrix) {
  20516. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20517. }
  20518. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20519. // Parent
  20520. if (parsedTransformNode.parentId) {
  20521. transformNode._waitingParentId = parsedTransformNode.parentId;
  20522. }
  20523. return transformNode;
  20524. };
  20525. /**
  20526. * Releases resources associated with this transform node.
  20527. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20528. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20529. */
  20530. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20531. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20532. // Animations
  20533. this.getScene().stopAnimation(this);
  20534. // Remove from scene
  20535. this.getScene().removeTransformNode(this);
  20536. this.onAfterWorldMatrixUpdateObservable.clear();
  20537. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20538. };
  20539. // Statics
  20540. /**
  20541. * Object will not rotate to face the camera
  20542. */
  20543. TransformNode.BILLBOARDMODE_NONE = 0;
  20544. /**
  20545. * Object will rotate to face the camera but only on the x axis
  20546. */
  20547. TransformNode.BILLBOARDMODE_X = 1;
  20548. /**
  20549. * Object will rotate to face the camera but only on the y axis
  20550. */
  20551. TransformNode.BILLBOARDMODE_Y = 2;
  20552. /**
  20553. * Object will rotate to face the camera but only on the z axis
  20554. */
  20555. TransformNode.BILLBOARDMODE_Z = 4;
  20556. /**
  20557. * Object will rotate to face the camera
  20558. */
  20559. TransformNode.BILLBOARDMODE_ALL = 7;
  20560. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20561. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20562. __decorate([
  20563. BABYLON.serializeAsVector3("position")
  20564. ], TransformNode.prototype, "_position", void 0);
  20565. __decorate([
  20566. BABYLON.serializeAsVector3("rotation")
  20567. ], TransformNode.prototype, "_rotation", void 0);
  20568. __decorate([
  20569. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20570. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20571. __decorate([
  20572. BABYLON.serializeAsVector3("scaling")
  20573. ], TransformNode.prototype, "_scaling", void 0);
  20574. __decorate([
  20575. BABYLON.serialize()
  20576. ], TransformNode.prototype, "billboardMode", void 0);
  20577. __decorate([
  20578. BABYLON.serialize()
  20579. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20580. __decorate([
  20581. BABYLON.serialize()
  20582. ], TransformNode.prototype, "infiniteDistance", void 0);
  20583. __decorate([
  20584. BABYLON.serialize()
  20585. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20586. return TransformNode;
  20587. }(BABYLON.Node));
  20588. BABYLON.TransformNode = TransformNode;
  20589. })(BABYLON || (BABYLON = {}));
  20590. //# sourceMappingURL=babylon.transformNode.js.map
  20591. var BABYLON;
  20592. (function (BABYLON) {
  20593. /** @hidden */
  20594. var _FacetDataStorage = /** @class */ (function () {
  20595. function _FacetDataStorage() {
  20596. this.facetNb = 0; // facet number
  20597. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20598. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20599. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20600. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20601. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20602. this.subDiv = {
  20603. max: 1,
  20604. X: 1,
  20605. Y: 1,
  20606. Z: 1
  20607. };
  20608. this.facetDepthSort = false; // is the facet depth sort to be computed
  20609. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20610. }
  20611. return _FacetDataStorage;
  20612. }());
  20613. /**
  20614. * Class used to store all common mesh properties
  20615. */
  20616. var AbstractMesh = /** @class */ (function (_super) {
  20617. __extends(AbstractMesh, _super);
  20618. // Constructor
  20619. /**
  20620. * Creates a new AbstractMesh
  20621. * @param name defines the name of the mesh
  20622. * @param scene defines the hosting scene
  20623. */
  20624. function AbstractMesh(name, scene) {
  20625. if (scene === void 0) { scene = null; }
  20626. var _this = _super.call(this, name, scene, false) || this;
  20627. _this._facetData = new _FacetDataStorage();
  20628. /** Gets ot sets the culling strategy to use to find visible meshes */
  20629. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20630. // Events
  20631. /**
  20632. * An event triggered when this mesh collides with another one
  20633. */
  20634. _this.onCollideObservable = new BABYLON.Observable();
  20635. /**
  20636. * An event triggered when the collision's position changes
  20637. */
  20638. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20639. /**
  20640. * An event triggered when material is changed
  20641. */
  20642. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20643. // Properties
  20644. /**
  20645. * Gets or sets the orientation for POV movement & rotation
  20646. */
  20647. _this.definedFacingForward = true;
  20648. _this._visibility = 1.0;
  20649. /** Gets or sets the alpha index used to sort transparent meshes
  20650. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20651. */
  20652. _this.alphaIndex = Number.MAX_VALUE;
  20653. /**
  20654. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20655. */
  20656. _this.isVisible = true;
  20657. /**
  20658. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20659. */
  20660. _this.isPickable = true;
  20661. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20662. _this.showSubMeshesBoundingBox = false;
  20663. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20664. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20665. */
  20666. _this.isBlocker = false;
  20667. /**
  20668. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20669. */
  20670. _this.enablePointerMoveEvents = false;
  20671. /**
  20672. * Specifies the rendering group id for this mesh (0 by default)
  20673. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20674. */
  20675. _this.renderingGroupId = 0;
  20676. _this._receiveShadows = false;
  20677. /** Defines color to use when rendering outline */
  20678. _this.outlineColor = BABYLON.Color3.Red();
  20679. /** Define width to use when rendering outline */
  20680. _this.outlineWidth = 0.02;
  20681. /** Defines color to use when rendering overlay */
  20682. _this.overlayColor = BABYLON.Color3.Red();
  20683. /** Defines alpha to use when rendering overlay */
  20684. _this.overlayAlpha = 0.5;
  20685. _this._hasVertexAlpha = false;
  20686. _this._useVertexColors = true;
  20687. _this._computeBonesUsingShaders = true;
  20688. _this._numBoneInfluencers = 4;
  20689. _this._applyFog = true;
  20690. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20691. _this.useOctreeForRenderingSelection = true;
  20692. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20693. _this.useOctreeForPicking = true;
  20694. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20695. _this.useOctreeForCollisions = true;
  20696. _this._layerMask = 0x0FFFFFFF;
  20697. /**
  20698. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20699. */
  20700. _this.alwaysSelectAsActiveMesh = false;
  20701. /**
  20702. * Gets or sets the current action manager
  20703. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20704. */
  20705. _this.actionManager = null;
  20706. // Collisions
  20707. _this._checkCollisions = false;
  20708. _this._collisionMask = -1;
  20709. _this._collisionGroup = -1;
  20710. /**
  20711. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20712. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20713. */
  20714. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20715. /**
  20716. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20717. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20718. */
  20719. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20720. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20721. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20722. // Edges
  20723. /**
  20724. * Defines edge width used when edgesRenderer is enabled
  20725. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20726. */
  20727. _this.edgesWidth = 1;
  20728. /**
  20729. * Defines edge color used when edgesRenderer is enabled
  20730. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20731. */
  20732. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20733. /** @hidden */
  20734. _this._renderId = 0;
  20735. /** @hidden */
  20736. _this._intersectionsInProgress = new Array();
  20737. /** @hidden */
  20738. _this._unIndexed = false;
  20739. /** @hidden */
  20740. _this._lightSources = new Array();
  20741. /**
  20742. * An event triggered when the mesh is rebuilt.
  20743. */
  20744. _this.onRebuildObservable = new BABYLON.Observable();
  20745. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20746. if (collidedMesh === void 0) { collidedMesh = null; }
  20747. //TODO move this to the collision coordinator!
  20748. if (_this.getScene().workerCollisions)
  20749. newPosition.multiplyInPlace(_this._collider._radius);
  20750. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20751. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20752. _this.position.addInPlace(_this._diffPositionForCollisions);
  20753. }
  20754. if (collidedMesh) {
  20755. _this.onCollideObservable.notifyObservers(collidedMesh);
  20756. }
  20757. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20758. };
  20759. _this.getScene().addMesh(_this);
  20760. _this._resyncLightSources();
  20761. return _this;
  20762. }
  20763. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20764. /**
  20765. * No billboard
  20766. */
  20767. get: function () {
  20768. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20769. },
  20770. enumerable: true,
  20771. configurable: true
  20772. });
  20773. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20774. /** Billboard on X axis */
  20775. get: function () {
  20776. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20777. },
  20778. enumerable: true,
  20779. configurable: true
  20780. });
  20781. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20782. /** Billboard on Y axis */
  20783. get: function () {
  20784. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20785. },
  20786. enumerable: true,
  20787. configurable: true
  20788. });
  20789. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20790. /** Billboard on Z axis */
  20791. get: function () {
  20792. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20793. },
  20794. enumerable: true,
  20795. configurable: true
  20796. });
  20797. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20798. /** Billboard on all axes */
  20799. get: function () {
  20800. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20801. },
  20802. enumerable: true,
  20803. configurable: true
  20804. });
  20805. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20806. /**
  20807. * Gets the number of facets in the mesh
  20808. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20809. */
  20810. get: function () {
  20811. return this._facetData.facetNb;
  20812. },
  20813. enumerable: true,
  20814. configurable: true
  20815. });
  20816. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20817. /**
  20818. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20819. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20820. */
  20821. get: function () {
  20822. return this._facetData.partitioningSubdivisions;
  20823. },
  20824. set: function (nb) {
  20825. this._facetData.partitioningSubdivisions = nb;
  20826. },
  20827. enumerable: true,
  20828. configurable: true
  20829. });
  20830. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20831. /**
  20832. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20833. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20834. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20835. */
  20836. get: function () {
  20837. return this._facetData.partitioningBBoxRatio;
  20838. },
  20839. set: function (ratio) {
  20840. this._facetData.partitioningBBoxRatio = ratio;
  20841. },
  20842. enumerable: true,
  20843. configurable: true
  20844. });
  20845. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20846. /**
  20847. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20848. * Works only for updatable meshes.
  20849. * Doesn't work with multi-materials
  20850. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20851. */
  20852. get: function () {
  20853. return this._facetData.facetDepthSort;
  20854. },
  20855. set: function (sort) {
  20856. this._facetData.facetDepthSort = sort;
  20857. },
  20858. enumerable: true,
  20859. configurable: true
  20860. });
  20861. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20862. /**
  20863. * The location (Vector3) where the facet depth sort must be computed from.
  20864. * By default, the active camera position.
  20865. * Used only when facet depth sort is enabled
  20866. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20867. */
  20868. get: function () {
  20869. return this._facetData.facetDepthSortFrom;
  20870. },
  20871. set: function (location) {
  20872. this._facetData.facetDepthSortFrom = location;
  20873. },
  20874. enumerable: true,
  20875. configurable: true
  20876. });
  20877. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20878. /**
  20879. * gets a boolean indicating if facetData is enabled
  20880. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20881. */
  20882. get: function () {
  20883. return this._facetData.facetDataEnabled;
  20884. },
  20885. enumerable: true,
  20886. configurable: true
  20887. });
  20888. /** @hidden */
  20889. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20890. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20891. return false;
  20892. }
  20893. this._markSubMeshesAsMiscDirty();
  20894. return true;
  20895. };
  20896. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20897. /** Set a function to call when this mesh collides with another one */
  20898. set: function (callback) {
  20899. if (this._onCollideObserver) {
  20900. this.onCollideObservable.remove(this._onCollideObserver);
  20901. }
  20902. this._onCollideObserver = this.onCollideObservable.add(callback);
  20903. },
  20904. enumerable: true,
  20905. configurable: true
  20906. });
  20907. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20908. /** Set a function to call when the collision's position changes */
  20909. set: function (callback) {
  20910. if (this._onCollisionPositionChangeObserver) {
  20911. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20912. }
  20913. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20914. },
  20915. enumerable: true,
  20916. configurable: true
  20917. });
  20918. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20919. /**
  20920. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20921. */
  20922. get: function () {
  20923. return this._visibility;
  20924. },
  20925. /**
  20926. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20927. */
  20928. set: function (value) {
  20929. if (this._visibility === value) {
  20930. return;
  20931. }
  20932. this._visibility = value;
  20933. this._markSubMeshesAsMiscDirty();
  20934. },
  20935. enumerable: true,
  20936. configurable: true
  20937. });
  20938. Object.defineProperty(AbstractMesh.prototype, "material", {
  20939. /** Gets or sets current material */
  20940. get: function () {
  20941. return this._material;
  20942. },
  20943. set: function (value) {
  20944. if (this._material === value) {
  20945. return;
  20946. }
  20947. this._material = value;
  20948. if (this.onMaterialChangedObservable.hasObservers) {
  20949. this.onMaterialChangedObservable.notifyObservers(this);
  20950. }
  20951. if (!this.subMeshes) {
  20952. return;
  20953. }
  20954. this._unBindEffect();
  20955. },
  20956. enumerable: true,
  20957. configurable: true
  20958. });
  20959. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20960. /**
  20961. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20962. * @see http://doc.babylonjs.com/babylon101/shadows
  20963. */
  20964. get: function () {
  20965. return this._receiveShadows;
  20966. },
  20967. set: function (value) {
  20968. if (this._receiveShadows === value) {
  20969. return;
  20970. }
  20971. this._receiveShadows = value;
  20972. this._markSubMeshesAsLightDirty();
  20973. },
  20974. enumerable: true,
  20975. configurable: true
  20976. });
  20977. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20978. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20979. get: function () {
  20980. return this._hasVertexAlpha;
  20981. },
  20982. set: function (value) {
  20983. if (this._hasVertexAlpha === value) {
  20984. return;
  20985. }
  20986. this._hasVertexAlpha = value;
  20987. this._markSubMeshesAsAttributesDirty();
  20988. this._markSubMeshesAsMiscDirty();
  20989. },
  20990. enumerable: true,
  20991. configurable: true
  20992. });
  20993. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20994. /** 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) */
  20995. get: function () {
  20996. return this._useVertexColors;
  20997. },
  20998. set: function (value) {
  20999. if (this._useVertexColors === value) {
  21000. return;
  21001. }
  21002. this._useVertexColors = value;
  21003. this._markSubMeshesAsAttributesDirty();
  21004. },
  21005. enumerable: true,
  21006. configurable: true
  21007. });
  21008. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21009. /**
  21010. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21011. */
  21012. get: function () {
  21013. return this._computeBonesUsingShaders;
  21014. },
  21015. set: function (value) {
  21016. if (this._computeBonesUsingShaders === value) {
  21017. return;
  21018. }
  21019. this._computeBonesUsingShaders = value;
  21020. this._markSubMeshesAsAttributesDirty();
  21021. },
  21022. enumerable: true,
  21023. configurable: true
  21024. });
  21025. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21026. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21027. get: function () {
  21028. return this._numBoneInfluencers;
  21029. },
  21030. set: function (value) {
  21031. if (this._numBoneInfluencers === value) {
  21032. return;
  21033. }
  21034. this._numBoneInfluencers = value;
  21035. this._markSubMeshesAsAttributesDirty();
  21036. },
  21037. enumerable: true,
  21038. configurable: true
  21039. });
  21040. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21041. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21042. get: function () {
  21043. return this._applyFog;
  21044. },
  21045. set: function (value) {
  21046. if (this._applyFog === value) {
  21047. return;
  21048. }
  21049. this._applyFog = value;
  21050. this._markSubMeshesAsMiscDirty();
  21051. },
  21052. enumerable: true,
  21053. configurable: true
  21054. });
  21055. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21056. /**
  21057. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21058. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21059. */
  21060. get: function () {
  21061. return this._layerMask;
  21062. },
  21063. set: function (value) {
  21064. if (value === this._layerMask) {
  21065. return;
  21066. }
  21067. this._layerMask = value;
  21068. this._resyncLightSources();
  21069. },
  21070. enumerable: true,
  21071. configurable: true
  21072. });
  21073. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21074. /**
  21075. * Gets or sets a collision mask used to mask collisions (default is -1).
  21076. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21077. */
  21078. get: function () {
  21079. return this._collisionMask;
  21080. },
  21081. set: function (mask) {
  21082. this._collisionMask = !isNaN(mask) ? mask : -1;
  21083. },
  21084. enumerable: true,
  21085. configurable: true
  21086. });
  21087. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21088. /**
  21089. * Gets or sets the current collision group mask (-1 by default).
  21090. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21091. */
  21092. get: function () {
  21093. return this._collisionGroup;
  21094. },
  21095. set: function (mask) {
  21096. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21097. },
  21098. enumerable: true,
  21099. configurable: true
  21100. });
  21101. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21102. /** @hidden */
  21103. get: function () {
  21104. return null;
  21105. },
  21106. enumerable: true,
  21107. configurable: true
  21108. });
  21109. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21110. get: function () {
  21111. return this._skeleton;
  21112. },
  21113. /**
  21114. * Gets or sets a skeleton to apply skining transformations
  21115. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21116. */
  21117. set: function (value) {
  21118. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21119. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21120. }
  21121. if (value && value.needInitialSkinMatrix) {
  21122. value._registerMeshWithPoseMatrix(this);
  21123. }
  21124. this._skeleton = value;
  21125. if (!this._skeleton) {
  21126. this._bonesTransformMatrices = null;
  21127. }
  21128. this._markSubMeshesAsAttributesDirty();
  21129. },
  21130. enumerable: true,
  21131. configurable: true
  21132. });
  21133. /**
  21134. * Returns the string "AbstractMesh"
  21135. * @returns "AbstractMesh"
  21136. */
  21137. AbstractMesh.prototype.getClassName = function () {
  21138. return "AbstractMesh";
  21139. };
  21140. /**
  21141. * Gets a string representation of the current mesh
  21142. * @param fullDetails defines a boolean indicating if full details must be included
  21143. * @returns a string representation of the current mesh
  21144. */
  21145. AbstractMesh.prototype.toString = function (fullDetails) {
  21146. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21147. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21148. if (this._skeleton) {
  21149. ret += ", skeleton: " + this._skeleton.name;
  21150. }
  21151. if (fullDetails) {
  21152. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21153. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21154. }
  21155. return ret;
  21156. };
  21157. /** @hidden */
  21158. AbstractMesh.prototype._rebuild = function () {
  21159. this.onRebuildObservable.notifyObservers(this);
  21160. if (this._occlusionQuery) {
  21161. this._occlusionQuery = null;
  21162. }
  21163. if (!this.subMeshes) {
  21164. return;
  21165. }
  21166. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21167. var subMesh = _a[_i];
  21168. subMesh._rebuild();
  21169. }
  21170. };
  21171. /** @hidden */
  21172. AbstractMesh.prototype._resyncLightSources = function () {
  21173. this._lightSources.length = 0;
  21174. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21175. var light = _a[_i];
  21176. if (!light.isEnabled()) {
  21177. continue;
  21178. }
  21179. if (light.canAffectMesh(this)) {
  21180. this._lightSources.push(light);
  21181. }
  21182. }
  21183. this._markSubMeshesAsLightDirty();
  21184. };
  21185. /** @hidden */
  21186. AbstractMesh.prototype._resyncLighSource = function (light) {
  21187. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21188. var index = this._lightSources.indexOf(light);
  21189. if (index === -1) {
  21190. if (!isIn) {
  21191. return;
  21192. }
  21193. this._lightSources.push(light);
  21194. }
  21195. else {
  21196. if (isIn) {
  21197. return;
  21198. }
  21199. this._lightSources.splice(index, 1);
  21200. }
  21201. this._markSubMeshesAsLightDirty();
  21202. };
  21203. /** @hidden */
  21204. AbstractMesh.prototype._unBindEffect = function () {
  21205. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21206. var subMesh = _a[_i];
  21207. subMesh.setEffect(null);
  21208. }
  21209. };
  21210. /** @hidden */
  21211. AbstractMesh.prototype._removeLightSource = function (light) {
  21212. var index = this._lightSources.indexOf(light);
  21213. if (index === -1) {
  21214. return;
  21215. }
  21216. this._lightSources.splice(index, 1);
  21217. this._markSubMeshesAsLightDirty();
  21218. };
  21219. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21220. if (!this.subMeshes) {
  21221. return;
  21222. }
  21223. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21224. var subMesh = _a[_i];
  21225. if (subMesh._materialDefines) {
  21226. func(subMesh._materialDefines);
  21227. }
  21228. }
  21229. };
  21230. /** @hidden */
  21231. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21232. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21233. };
  21234. /** @hidden */
  21235. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21236. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21237. };
  21238. /** @hidden */
  21239. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21240. if (!this.subMeshes) {
  21241. return;
  21242. }
  21243. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21244. var subMesh = _a[_i];
  21245. var material = subMesh.getMaterial();
  21246. if (material) {
  21247. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21248. }
  21249. }
  21250. };
  21251. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21252. /**
  21253. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21254. */
  21255. get: function () {
  21256. return this._scaling;
  21257. },
  21258. set: function (newScaling) {
  21259. this._scaling = newScaling;
  21260. if (this.physicsImpostor) {
  21261. this.physicsImpostor.forceUpdate();
  21262. }
  21263. },
  21264. enumerable: true,
  21265. configurable: true
  21266. });
  21267. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21268. // Methods
  21269. /**
  21270. * Returns true if the mesh is blocked. Implemented by child classes
  21271. */
  21272. get: function () {
  21273. return false;
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. /**
  21279. * Returns the mesh itself by default. Implemented by child classes
  21280. * @param camera defines the camera to use to pick the right LOD level
  21281. * @returns the currentAbstractMesh
  21282. */
  21283. AbstractMesh.prototype.getLOD = function (camera) {
  21284. return this;
  21285. };
  21286. /**
  21287. * Returns 0 by default. Implemented by child classes
  21288. * @returns an integer
  21289. */
  21290. AbstractMesh.prototype.getTotalVertices = function () {
  21291. return 0;
  21292. };
  21293. /**
  21294. * Returns null by default. Implemented by child classes
  21295. * @returns null
  21296. */
  21297. AbstractMesh.prototype.getIndices = function () {
  21298. return null;
  21299. };
  21300. /**
  21301. * Returns the array of the requested vertex data kind. Implemented by child classes
  21302. * @param kind defines the vertex data kind to use
  21303. * @returns null
  21304. */
  21305. AbstractMesh.prototype.getVerticesData = function (kind) {
  21306. return null;
  21307. };
  21308. /**
  21309. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21310. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21311. * Note that a new underlying VertexBuffer object is created each call.
  21312. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21313. * @param kind defines vertex data kind:
  21314. * * BABYLON.VertexBuffer.PositionKind
  21315. * * BABYLON.VertexBuffer.UVKind
  21316. * * BABYLON.VertexBuffer.UV2Kind
  21317. * * BABYLON.VertexBuffer.UV3Kind
  21318. * * BABYLON.VertexBuffer.UV4Kind
  21319. * * BABYLON.VertexBuffer.UV5Kind
  21320. * * BABYLON.VertexBuffer.UV6Kind
  21321. * * BABYLON.VertexBuffer.ColorKind
  21322. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21323. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21324. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21325. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21326. * @param data defines the data source
  21327. * @param updatable defines if the data must be flagged as updatable (or static)
  21328. * @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
  21329. * @returns the current mesh
  21330. */
  21331. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21332. return this;
  21333. };
  21334. /**
  21335. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21336. * If the mesh has no geometry, it is simply returned as it is.
  21337. * @param kind defines vertex data kind:
  21338. * * BABYLON.VertexBuffer.PositionKind
  21339. * * BABYLON.VertexBuffer.UVKind
  21340. * * BABYLON.VertexBuffer.UV2Kind
  21341. * * BABYLON.VertexBuffer.UV3Kind
  21342. * * BABYLON.VertexBuffer.UV4Kind
  21343. * * BABYLON.VertexBuffer.UV5Kind
  21344. * * BABYLON.VertexBuffer.UV6Kind
  21345. * * BABYLON.VertexBuffer.ColorKind
  21346. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21347. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21348. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21349. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21350. * @param data defines the data source
  21351. * @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
  21352. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21353. * @returns the current mesh
  21354. */
  21355. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21356. return this;
  21357. };
  21358. /**
  21359. * Sets the mesh indices,
  21360. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21361. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21362. * @param totalVertices Defines the total number of vertices
  21363. * @returns the current mesh
  21364. */
  21365. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21366. return this;
  21367. };
  21368. /**
  21369. * Gets a boolean indicating if specific vertex data is present
  21370. * @param kind defines the vertex data kind to use
  21371. * @returns true is data kind is present
  21372. */
  21373. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21374. return false;
  21375. };
  21376. /**
  21377. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21378. * @returns a BoundingInfo
  21379. */
  21380. AbstractMesh.prototype.getBoundingInfo = function () {
  21381. if (this._masterMesh) {
  21382. return this._masterMesh.getBoundingInfo();
  21383. }
  21384. if (!this._boundingInfo) {
  21385. // this._boundingInfo is being created here
  21386. this._updateBoundingInfo();
  21387. }
  21388. // cannot be null.
  21389. return this._boundingInfo;
  21390. };
  21391. /**
  21392. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21393. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21394. * @returns the current mesh
  21395. */
  21396. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21397. if (includeDescendants === void 0) { includeDescendants = true; }
  21398. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21399. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21400. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21401. if (maxDimension === 0) {
  21402. return this;
  21403. }
  21404. var scale = 1 / maxDimension;
  21405. this.scaling.scaleInPlace(scale);
  21406. return this;
  21407. };
  21408. /**
  21409. * Overwrite the current bounding info
  21410. * @param boundingInfo defines the new bounding info
  21411. * @returns the current mesh
  21412. */
  21413. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21414. this._boundingInfo = boundingInfo;
  21415. return this;
  21416. };
  21417. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21418. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21419. get: function () {
  21420. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21421. },
  21422. enumerable: true,
  21423. configurable: true
  21424. });
  21425. /** @hidden */
  21426. AbstractMesh.prototype._preActivate = function () {
  21427. };
  21428. /** @hidden */
  21429. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21430. };
  21431. /** @hidden */
  21432. AbstractMesh.prototype._activate = function (renderId) {
  21433. this._renderId = renderId;
  21434. };
  21435. /**
  21436. * Gets the current world matrix
  21437. * @returns a Matrix
  21438. */
  21439. AbstractMesh.prototype.getWorldMatrix = function () {
  21440. if (this._masterMesh) {
  21441. return this._masterMesh.getWorldMatrix();
  21442. }
  21443. return _super.prototype.getWorldMatrix.call(this);
  21444. };
  21445. /** @hidden */
  21446. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21447. if (this._masterMesh) {
  21448. return this._masterMesh._getWorldMatrixDeterminant();
  21449. }
  21450. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21451. };
  21452. // ================================== Point of View Movement =================================
  21453. /**
  21454. * Perform relative position change from the point of view of behind the front of the mesh.
  21455. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21456. * Supports definition of mesh facing forward or backward
  21457. * @param amountRight defines the distance on the right axis
  21458. * @param amountUp defines the distance on the up axis
  21459. * @param amountForward defines the distance on the forward axis
  21460. * @returns the current mesh
  21461. */
  21462. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21463. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21464. return this;
  21465. };
  21466. /**
  21467. * Calculate relative position change from the point of view of behind the front of the mesh.
  21468. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21469. * Supports definition of mesh facing forward or backward
  21470. * @param amountRight defines the distance on the right axis
  21471. * @param amountUp defines the distance on the up axis
  21472. * @param amountForward defines the distance on the forward axis
  21473. * @returns the new displacement vector
  21474. */
  21475. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21476. var rotMatrix = new BABYLON.Matrix();
  21477. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21478. rotQuaternion.toRotationMatrix(rotMatrix);
  21479. var translationDelta = BABYLON.Vector3.Zero();
  21480. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21481. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21482. return translationDelta;
  21483. };
  21484. // ================================== Point of View Rotation =================================
  21485. /**
  21486. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21487. * Supports definition of mesh facing forward or backward
  21488. * @param flipBack defines the flip
  21489. * @param twirlClockwise defines the twirl
  21490. * @param tiltRight defines the tilt
  21491. * @returns the current mesh
  21492. */
  21493. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21494. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21495. return this;
  21496. };
  21497. /**
  21498. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21499. * Supports definition of mesh facing forward or backward.
  21500. * @param flipBack defines the flip
  21501. * @param twirlClockwise defines the twirl
  21502. * @param tiltRight defines the tilt
  21503. * @returns the new rotation vector
  21504. */
  21505. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21506. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21507. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21508. };
  21509. /**
  21510. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21511. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21512. * @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
  21513. * @returns the new bounding vectors
  21514. */
  21515. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21516. if (includeDescendants === void 0) { includeDescendants = true; }
  21517. if (predicate === void 0) { predicate = null; }
  21518. // Ensures that all world matrix will be recomputed.
  21519. this.getScene().incrementRenderId();
  21520. this.computeWorldMatrix(true);
  21521. var min;
  21522. var max;
  21523. var boundingInfo = this.getBoundingInfo();
  21524. if (!this.subMeshes) {
  21525. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21526. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21527. }
  21528. else {
  21529. min = boundingInfo.boundingBox.minimumWorld;
  21530. max = boundingInfo.boundingBox.maximumWorld;
  21531. }
  21532. if (includeDescendants) {
  21533. var descendants = this.getDescendants(false);
  21534. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21535. var descendant = descendants_1[_i];
  21536. var childMesh = descendant;
  21537. childMesh.computeWorldMatrix(true);
  21538. // Filters meshes based on custom predicate function.
  21539. if (predicate && !predicate(childMesh)) {
  21540. continue;
  21541. }
  21542. //make sure we have the needed params to get mix and max
  21543. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21544. continue;
  21545. }
  21546. var childBoundingInfo = childMesh.getBoundingInfo();
  21547. var boundingBox = childBoundingInfo.boundingBox;
  21548. var minBox = boundingBox.minimumWorld;
  21549. var maxBox = boundingBox.maximumWorld;
  21550. BABYLON.Tools.CheckExtends(minBox, min, max);
  21551. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21552. }
  21553. }
  21554. return {
  21555. min: min,
  21556. max: max
  21557. };
  21558. };
  21559. /** @hidden */
  21560. AbstractMesh.prototype._updateBoundingInfo = function () {
  21561. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21562. this._boundingInfo.update(this.worldMatrixFromCache);
  21563. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21564. return this;
  21565. };
  21566. /** @hidden */
  21567. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21568. if (!this.subMeshes) {
  21569. return this;
  21570. }
  21571. var count = this.subMeshes.length;
  21572. for (var subIndex = 0; subIndex < count; subIndex++) {
  21573. var subMesh = this.subMeshes[subIndex];
  21574. if (count > 1 || !subMesh.IsGlobal) {
  21575. subMesh.updateBoundingInfo(matrix);
  21576. }
  21577. }
  21578. return this;
  21579. };
  21580. /** @hidden */
  21581. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21582. // Bounding info
  21583. this._updateBoundingInfo();
  21584. };
  21585. /**
  21586. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21587. * A mesh is in the frustum if its bounding box intersects the frustum
  21588. * @param frustumPlanes defines the frustum to test
  21589. * @returns true if the mesh is in the frustum planes
  21590. */
  21591. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21592. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21593. };
  21594. /**
  21595. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21596. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21597. * @param frustumPlanes defines the frustum to test
  21598. * @returns true if the mesh is completely in the frustum planes
  21599. */
  21600. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21601. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21602. };
  21603. /**
  21604. * True if the mesh intersects another mesh or a SolidParticle object
  21605. * @param mesh defines a target mesh or SolidParticle to test
  21606. * @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)
  21607. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21608. * @returns true if there is an intersection
  21609. */
  21610. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21611. if (precise === void 0) { precise = false; }
  21612. if (!this._boundingInfo || !mesh._boundingInfo) {
  21613. return false;
  21614. }
  21615. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21616. return true;
  21617. }
  21618. if (includeDescendants) {
  21619. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21620. var child = _a[_i];
  21621. if (child.intersectsMesh(mesh, precise, true)) {
  21622. return true;
  21623. }
  21624. }
  21625. }
  21626. return false;
  21627. };
  21628. /**
  21629. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21630. * @param point defines the point to test
  21631. * @returns true if there is an intersection
  21632. */
  21633. AbstractMesh.prototype.intersectsPoint = function (point) {
  21634. if (!this._boundingInfo) {
  21635. return false;
  21636. }
  21637. return this._boundingInfo.intersectsPoint(point);
  21638. };
  21639. /**
  21640. * Gets the position of the current mesh in camera space
  21641. * @param camera defines the camera to use
  21642. * @returns a position
  21643. */
  21644. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21645. if (camera === void 0) { camera = null; }
  21646. if (!camera) {
  21647. camera = this.getScene().activeCamera;
  21648. }
  21649. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21650. };
  21651. /**
  21652. * Returns the distance from the mesh to the active camera
  21653. * @param camera defines the camera to use
  21654. * @returns the distance
  21655. */
  21656. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21657. if (camera === void 0) { camera = null; }
  21658. if (!camera) {
  21659. camera = this.getScene().activeCamera;
  21660. }
  21661. return this.absolutePosition.subtract(camera.position).length();
  21662. };
  21663. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21664. // Collisions
  21665. /**
  21666. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21667. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21668. */
  21669. get: function () {
  21670. return this._checkCollisions;
  21671. },
  21672. set: function (collisionEnabled) {
  21673. this._checkCollisions = collisionEnabled;
  21674. if (this.getScene().workerCollisions) {
  21675. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21676. }
  21677. },
  21678. enumerable: true,
  21679. configurable: true
  21680. });
  21681. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21682. /**
  21683. * Gets Collider object used to compute collisions (not physics)
  21684. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21685. */
  21686. get: function () {
  21687. return this._collider;
  21688. },
  21689. enumerable: true,
  21690. configurable: true
  21691. });
  21692. /**
  21693. * Move the mesh using collision engine
  21694. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21695. * @param displacement defines the requested displacement vector
  21696. * @returns the current mesh
  21697. */
  21698. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21699. var globalPosition = this.getAbsolutePosition();
  21700. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21701. if (!this._collider) {
  21702. this._collider = new BABYLON.Collider();
  21703. }
  21704. this._collider._radius = this.ellipsoid;
  21705. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21706. return this;
  21707. };
  21708. // Collisions
  21709. /** @hidden */
  21710. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21711. this._generatePointsArray();
  21712. if (!this._positions) {
  21713. return this;
  21714. }
  21715. // Transformation
  21716. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21717. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21718. subMesh._lastColliderWorldVertices = [];
  21719. subMesh._trianglePlanes = [];
  21720. var start = subMesh.verticesStart;
  21721. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21722. for (var i = start; i < end; i++) {
  21723. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21724. }
  21725. }
  21726. // Collide
  21727. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21728. if (collider.collisionFound) {
  21729. collider.collidedMesh = this;
  21730. }
  21731. return this;
  21732. };
  21733. /** @hidden */
  21734. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21735. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21736. var len = subMeshes.length;
  21737. for (var index = 0; index < len; index++) {
  21738. var subMesh = subMeshes.data[index];
  21739. // Bounding test
  21740. if (len > 1 && !subMesh._checkCollision(collider))
  21741. continue;
  21742. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21743. }
  21744. return this;
  21745. };
  21746. /** @hidden */
  21747. AbstractMesh.prototype._checkCollision = function (collider) {
  21748. // Bounding box test
  21749. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21750. return this;
  21751. // Transformation matrix
  21752. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21753. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21754. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21755. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21756. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21757. return this;
  21758. };
  21759. // Picking
  21760. /** @hidden */
  21761. AbstractMesh.prototype._generatePointsArray = function () {
  21762. return false;
  21763. };
  21764. /**
  21765. * Checks if the passed Ray intersects with the mesh
  21766. * @param ray defines the ray to use
  21767. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21768. * @returns the picking info
  21769. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21770. */
  21771. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21772. var pickingInfo = new BABYLON.PickingInfo();
  21773. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21774. return pickingInfo;
  21775. }
  21776. if (!this._generatePointsArray()) {
  21777. return pickingInfo;
  21778. }
  21779. var intersectInfo = null;
  21780. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21781. var len = subMeshes.length;
  21782. for (var index = 0; index < len; index++) {
  21783. var subMesh = subMeshes.data[index];
  21784. // Bounding test
  21785. if (len > 1 && !subMesh.canIntersects(ray))
  21786. continue;
  21787. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21788. if (currentIntersectInfo) {
  21789. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21790. intersectInfo = currentIntersectInfo;
  21791. intersectInfo.subMeshId = index;
  21792. if (fastCheck) {
  21793. break;
  21794. }
  21795. }
  21796. }
  21797. }
  21798. if (intersectInfo) {
  21799. // Get picked point
  21800. var world = this.getWorldMatrix();
  21801. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21802. var direction = ray.direction.clone();
  21803. direction = direction.scale(intersectInfo.distance);
  21804. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21805. var pickedPoint = worldOrigin.add(worldDirection);
  21806. // Return result
  21807. pickingInfo.hit = true;
  21808. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21809. pickingInfo.pickedPoint = pickedPoint;
  21810. pickingInfo.pickedMesh = this;
  21811. pickingInfo.bu = intersectInfo.bu || 0;
  21812. pickingInfo.bv = intersectInfo.bv || 0;
  21813. pickingInfo.faceId = intersectInfo.faceId;
  21814. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21815. return pickingInfo;
  21816. }
  21817. return pickingInfo;
  21818. };
  21819. /**
  21820. * Clones the current mesh
  21821. * @param name defines the mesh name
  21822. * @param newParent defines the new mesh parent
  21823. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21824. * @returns the new mesh
  21825. */
  21826. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21827. return null;
  21828. };
  21829. /**
  21830. * Disposes all the submeshes of the current meshnp
  21831. * @returns the current mesh
  21832. */
  21833. AbstractMesh.prototype.releaseSubMeshes = function () {
  21834. if (this.subMeshes) {
  21835. while (this.subMeshes.length) {
  21836. this.subMeshes[0].dispose();
  21837. }
  21838. }
  21839. else {
  21840. this.subMeshes = new Array();
  21841. }
  21842. return this;
  21843. };
  21844. /**
  21845. * Releases resources associated with this abstract mesh.
  21846. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21847. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21848. */
  21849. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21850. var _this = this;
  21851. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21852. var index;
  21853. // Smart Array Retainers.
  21854. this.getScene().freeActiveMeshes();
  21855. this.getScene().freeRenderingGroups();
  21856. // Action manager
  21857. if (this.actionManager !== undefined && this.actionManager !== null) {
  21858. this.actionManager.dispose();
  21859. this.actionManager = null;
  21860. }
  21861. // Skeleton
  21862. this._skeleton = null;
  21863. // Intersections in progress
  21864. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21865. var other = this._intersectionsInProgress[index];
  21866. var pos = other._intersectionsInProgress.indexOf(this);
  21867. other._intersectionsInProgress.splice(pos, 1);
  21868. }
  21869. this._intersectionsInProgress = [];
  21870. // Lights
  21871. var lights = this.getScene().lights;
  21872. lights.forEach(function (light) {
  21873. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21874. if (meshIndex !== -1) {
  21875. light.includedOnlyMeshes.splice(meshIndex, 1);
  21876. }
  21877. meshIndex = light.excludedMeshes.indexOf(_this);
  21878. if (meshIndex !== -1) {
  21879. light.excludedMeshes.splice(meshIndex, 1);
  21880. }
  21881. // Shadow generators
  21882. var generator = light.getShadowGenerator();
  21883. if (generator) {
  21884. var shadowMap = generator.getShadowMap();
  21885. if (shadowMap && shadowMap.renderList) {
  21886. meshIndex = shadowMap.renderList.indexOf(_this);
  21887. if (meshIndex !== -1) {
  21888. shadowMap.renderList.splice(meshIndex, 1);
  21889. }
  21890. }
  21891. }
  21892. });
  21893. // SubMeshes
  21894. if (this.getClassName() !== "InstancedMesh") {
  21895. this.releaseSubMeshes();
  21896. }
  21897. // Query
  21898. var engine = this.getScene().getEngine();
  21899. if (this._occlusionQuery) {
  21900. this.isOcclusionQueryInProgress = false;
  21901. engine.deleteQuery(this._occlusionQuery);
  21902. this._occlusionQuery = null;
  21903. }
  21904. // Engine
  21905. engine.wipeCaches();
  21906. // Remove from scene
  21907. this.getScene().removeMesh(this);
  21908. if (disposeMaterialAndTextures) {
  21909. if (this.material) {
  21910. this.material.dispose(false, true);
  21911. }
  21912. }
  21913. if (!doNotRecurse) {
  21914. // Particles
  21915. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21916. if (this.getScene().particleSystems[index].emitter === this) {
  21917. this.getScene().particleSystems[index].dispose();
  21918. index--;
  21919. }
  21920. }
  21921. }
  21922. // facet data
  21923. if (this._facetData.facetDataEnabled) {
  21924. this.disableFacetData();
  21925. }
  21926. this.onAfterWorldMatrixUpdateObservable.clear();
  21927. this.onCollideObservable.clear();
  21928. this.onCollisionPositionChangeObservable.clear();
  21929. this.onRebuildObservable.clear();
  21930. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21931. };
  21932. /**
  21933. * Adds the passed mesh as a child to the current mesh
  21934. * @param mesh defines the child mesh
  21935. * @returns the current mesh
  21936. */
  21937. AbstractMesh.prototype.addChild = function (mesh) {
  21938. mesh.setParent(this);
  21939. return this;
  21940. };
  21941. /**
  21942. * Removes the passed mesh from the current mesh children list
  21943. * @param mesh defines the child mesh
  21944. * @returns the current mesh
  21945. */
  21946. AbstractMesh.prototype.removeChild = function (mesh) {
  21947. mesh.setParent(null);
  21948. return this;
  21949. };
  21950. // Facet data
  21951. /** @hidden */
  21952. AbstractMesh.prototype._initFacetData = function () {
  21953. var data = this._facetData;
  21954. if (!data.facetNormals) {
  21955. data.facetNormals = new Array();
  21956. }
  21957. if (!data.facetPositions) {
  21958. data.facetPositions = new Array();
  21959. }
  21960. if (!data.facetPartitioning) {
  21961. data.facetPartitioning = new Array();
  21962. }
  21963. data.facetNb = (this.getIndices().length / 3) | 0;
  21964. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21965. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21966. for (var f = 0; f < data.facetNb; f++) {
  21967. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21968. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21969. }
  21970. data.facetDataEnabled = true;
  21971. return this;
  21972. };
  21973. /**
  21974. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21975. * This method can be called within the render loop.
  21976. * 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
  21977. * @returns the current mesh
  21978. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21979. */
  21980. AbstractMesh.prototype.updateFacetData = function () {
  21981. var data = this._facetData;
  21982. if (!data.facetDataEnabled) {
  21983. this._initFacetData();
  21984. }
  21985. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21986. var indices = this.getIndices();
  21987. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21988. var bInfo = this.getBoundingInfo();
  21989. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  21990. // init arrays, matrix and sort function on first call
  21991. data.facetDepthSortEnabled = true;
  21992. if (indices instanceof Uint16Array) {
  21993. data.depthSortedIndices = new Uint16Array(indices);
  21994. }
  21995. else if (indices instanceof Uint32Array) {
  21996. data.depthSortedIndices = new Uint32Array(indices);
  21997. }
  21998. else {
  21999. var needs32bits = false;
  22000. for (var i = 0; i < indices.length; i++) {
  22001. if (indices[i] > 65535) {
  22002. needs32bits = true;
  22003. break;
  22004. }
  22005. }
  22006. if (needs32bits) {
  22007. data.depthSortedIndices = new Uint32Array(indices);
  22008. }
  22009. else {
  22010. data.depthSortedIndices = new Uint16Array(indices);
  22011. }
  22012. }
  22013. data.facetDepthSortFunction = function (f1, f2) {
  22014. return (f2.sqDistance - f1.sqDistance);
  22015. };
  22016. if (!data.facetDepthSortFrom) {
  22017. var camera = this.getScene().activeCamera;
  22018. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22019. }
  22020. data.depthSortedFacets = [];
  22021. for (var f = 0; f < data.facetNb; f++) {
  22022. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22023. data.depthSortedFacets.push(depthSortedFacet);
  22024. }
  22025. data.invertedMatrix = BABYLON.Matrix.Identity();
  22026. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22027. }
  22028. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22029. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22030. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22031. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22032. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22033. data.subDiv.max = data.partitioningSubdivisions;
  22034. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22035. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22036. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22037. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22038. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22039. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22040. // set the parameters for ComputeNormals()
  22041. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22042. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22043. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22044. data.facetParameters.bInfo = bInfo;
  22045. data.facetParameters.bbSize = data.bbSize;
  22046. data.facetParameters.subDiv = data.subDiv;
  22047. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22048. data.facetParameters.depthSort = data.facetDepthSort;
  22049. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22050. this.computeWorldMatrix(true);
  22051. this._worldMatrix.invertToRef(data.invertedMatrix);
  22052. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22053. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22054. }
  22055. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22056. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22057. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22058. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22059. var l = (data.depthSortedIndices.length / 3) | 0;
  22060. for (var f = 0; f < l; f++) {
  22061. var sind = data.depthSortedFacets[f].ind;
  22062. data.depthSortedIndices[f * 3] = indices[sind];
  22063. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22064. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22065. }
  22066. this.updateIndices(data.depthSortedIndices);
  22067. }
  22068. return this;
  22069. };
  22070. /**
  22071. * Returns the facetLocalNormals array.
  22072. * The normals are expressed in the mesh local spac
  22073. * @returns an array of Vector3
  22074. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22075. */
  22076. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22077. if (!this._facetData.facetNormals) {
  22078. this.updateFacetData();
  22079. }
  22080. return this._facetData.facetNormals;
  22081. };
  22082. /**
  22083. * Returns the facetLocalPositions array.
  22084. * The facet positions are expressed in the mesh local space
  22085. * @returns an array of Vector3
  22086. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22087. */
  22088. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22089. if (!this._facetData.facetPositions) {
  22090. this.updateFacetData();
  22091. }
  22092. return this._facetData.facetPositions;
  22093. };
  22094. /**
  22095. * Returns the facetLocalPartioning array
  22096. * @returns an array of array of numbers
  22097. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22098. */
  22099. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22100. if (!this._facetData.facetPartitioning) {
  22101. this.updateFacetData();
  22102. }
  22103. return this._facetData.facetPartitioning;
  22104. };
  22105. /**
  22106. * Returns the i-th facet position in the world system.
  22107. * This method allocates a new Vector3 per call
  22108. * @param i defines the facet index
  22109. * @returns a new Vector3
  22110. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22111. */
  22112. AbstractMesh.prototype.getFacetPosition = function (i) {
  22113. var pos = BABYLON.Vector3.Zero();
  22114. this.getFacetPositionToRef(i, pos);
  22115. return pos;
  22116. };
  22117. /**
  22118. * Sets the reference Vector3 with the i-th facet position in the world system
  22119. * @param i defines the facet index
  22120. * @param ref defines the target vector
  22121. * @returns the current mesh
  22122. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22123. */
  22124. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22125. var localPos = (this.getFacetLocalPositions())[i];
  22126. var world = this.getWorldMatrix();
  22127. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22128. return this;
  22129. };
  22130. /**
  22131. * Returns the i-th facet normal in the world system.
  22132. * This method allocates a new Vector3 per call
  22133. * @param i defines the facet index
  22134. * @returns a new Vector3
  22135. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22136. */
  22137. AbstractMesh.prototype.getFacetNormal = function (i) {
  22138. var norm = BABYLON.Vector3.Zero();
  22139. this.getFacetNormalToRef(i, norm);
  22140. return norm;
  22141. };
  22142. /**
  22143. * Sets the reference Vector3 with the i-th facet normal in the world system
  22144. * @param i defines the facet index
  22145. * @param ref defines the target vector
  22146. * @returns the current mesh
  22147. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22148. */
  22149. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22150. var localNorm = (this.getFacetLocalNormals())[i];
  22151. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22152. return this;
  22153. };
  22154. /**
  22155. * 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)
  22156. * @param x defines x coordinate
  22157. * @param y defines y coordinate
  22158. * @param z defines z coordinate
  22159. * @returns the array of facet indexes
  22160. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22161. */
  22162. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22163. var bInfo = this.getBoundingInfo();
  22164. var data = this._facetData;
  22165. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22166. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22167. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22168. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22169. return null;
  22170. }
  22171. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22172. };
  22173. /**
  22174. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22175. * @param projected sets as the (x,y,z) world projection on the facet
  22176. * @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
  22177. * @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
  22178. * @param x defines x coordinate
  22179. * @param y defines y coordinate
  22180. * @param z defines z coordinate
  22181. * @returns the face index if found (or null instead)
  22182. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22183. */
  22184. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22185. if (checkFace === void 0) { checkFace = false; }
  22186. if (facing === void 0) { facing = true; }
  22187. var world = this.getWorldMatrix();
  22188. var invMat = BABYLON.Tmp.Matrix[5];
  22189. world.invertToRef(invMat);
  22190. var invVect = BABYLON.Tmp.Vector3[8];
  22191. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22192. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22193. if (projected) {
  22194. // tranform the local computed projected vector to world coordinates
  22195. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22196. }
  22197. return closest;
  22198. };
  22199. /**
  22200. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22201. * @param projected sets as the (x,y,z) local projection on the facet
  22202. * @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
  22203. * @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
  22204. * @param x defines x coordinate
  22205. * @param y defines y coordinate
  22206. * @param z defines z coordinate
  22207. * @returns the face index if found (or null instead)
  22208. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22209. */
  22210. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22211. if (checkFace === void 0) { checkFace = false; }
  22212. if (facing === void 0) { facing = true; }
  22213. var closest = null;
  22214. var tmpx = 0.0;
  22215. var tmpy = 0.0;
  22216. var tmpz = 0.0;
  22217. var d = 0.0; // tmp dot facet normal * facet position
  22218. var t0 = 0.0;
  22219. var projx = 0.0;
  22220. var projy = 0.0;
  22221. var projz = 0.0;
  22222. // Get all the facets in the same partitioning block than (x, y, z)
  22223. var facetPositions = this.getFacetLocalPositions();
  22224. var facetNormals = this.getFacetLocalNormals();
  22225. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22226. if (!facetsInBlock) {
  22227. return null;
  22228. }
  22229. // Get the closest facet to (x, y, z)
  22230. var shortest = Number.MAX_VALUE; // init distance vars
  22231. var tmpDistance = shortest;
  22232. var fib; // current facet in the block
  22233. var norm; // current facet normal
  22234. var p0; // current facet barycenter position
  22235. // loop on all the facets in the current partitioning block
  22236. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22237. fib = facetsInBlock[idx];
  22238. norm = facetNormals[fib];
  22239. p0 = facetPositions[fib];
  22240. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22241. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22242. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22243. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22244. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22245. projx = x + norm.x * t0;
  22246. projy = y + norm.y * t0;
  22247. projz = z + norm.z * t0;
  22248. tmpx = projx - x;
  22249. tmpy = projy - y;
  22250. tmpz = projz - z;
  22251. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22252. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22253. shortest = tmpDistance;
  22254. closest = fib;
  22255. if (projected) {
  22256. projected.x = projx;
  22257. projected.y = projy;
  22258. projected.z = projz;
  22259. }
  22260. }
  22261. }
  22262. }
  22263. return closest;
  22264. };
  22265. /**
  22266. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22267. * @returns the parameters
  22268. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22269. */
  22270. AbstractMesh.prototype.getFacetDataParameters = function () {
  22271. return this._facetData.facetParameters;
  22272. };
  22273. /**
  22274. * Disables the feature FacetData and frees the related memory
  22275. * @returns the current mesh
  22276. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22277. */
  22278. AbstractMesh.prototype.disableFacetData = function () {
  22279. if (this._facetData.facetDataEnabled) {
  22280. this._facetData.facetDataEnabled = false;
  22281. this._facetData.facetPositions = new Array();
  22282. this._facetData.facetNormals = new Array();
  22283. this._facetData.facetPartitioning = new Array();
  22284. this._facetData.facetParameters = null;
  22285. this._facetData.depthSortedIndices = new Uint32Array(0);
  22286. }
  22287. return this;
  22288. };
  22289. /**
  22290. * Updates the AbstractMesh indices array
  22291. * @param indices defines the data source
  22292. * @returns the current mesh
  22293. */
  22294. AbstractMesh.prototype.updateIndices = function (indices) {
  22295. return this;
  22296. };
  22297. /**
  22298. * Creates new normals data for the mesh
  22299. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22300. * @returns the current mesh
  22301. */
  22302. AbstractMesh.prototype.createNormals = function (updatable) {
  22303. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22304. var indices = this.getIndices();
  22305. var normals;
  22306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22307. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22308. }
  22309. else {
  22310. normals = [];
  22311. }
  22312. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22313. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22314. return this;
  22315. };
  22316. /**
  22317. * Align the mesh with a normal
  22318. * @param normal defines the normal to use
  22319. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22320. * @returns the current mesh
  22321. */
  22322. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22323. if (!upDirection) {
  22324. upDirection = BABYLON.Axis.Y;
  22325. }
  22326. var axisX = BABYLON.Tmp.Vector3[0];
  22327. var axisZ = BABYLON.Tmp.Vector3[1];
  22328. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22329. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22330. if (this.rotationQuaternion) {
  22331. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22332. }
  22333. else {
  22334. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22335. }
  22336. return this;
  22337. };
  22338. /** @hidden */
  22339. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22340. return false;
  22341. };
  22342. /** No occlusion */
  22343. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22344. /** Occlusion set to optimisitic */
  22345. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22346. /** Occlusion set to strict */
  22347. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22348. /** Use an accurante occlusion algorithm */
  22349. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22350. /** Use a conservative occlusion algorithm */
  22351. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22352. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22353. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22354. /** Culling strategy with bounding sphere only and then frustum culling */
  22355. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22356. return AbstractMesh;
  22357. }(BABYLON.TransformNode));
  22358. BABYLON.AbstractMesh = AbstractMesh;
  22359. })(BABYLON || (BABYLON = {}));
  22360. //# sourceMappingURL=babylon.abstractMesh.js.map
  22361. var BABYLON;
  22362. (function (BABYLON) {
  22363. /**
  22364. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22365. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22366. * 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.
  22367. */
  22368. var Light = /** @class */ (function (_super) {
  22369. __extends(Light, _super);
  22370. /**
  22371. * Creates a Light object in the scene.
  22372. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22373. * @param name The firendly name of the light
  22374. * @param scene The scene the light belongs too
  22375. */
  22376. function Light(name, scene) {
  22377. var _this = _super.call(this, name, scene) || this;
  22378. /**
  22379. * Diffuse gives the basic color to an object.
  22380. */
  22381. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22382. /**
  22383. * Specular produces a highlight color on an object.
  22384. * Note: This is note affecting PBR materials.
  22385. */
  22386. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22387. /**
  22388. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22389. * falling off base on range or angle.
  22390. * This can be set to any values in Light.FALLOFF_x.
  22391. *
  22392. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22393. * other types of materials.
  22394. */
  22395. _this.falloffType = Light.FALLOFF_DEFAULT;
  22396. /**
  22397. * Strength of the light.
  22398. * Note: By default it is define in the framework own unit.
  22399. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22400. */
  22401. _this.intensity = 1.0;
  22402. _this._range = Number.MAX_VALUE;
  22403. _this._inverseSquaredRange = 0;
  22404. /**
  22405. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22406. * of light.
  22407. */
  22408. _this._photometricScale = 1.0;
  22409. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22410. _this._radius = 0.00001;
  22411. /**
  22412. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22413. * exceeding the number allowed of the materials.
  22414. */
  22415. _this.renderPriority = 0;
  22416. _this._shadowEnabled = true;
  22417. _this._excludeWithLayerMask = 0;
  22418. _this._includeOnlyWithLayerMask = 0;
  22419. _this._lightmapMode = 0;
  22420. /**
  22421. * @hidden Internal use only.
  22422. */
  22423. _this._excludedMeshesIds = new Array();
  22424. /**
  22425. * @hidden Internal use only.
  22426. */
  22427. _this._includedOnlyMeshesIds = new Array();
  22428. _this.getScene().addLight(_this);
  22429. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22430. _this._buildUniformLayout();
  22431. _this.includedOnlyMeshes = new Array();
  22432. _this.excludedMeshes = new Array();
  22433. _this._resyncMeshes();
  22434. return _this;
  22435. }
  22436. Object.defineProperty(Light.prototype, "range", {
  22437. /**
  22438. * Defines how far from the source the light is impacting in scene units.
  22439. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22440. */
  22441. get: function () {
  22442. return this._range;
  22443. },
  22444. /**
  22445. * Defines how far from the source the light is impacting in scene units.
  22446. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22447. */
  22448. set: function (value) {
  22449. this._range = value;
  22450. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22451. },
  22452. enumerable: true,
  22453. configurable: true
  22454. });
  22455. Object.defineProperty(Light.prototype, "intensityMode", {
  22456. /**
  22457. * Gets the photometric scale used to interpret the intensity.
  22458. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22459. */
  22460. get: function () {
  22461. return this._intensityMode;
  22462. },
  22463. /**
  22464. * Sets the photometric scale used to interpret the intensity.
  22465. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22466. */
  22467. set: function (value) {
  22468. this._intensityMode = value;
  22469. this._computePhotometricScale();
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. ;
  22475. ;
  22476. Object.defineProperty(Light.prototype, "radius", {
  22477. /**
  22478. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22479. */
  22480. get: function () {
  22481. return this._radius;
  22482. },
  22483. /**
  22484. * sets the light radius used by PBR Materials to simulate soft area lights.
  22485. */
  22486. set: function (value) {
  22487. this._radius = value;
  22488. this._computePhotometricScale();
  22489. },
  22490. enumerable: true,
  22491. configurable: true
  22492. });
  22493. ;
  22494. ;
  22495. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22496. /**
  22497. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22498. * the current shadow generator.
  22499. */
  22500. get: function () {
  22501. return this._shadowEnabled;
  22502. },
  22503. /**
  22504. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22505. * the current shadow generator.
  22506. */
  22507. set: function (value) {
  22508. if (this._shadowEnabled === value) {
  22509. return;
  22510. }
  22511. this._shadowEnabled = value;
  22512. this._markMeshesAsLightDirty();
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22518. /**
  22519. * Gets the only meshes impacted by this light.
  22520. */
  22521. get: function () {
  22522. return this._includedOnlyMeshes;
  22523. },
  22524. /**
  22525. * Sets the only meshes impacted by this light.
  22526. */
  22527. set: function (value) {
  22528. this._includedOnlyMeshes = value;
  22529. this._hookArrayForIncludedOnly(value);
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22535. /**
  22536. * Gets the meshes not impacted by this light.
  22537. */
  22538. get: function () {
  22539. return this._excludedMeshes;
  22540. },
  22541. /**
  22542. * Sets the meshes not impacted by this light.
  22543. */
  22544. set: function (value) {
  22545. this._excludedMeshes = value;
  22546. this._hookArrayForExcluded(value);
  22547. },
  22548. enumerable: true,
  22549. configurable: true
  22550. });
  22551. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22552. /**
  22553. * Gets the layer id use to find what meshes are not impacted by the light.
  22554. * Inactive if 0
  22555. */
  22556. get: function () {
  22557. return this._excludeWithLayerMask;
  22558. },
  22559. /**
  22560. * Sets the layer id use to find what meshes are not impacted by the light.
  22561. * Inactive if 0
  22562. */
  22563. set: function (value) {
  22564. this._excludeWithLayerMask = value;
  22565. this._resyncMeshes();
  22566. },
  22567. enumerable: true,
  22568. configurable: true
  22569. });
  22570. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22571. /**
  22572. * Gets the layer id use to find what meshes are impacted by the light.
  22573. * Inactive if 0
  22574. */
  22575. get: function () {
  22576. return this._includeOnlyWithLayerMask;
  22577. },
  22578. /**
  22579. * Sets the layer id use to find what meshes are impacted by the light.
  22580. * Inactive if 0
  22581. */
  22582. set: function (value) {
  22583. this._includeOnlyWithLayerMask = value;
  22584. this._resyncMeshes();
  22585. },
  22586. enumerable: true,
  22587. configurable: true
  22588. });
  22589. Object.defineProperty(Light.prototype, "lightmapMode", {
  22590. /**
  22591. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22592. */
  22593. get: function () {
  22594. return this._lightmapMode;
  22595. },
  22596. /**
  22597. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22598. */
  22599. set: function (value) {
  22600. if (this._lightmapMode === value) {
  22601. return;
  22602. }
  22603. this._lightmapMode = value;
  22604. this._markMeshesAsLightDirty();
  22605. },
  22606. enumerable: true,
  22607. configurable: true
  22608. });
  22609. /**
  22610. * Returns the string "Light".
  22611. * @returns the class name
  22612. */
  22613. Light.prototype.getClassName = function () {
  22614. return "Light";
  22615. };
  22616. /**
  22617. * Converts the light information to a readable string for debug purpose.
  22618. * @param fullDetails Supports for multiple levels of logging within scene loading
  22619. * @returns the human readable light info
  22620. */
  22621. Light.prototype.toString = function (fullDetails) {
  22622. var ret = "Name: " + this.name;
  22623. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22624. if (this.animations) {
  22625. for (var i = 0; i < this.animations.length; i++) {
  22626. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22627. }
  22628. }
  22629. if (fullDetails) {
  22630. }
  22631. return ret;
  22632. };
  22633. /** @hidden */
  22634. Light.prototype._syncParentEnabledState = function () {
  22635. _super.prototype._syncParentEnabledState.call(this);
  22636. this._resyncMeshes();
  22637. };
  22638. /**
  22639. * Set the enabled state of this node.
  22640. * @param value - the new enabled state
  22641. */
  22642. Light.prototype.setEnabled = function (value) {
  22643. _super.prototype.setEnabled.call(this, value);
  22644. this._resyncMeshes();
  22645. };
  22646. /**
  22647. * Returns the Light associated shadow generator if any.
  22648. * @return the associated shadow generator.
  22649. */
  22650. Light.prototype.getShadowGenerator = function () {
  22651. return this._shadowGenerator;
  22652. };
  22653. /**
  22654. * Returns a Vector3, the absolute light position in the World.
  22655. * @returns the world space position of the light
  22656. */
  22657. Light.prototype.getAbsolutePosition = function () {
  22658. return BABYLON.Vector3.Zero();
  22659. };
  22660. /**
  22661. * Specifies if the light will affect the passed mesh.
  22662. * @param mesh The mesh to test against the light
  22663. * @return true the mesh is affected otherwise, false.
  22664. */
  22665. Light.prototype.canAffectMesh = function (mesh) {
  22666. if (!mesh) {
  22667. return true;
  22668. }
  22669. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22670. return false;
  22671. }
  22672. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22673. return false;
  22674. }
  22675. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22676. return false;
  22677. }
  22678. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22679. return false;
  22680. }
  22681. return true;
  22682. };
  22683. /**
  22684. * Sort function to order lights for rendering.
  22685. * @param a First Light object to compare to second.
  22686. * @param b Second Light object to compare first.
  22687. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22688. */
  22689. Light.CompareLightsPriority = function (a, b) {
  22690. //shadow-casting lights have priority over non-shadow-casting lights
  22691. //the renderPrioirty is a secondary sort criterion
  22692. if (a.shadowEnabled !== b.shadowEnabled) {
  22693. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22694. }
  22695. return b.renderPriority - a.renderPriority;
  22696. };
  22697. /**
  22698. * Releases resources associated with this node.
  22699. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22700. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22701. */
  22702. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22703. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22704. if (this._shadowGenerator) {
  22705. this._shadowGenerator.dispose();
  22706. this._shadowGenerator = null;
  22707. }
  22708. // Animations
  22709. this.getScene().stopAnimation(this);
  22710. // Remove from meshes
  22711. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22712. var mesh = _a[_i];
  22713. mesh._removeLightSource(this);
  22714. }
  22715. this._uniformBuffer.dispose();
  22716. // Remove from scene
  22717. this.getScene().removeLight(this);
  22718. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22719. };
  22720. /**
  22721. * Returns the light type ID (integer).
  22722. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22723. */
  22724. Light.prototype.getTypeID = function () {
  22725. return 0;
  22726. };
  22727. /**
  22728. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22729. * @returns the scaled intensity in intensity mode unit
  22730. */
  22731. Light.prototype.getScaledIntensity = function () {
  22732. return this._photometricScale * this.intensity;
  22733. };
  22734. /**
  22735. * Returns a new Light object, named "name", from the current one.
  22736. * @param name The name of the cloned light
  22737. * @returns the new created light
  22738. */
  22739. Light.prototype.clone = function (name) {
  22740. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22741. if (!constructor) {
  22742. return null;
  22743. }
  22744. return BABYLON.SerializationHelper.Clone(constructor, this);
  22745. };
  22746. /**
  22747. * Serializes the current light into a Serialization object.
  22748. * @returns the serialized object.
  22749. */
  22750. Light.prototype.serialize = function () {
  22751. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22752. // Type
  22753. serializationObject.type = this.getTypeID();
  22754. // Parent
  22755. if (this.parent) {
  22756. serializationObject.parentId = this.parent.id;
  22757. }
  22758. // Inclusion / exclusions
  22759. if (this.excludedMeshes.length > 0) {
  22760. serializationObject.excludedMeshesIds = [];
  22761. this.excludedMeshes.forEach(function (mesh) {
  22762. serializationObject.excludedMeshesIds.push(mesh.id);
  22763. });
  22764. }
  22765. if (this.includedOnlyMeshes.length > 0) {
  22766. serializationObject.includedOnlyMeshesIds = [];
  22767. this.includedOnlyMeshes.forEach(function (mesh) {
  22768. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22769. });
  22770. }
  22771. // Animations
  22772. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22773. serializationObject.ranges = this.serializeAnimationRanges();
  22774. return serializationObject;
  22775. };
  22776. /**
  22777. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22778. * This new light is named "name" and added to the passed scene.
  22779. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22780. * @param name The friendly name of the light
  22781. * @param scene The scene the new light will belong to
  22782. * @returns the constructor function
  22783. */
  22784. Light.GetConstructorFromName = function (type, name, scene) {
  22785. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22786. if (constructorFunc) {
  22787. return constructorFunc;
  22788. }
  22789. // Default to no light for none present once.
  22790. return null;
  22791. };
  22792. /**
  22793. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22794. * @param parsedLight The JSON representation of the light
  22795. * @param scene The scene to create the parsed light in
  22796. * @returns the created light after parsing
  22797. */
  22798. Light.Parse = function (parsedLight, scene) {
  22799. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22800. if (!constructor) {
  22801. return null;
  22802. }
  22803. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22804. // Inclusion / exclusions
  22805. if (parsedLight.excludedMeshesIds) {
  22806. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22807. }
  22808. if (parsedLight.includedOnlyMeshesIds) {
  22809. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22810. }
  22811. // Parent
  22812. if (parsedLight.parentId) {
  22813. light._waitingParentId = parsedLight.parentId;
  22814. }
  22815. // Animations
  22816. if (parsedLight.animations) {
  22817. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22818. var parsedAnimation = parsedLight.animations[animationIndex];
  22819. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22820. }
  22821. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22822. }
  22823. if (parsedLight.autoAnimate) {
  22824. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22825. }
  22826. return light;
  22827. };
  22828. Light.prototype._hookArrayForExcluded = function (array) {
  22829. var _this = this;
  22830. var oldPush = array.push;
  22831. array.push = function () {
  22832. var items = [];
  22833. for (var _i = 0; _i < arguments.length; _i++) {
  22834. items[_i] = arguments[_i];
  22835. }
  22836. var result = oldPush.apply(array, items);
  22837. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22838. var item = items_1[_a];
  22839. item._resyncLighSource(_this);
  22840. }
  22841. return result;
  22842. };
  22843. var oldSplice = array.splice;
  22844. array.splice = function (index, deleteCount) {
  22845. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22846. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22847. var item = deleted_1[_i];
  22848. item._resyncLighSource(_this);
  22849. }
  22850. return deleted;
  22851. };
  22852. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22853. var item = array_1[_i];
  22854. item._resyncLighSource(this);
  22855. }
  22856. };
  22857. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22858. var _this = this;
  22859. var oldPush = array.push;
  22860. array.push = function () {
  22861. var items = [];
  22862. for (var _i = 0; _i < arguments.length; _i++) {
  22863. items[_i] = arguments[_i];
  22864. }
  22865. var result = oldPush.apply(array, items);
  22866. _this._resyncMeshes();
  22867. return result;
  22868. };
  22869. var oldSplice = array.splice;
  22870. array.splice = function (index, deleteCount) {
  22871. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22872. _this._resyncMeshes();
  22873. return deleted;
  22874. };
  22875. this._resyncMeshes();
  22876. };
  22877. Light.prototype._resyncMeshes = function () {
  22878. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22879. var mesh = _a[_i];
  22880. mesh._resyncLighSource(this);
  22881. }
  22882. };
  22883. /**
  22884. * Forces the meshes to update their light related information in their rendering used effects
  22885. * @hidden Internal Use Only
  22886. */
  22887. Light.prototype._markMeshesAsLightDirty = function () {
  22888. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22889. var mesh = _a[_i];
  22890. if (mesh._lightSources.indexOf(this) !== -1) {
  22891. mesh._markSubMeshesAsLightDirty();
  22892. }
  22893. }
  22894. };
  22895. /**
  22896. * Recomputes the cached photometric scale if needed.
  22897. */
  22898. Light.prototype._computePhotometricScale = function () {
  22899. this._photometricScale = this._getPhotometricScale();
  22900. this.getScene().resetCachedMaterial();
  22901. };
  22902. /**
  22903. * Returns the Photometric Scale according to the light type and intensity mode.
  22904. */
  22905. Light.prototype._getPhotometricScale = function () {
  22906. var photometricScale = 0.0;
  22907. var lightTypeID = this.getTypeID();
  22908. //get photometric mode
  22909. var photometricMode = this.intensityMode;
  22910. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22911. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22912. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22913. }
  22914. else {
  22915. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22916. }
  22917. }
  22918. //compute photometric scale
  22919. switch (lightTypeID) {
  22920. case Light.LIGHTTYPEID_POINTLIGHT:
  22921. case Light.LIGHTTYPEID_SPOTLIGHT:
  22922. switch (photometricMode) {
  22923. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22924. photometricScale = 1.0 / (4.0 * Math.PI);
  22925. break;
  22926. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22927. photometricScale = 1.0;
  22928. break;
  22929. case Light.INTENSITYMODE_LUMINANCE:
  22930. photometricScale = this.radius * this.radius;
  22931. break;
  22932. }
  22933. break;
  22934. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22935. switch (photometricMode) {
  22936. case Light.INTENSITYMODE_ILLUMINANCE:
  22937. photometricScale = 1.0;
  22938. break;
  22939. case Light.INTENSITYMODE_LUMINANCE:
  22940. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22941. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22942. var apexAngleRadians = this.radius;
  22943. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22944. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22945. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22946. photometricScale = solidAngle;
  22947. break;
  22948. }
  22949. break;
  22950. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22951. // No fall off in hemisperic light.
  22952. photometricScale = 1.0;
  22953. break;
  22954. }
  22955. return photometricScale;
  22956. };
  22957. /**
  22958. * Reorder the light in the scene according to their defined priority.
  22959. * @hidden Internal Use Only
  22960. */
  22961. Light.prototype._reorderLightsInScene = function () {
  22962. var scene = this.getScene();
  22963. if (this._renderPriority != 0) {
  22964. scene.requireLightSorting = true;
  22965. }
  22966. this.getScene().sortLightsByPriority();
  22967. };
  22968. /**
  22969. * Falloff Default: light is falling off following the material specification:
  22970. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22971. */
  22972. Light.FALLOFF_DEFAULT = 0;
  22973. /**
  22974. * Falloff Physical: light is falling off following the inverse squared distance law.
  22975. */
  22976. Light.FALLOFF_PHYSICAL = 1;
  22977. /**
  22978. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  22979. * to enhance interoperability with other engines.
  22980. */
  22981. Light.FALLOFF_GLTF = 2;
  22982. /**
  22983. * Falloff Standard: light is falling off like in the standard material
  22984. * to enhance interoperability with other materials.
  22985. */
  22986. Light.FALLOFF_STANDARD = 3;
  22987. //lightmapMode Consts
  22988. /**
  22989. * If every light affecting the material is in this lightmapMode,
  22990. * material.lightmapTexture adds or multiplies
  22991. * (depends on material.useLightmapAsShadowmap)
  22992. * after every other light calculations.
  22993. */
  22994. Light.LIGHTMAP_DEFAULT = 0;
  22995. /**
  22996. * material.lightmapTexture as only diffuse lighting from this light
  22997. * adds only specular lighting from this light
  22998. * adds dynamic shadows
  22999. */
  23000. Light.LIGHTMAP_SPECULAR = 1;
  23001. /**
  23002. * material.lightmapTexture as only lighting
  23003. * no light calculation from this light
  23004. * only adds dynamic shadows from this light
  23005. */
  23006. Light.LIGHTMAP_SHADOWSONLY = 2;
  23007. // Intensity Mode Consts
  23008. /**
  23009. * Each light type uses the default quantity according to its type:
  23010. * point/spot lights use luminous intensity
  23011. * directional lights use illuminance
  23012. */
  23013. Light.INTENSITYMODE_AUTOMATIC = 0;
  23014. /**
  23015. * lumen (lm)
  23016. */
  23017. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23018. /**
  23019. * candela (lm/sr)
  23020. */
  23021. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23022. /**
  23023. * lux (lm/m^2)
  23024. */
  23025. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23026. /**
  23027. * nit (cd/m^2)
  23028. */
  23029. Light.INTENSITYMODE_LUMINANCE = 4;
  23030. // Light types ids const.
  23031. /**
  23032. * Light type const id of the point light.
  23033. */
  23034. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23035. /**
  23036. * Light type const id of the directional light.
  23037. */
  23038. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23039. /**
  23040. * Light type const id of the spot light.
  23041. */
  23042. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23043. /**
  23044. * Light type const id of the hemispheric light.
  23045. */
  23046. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23047. __decorate([
  23048. BABYLON.serializeAsColor3()
  23049. ], Light.prototype, "diffuse", void 0);
  23050. __decorate([
  23051. BABYLON.serializeAsColor3()
  23052. ], Light.prototype, "specular", void 0);
  23053. __decorate([
  23054. BABYLON.serialize()
  23055. ], Light.prototype, "falloffType", void 0);
  23056. __decorate([
  23057. BABYLON.serialize()
  23058. ], Light.prototype, "intensity", void 0);
  23059. __decorate([
  23060. BABYLON.serialize()
  23061. ], Light.prototype, "range", null);
  23062. __decorate([
  23063. BABYLON.serialize()
  23064. ], Light.prototype, "intensityMode", null);
  23065. __decorate([
  23066. BABYLON.serialize()
  23067. ], Light.prototype, "radius", null);
  23068. __decorate([
  23069. BABYLON.serialize()
  23070. ], Light.prototype, "_renderPriority", void 0);
  23071. __decorate([
  23072. BABYLON.expandToProperty("_reorderLightsInScene")
  23073. ], Light.prototype, "renderPriority", void 0);
  23074. __decorate([
  23075. BABYLON.serialize("shadowEnabled")
  23076. ], Light.prototype, "_shadowEnabled", void 0);
  23077. __decorate([
  23078. BABYLON.serialize("excludeWithLayerMask")
  23079. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23080. __decorate([
  23081. BABYLON.serialize("includeOnlyWithLayerMask")
  23082. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23083. __decorate([
  23084. BABYLON.serialize("lightmapMode")
  23085. ], Light.prototype, "_lightmapMode", void 0);
  23086. return Light;
  23087. }(BABYLON.Node));
  23088. BABYLON.Light = Light;
  23089. })(BABYLON || (BABYLON = {}));
  23090. //# sourceMappingURL=babylon.light.js.map
  23091. var BABYLON;
  23092. (function (BABYLON) {
  23093. /**
  23094. * This is the base class of all the camera used in the application.
  23095. * @see http://doc.babylonjs.com/features/cameras
  23096. */
  23097. var Camera = /** @class */ (function (_super) {
  23098. __extends(Camera, _super);
  23099. /**
  23100. * Instantiates a new camera object.
  23101. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23102. * @see http://doc.babylonjs.com/features/cameras
  23103. * @param name Defines the name of the camera in the scene
  23104. * @param position Defines the position of the camera
  23105. * @param scene Defines the scene the camera belongs too
  23106. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23107. */
  23108. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23109. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23110. var _this = _super.call(this, name, scene) || this;
  23111. /**
  23112. * The vector the camera should consider as up.
  23113. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23114. */
  23115. _this.upVector = BABYLON.Vector3.Up();
  23116. /**
  23117. * Define the current limit on the left side for an orthographic camera
  23118. * In scene unit
  23119. */
  23120. _this.orthoLeft = null;
  23121. /**
  23122. * Define the current limit on the right side for an orthographic camera
  23123. * In scene unit
  23124. */
  23125. _this.orthoRight = null;
  23126. /**
  23127. * Define the current limit on the bottom side for an orthographic camera
  23128. * In scene unit
  23129. */
  23130. _this.orthoBottom = null;
  23131. /**
  23132. * Define the current limit on the top side for an orthographic camera
  23133. * In scene unit
  23134. */
  23135. _this.orthoTop = null;
  23136. /**
  23137. * Field Of View is set in Radians. (default is 0.8)
  23138. */
  23139. _this.fov = 0.8;
  23140. /**
  23141. * Define the minimum distance the camera can see from.
  23142. * This is important to note that the depth buffer are not infinite and the closer it starts
  23143. * the more your scene might encounter depth fighting issue.
  23144. */
  23145. _this.minZ = 1;
  23146. /**
  23147. * Define the maximum distance the camera can see to.
  23148. * This is important to note that the depth buffer are not infinite and the further it end
  23149. * the more your scene might encounter depth fighting issue.
  23150. */
  23151. _this.maxZ = 10000.0;
  23152. /**
  23153. * Define the default inertia of the camera.
  23154. * This helps giving a smooth feeling to the camera movement.
  23155. */
  23156. _this.inertia = 0.9;
  23157. /**
  23158. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23159. */
  23160. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23161. /**
  23162. * Define wether the camera is intermediate.
  23163. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23164. */
  23165. _this.isIntermediate = false;
  23166. /**
  23167. * Define the viewport of the camera.
  23168. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23169. */
  23170. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23171. /**
  23172. * Restricts the camera to viewing objects with the same layerMask.
  23173. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23174. */
  23175. _this.layerMask = 0x0FFFFFFF;
  23176. /**
  23177. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23178. */
  23179. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23180. /**
  23181. * Rig mode of the camera.
  23182. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23183. * This is normally controlled byt the camera themselves as internal use.
  23184. */
  23185. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23186. /**
  23187. * Defines the list of custom render target the camera should render to.
  23188. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23189. * else in the scene.
  23190. */
  23191. _this.customRenderTargets = new Array();
  23192. /**
  23193. * Observable triggered when the camera view matrix has changed.
  23194. */
  23195. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23196. /**
  23197. * Observable triggered when the camera Projection matrix has changed.
  23198. */
  23199. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23200. /**
  23201. * Observable triggered when the inputs have been processed.
  23202. */
  23203. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23204. /**
  23205. * Observable triggered when reset has been called and applied to the camera.
  23206. */
  23207. _this.onRestoreStateObservable = new BABYLON.Observable();
  23208. /** @hidden */
  23209. _this._rigCameras = new Array();
  23210. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23211. /** @hidden */
  23212. _this._skipRendering = false;
  23213. /** @hidden */
  23214. _this._projectionMatrix = new BABYLON.Matrix();
  23215. /** @hidden */
  23216. _this._postProcesses = new Array();
  23217. /** @hidden */
  23218. _this._activeMeshes = new BABYLON.SmartArray(256);
  23219. _this._globalPosition = BABYLON.Vector3.Zero();
  23220. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23221. _this._doNotComputeProjectionMatrix = false;
  23222. _this._transformMatrix = BABYLON.Matrix.Zero();
  23223. _this._refreshFrustumPlanes = true;
  23224. _this.getScene().addCamera(_this);
  23225. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23226. _this.getScene().activeCamera = _this;
  23227. }
  23228. _this.position = position;
  23229. return _this;
  23230. }
  23231. /**
  23232. * Store current camera state (fov, position, etc..)
  23233. * @returns the camera
  23234. */
  23235. Camera.prototype.storeState = function () {
  23236. this._stateStored = true;
  23237. this._storedFov = this.fov;
  23238. return this;
  23239. };
  23240. /**
  23241. * Restores the camera state values if it has been stored. You must call storeState() first
  23242. */
  23243. Camera.prototype._restoreStateValues = function () {
  23244. if (!this._stateStored) {
  23245. return false;
  23246. }
  23247. this.fov = this._storedFov;
  23248. return true;
  23249. };
  23250. /**
  23251. * Restored camera state. You must call storeState() first.
  23252. * @returns true if restored and false otherwise
  23253. */
  23254. Camera.prototype.restoreState = function () {
  23255. if (this._restoreStateValues()) {
  23256. this.onRestoreStateObservable.notifyObservers(this);
  23257. return true;
  23258. }
  23259. return false;
  23260. };
  23261. /**
  23262. * Gets the class name of the camera.
  23263. * @returns the class name
  23264. */
  23265. Camera.prototype.getClassName = function () {
  23266. return "Camera";
  23267. };
  23268. /**
  23269. * Gets a string representation of the camera usefull for debug purpose.
  23270. * @param fullDetails Defines that a more verboe level of logging is required
  23271. * @returns the string representation
  23272. */
  23273. Camera.prototype.toString = function (fullDetails) {
  23274. var ret = "Name: " + this.name;
  23275. ret += ", type: " + this.getClassName();
  23276. if (this.animations) {
  23277. for (var i = 0; i < this.animations.length; i++) {
  23278. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23279. }
  23280. }
  23281. if (fullDetails) {
  23282. }
  23283. return ret;
  23284. };
  23285. Object.defineProperty(Camera.prototype, "globalPosition", {
  23286. /**
  23287. * Gets the current world space position of the camera.
  23288. */
  23289. get: function () {
  23290. return this._globalPosition;
  23291. },
  23292. enumerable: true,
  23293. configurable: true
  23294. });
  23295. /**
  23296. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23297. * @returns the active meshe list
  23298. */
  23299. Camera.prototype.getActiveMeshes = function () {
  23300. return this._activeMeshes;
  23301. };
  23302. /**
  23303. * Check wether a mesh is part of the current active mesh list of the camera
  23304. * @param mesh Defines the mesh to check
  23305. * @returns true if active, false otherwise
  23306. */
  23307. Camera.prototype.isActiveMesh = function (mesh) {
  23308. return (this._activeMeshes.indexOf(mesh) !== -1);
  23309. };
  23310. /**
  23311. * Is this camera ready to be used/rendered
  23312. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23313. * @return true if the camera is ready
  23314. */
  23315. Camera.prototype.isReady = function (completeCheck) {
  23316. if (completeCheck === void 0) { completeCheck = false; }
  23317. if (completeCheck) {
  23318. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23319. var pp = _a[_i];
  23320. if (pp && !pp.isReady()) {
  23321. return false;
  23322. }
  23323. }
  23324. }
  23325. return _super.prototype.isReady.call(this, completeCheck);
  23326. };
  23327. /** @hidden */
  23328. Camera.prototype._initCache = function () {
  23329. _super.prototype._initCache.call(this);
  23330. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23331. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23332. this._cache.mode = undefined;
  23333. this._cache.minZ = undefined;
  23334. this._cache.maxZ = undefined;
  23335. this._cache.fov = undefined;
  23336. this._cache.fovMode = undefined;
  23337. this._cache.aspectRatio = undefined;
  23338. this._cache.orthoLeft = undefined;
  23339. this._cache.orthoRight = undefined;
  23340. this._cache.orthoBottom = undefined;
  23341. this._cache.orthoTop = undefined;
  23342. this._cache.renderWidth = undefined;
  23343. this._cache.renderHeight = undefined;
  23344. };
  23345. /** @hidden */
  23346. Camera.prototype._updateCache = function (ignoreParentClass) {
  23347. if (!ignoreParentClass) {
  23348. _super.prototype._updateCache.call(this);
  23349. }
  23350. this._cache.position.copyFrom(this.position);
  23351. this._cache.upVector.copyFrom(this.upVector);
  23352. };
  23353. /** @hidden */
  23354. Camera.prototype._isSynchronized = function () {
  23355. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23356. };
  23357. /** @hidden */
  23358. Camera.prototype._isSynchronizedViewMatrix = function () {
  23359. if (!_super.prototype._isSynchronized.call(this))
  23360. return false;
  23361. return this._cache.position.equals(this.position)
  23362. && this._cache.upVector.equals(this.upVector)
  23363. && this.isSynchronizedWithParent();
  23364. };
  23365. /** @hidden */
  23366. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23367. var check = this._cache.mode === this.mode
  23368. && this._cache.minZ === this.minZ
  23369. && this._cache.maxZ === this.maxZ;
  23370. if (!check) {
  23371. return false;
  23372. }
  23373. var engine = this.getEngine();
  23374. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23375. check = this._cache.fov === this.fov
  23376. && this._cache.fovMode === this.fovMode
  23377. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23378. }
  23379. else {
  23380. check = this._cache.orthoLeft === this.orthoLeft
  23381. && this._cache.orthoRight === this.orthoRight
  23382. && this._cache.orthoBottom === this.orthoBottom
  23383. && this._cache.orthoTop === this.orthoTop
  23384. && this._cache.renderWidth === engine.getRenderWidth()
  23385. && this._cache.renderHeight === engine.getRenderHeight();
  23386. }
  23387. return check;
  23388. };
  23389. /**
  23390. * Attach the input controls to a specific dom element to get the input from.
  23391. * @param element Defines the element the controls should be listened from
  23392. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23393. */
  23394. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23395. };
  23396. /**
  23397. * Detach the current controls from the specified dom element.
  23398. * @param element Defines the element to stop listening the inputs from
  23399. */
  23400. Camera.prototype.detachControl = function (element) {
  23401. };
  23402. /**
  23403. * Update the camera state according to the different inputs gathered during the frame.
  23404. */
  23405. Camera.prototype.update = function () {
  23406. this._checkInputs();
  23407. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23408. this._updateRigCameras();
  23409. }
  23410. };
  23411. /** @hidden */
  23412. Camera.prototype._checkInputs = function () {
  23413. this.onAfterCheckInputsObservable.notifyObservers(this);
  23414. };
  23415. Object.defineProperty(Camera.prototype, "rigCameras", {
  23416. /** @hidden */
  23417. get: function () {
  23418. return this._rigCameras;
  23419. },
  23420. enumerable: true,
  23421. configurable: true
  23422. });
  23423. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23424. /**
  23425. * Gets the post process used by the rig cameras
  23426. */
  23427. get: function () {
  23428. return this._rigPostProcess;
  23429. },
  23430. enumerable: true,
  23431. configurable: true
  23432. });
  23433. /**
  23434. * Internal, gets the first post proces.
  23435. * @returns the first post process to be run on this camera.
  23436. */
  23437. Camera.prototype._getFirstPostProcess = function () {
  23438. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23439. if (this._postProcesses[ppIndex] !== null) {
  23440. return this._postProcesses[ppIndex];
  23441. }
  23442. }
  23443. return null;
  23444. };
  23445. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23446. // invalidate framebuffer
  23447. var firstPostProcess = this._getFirstPostProcess();
  23448. if (firstPostProcess) {
  23449. firstPostProcess.markTextureDirty();
  23450. }
  23451. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23452. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23453. var cam = this._rigCameras[i];
  23454. var rigPostProcess = cam._rigPostProcess;
  23455. // for VR rig, there does not have to be a post process
  23456. if (rigPostProcess) {
  23457. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23458. if (isPass) {
  23459. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23460. cam.isIntermediate = this._postProcesses.length === 0;
  23461. }
  23462. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23463. rigPostProcess.markTextureDirty();
  23464. }
  23465. else {
  23466. cam._postProcesses = this._postProcesses.slice(0);
  23467. }
  23468. }
  23469. };
  23470. /**
  23471. * Attach a post process to the camera.
  23472. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23473. * @param postProcess The post process to attach to the camera
  23474. * @param insertAt The position of the post process in case several of them are in use in the scene
  23475. * @returns the position the post process has been inserted at
  23476. */
  23477. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23478. if (insertAt === void 0) { insertAt = null; }
  23479. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23480. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23481. return 0;
  23482. }
  23483. if (insertAt == null || insertAt < 0) {
  23484. this._postProcesses.push(postProcess);
  23485. }
  23486. else if (this._postProcesses[insertAt] === null) {
  23487. this._postProcesses[insertAt] = postProcess;
  23488. }
  23489. else {
  23490. this._postProcesses.splice(insertAt, 0, postProcess);
  23491. }
  23492. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23493. return this._postProcesses.indexOf(postProcess);
  23494. };
  23495. /**
  23496. * Detach a post process to the camera.
  23497. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23498. * @param postProcess The post process to detach from the camera
  23499. */
  23500. Camera.prototype.detachPostProcess = function (postProcess) {
  23501. var idx = this._postProcesses.indexOf(postProcess);
  23502. if (idx !== -1) {
  23503. this._postProcesses[idx] = null;
  23504. }
  23505. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23506. };
  23507. /**
  23508. * Gets the current world matrix of the camera
  23509. */
  23510. Camera.prototype.getWorldMatrix = function () {
  23511. if (this._isSynchronizedViewMatrix()) {
  23512. return this._worldMatrix;
  23513. }
  23514. // Getting the the view matrix will also compute the world matrix.
  23515. this.getViewMatrix();
  23516. return this._worldMatrix;
  23517. };
  23518. /** @hidden */
  23519. Camera.prototype._getViewMatrix = function () {
  23520. return BABYLON.Matrix.Identity();
  23521. };
  23522. /**
  23523. * Gets the current view matrix of the camera.
  23524. * @param force forces the camera to recompute the matrix without looking at the cached state
  23525. * @returns the view matrix
  23526. */
  23527. Camera.prototype.getViewMatrix = function (force) {
  23528. if (!force && this._isSynchronizedViewMatrix()) {
  23529. return this._computedViewMatrix;
  23530. }
  23531. this.updateCache();
  23532. this._computedViewMatrix = this._getViewMatrix();
  23533. this._currentRenderId = this.getScene().getRenderId();
  23534. this._childRenderId = this._currentRenderId;
  23535. this._refreshFrustumPlanes = true;
  23536. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23537. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23538. }
  23539. this.onViewMatrixChangedObservable.notifyObservers(this);
  23540. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23541. return this._computedViewMatrix;
  23542. };
  23543. /**
  23544. * Freeze the projection matrix.
  23545. * It will prevent the cache check of the camera projection compute and can speed up perf
  23546. * if no parameter of the camera are meant to change
  23547. * @param projection Defines manually a projection if necessary
  23548. */
  23549. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23550. this._doNotComputeProjectionMatrix = true;
  23551. if (projection !== undefined) {
  23552. this._projectionMatrix = projection;
  23553. }
  23554. };
  23555. ;
  23556. /**
  23557. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23558. */
  23559. Camera.prototype.unfreezeProjectionMatrix = function () {
  23560. this._doNotComputeProjectionMatrix = false;
  23561. };
  23562. ;
  23563. /**
  23564. * Gets the current projection matrix of the camera.
  23565. * @param force forces the camera to recompute the matrix without looking at the cached state
  23566. * @returns the projection matrix
  23567. */
  23568. Camera.prototype.getProjectionMatrix = function (force) {
  23569. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23570. return this._projectionMatrix;
  23571. }
  23572. // Cache
  23573. this._cache.mode = this.mode;
  23574. this._cache.minZ = this.minZ;
  23575. this._cache.maxZ = this.maxZ;
  23576. // Matrix
  23577. this._refreshFrustumPlanes = true;
  23578. var engine = this.getEngine();
  23579. var scene = this.getScene();
  23580. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23581. this._cache.fov = this.fov;
  23582. this._cache.fovMode = this.fovMode;
  23583. this._cache.aspectRatio = engine.getAspectRatio(this);
  23584. if (this.minZ <= 0) {
  23585. this.minZ = 0.1;
  23586. }
  23587. if (scene.useRightHandedSystem) {
  23588. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23589. }
  23590. else {
  23591. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23592. }
  23593. }
  23594. else {
  23595. var halfWidth = engine.getRenderWidth() / 2.0;
  23596. var halfHeight = engine.getRenderHeight() / 2.0;
  23597. if (scene.useRightHandedSystem) {
  23598. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23599. }
  23600. else {
  23601. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23602. }
  23603. this._cache.orthoLeft = this.orthoLeft;
  23604. this._cache.orthoRight = this.orthoRight;
  23605. this._cache.orthoBottom = this.orthoBottom;
  23606. this._cache.orthoTop = this.orthoTop;
  23607. this._cache.renderWidth = engine.getRenderWidth();
  23608. this._cache.renderHeight = engine.getRenderHeight();
  23609. }
  23610. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23611. return this._projectionMatrix;
  23612. };
  23613. /**
  23614. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23615. * @returns a Matrix
  23616. */
  23617. Camera.prototype.getTransformationMatrix = function () {
  23618. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23619. return this._transformMatrix;
  23620. };
  23621. Camera.prototype._updateFrustumPlanes = function () {
  23622. if (!this._refreshFrustumPlanes) {
  23623. return;
  23624. }
  23625. this.getTransformationMatrix();
  23626. if (!this._frustumPlanes) {
  23627. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23628. }
  23629. else {
  23630. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23631. }
  23632. this._refreshFrustumPlanes = false;
  23633. };
  23634. /**
  23635. * Checks if a cullable object (mesh...) is in the camera frustum
  23636. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23637. * @param target The object to check
  23638. * @returns true if the object is in frustum otherwise false
  23639. */
  23640. Camera.prototype.isInFrustum = function (target) {
  23641. this._updateFrustumPlanes();
  23642. return target.isInFrustum(this._frustumPlanes);
  23643. };
  23644. /**
  23645. * Checks if a cullable object (mesh...) is in the camera frustum
  23646. * Unlike isInFrustum this cheks the full bounding box
  23647. * @param target The object to check
  23648. * @returns true if the object is in frustum otherwise false
  23649. */
  23650. Camera.prototype.isCompletelyInFrustum = function (target) {
  23651. this._updateFrustumPlanes();
  23652. return target.isCompletelyInFrustum(this._frustumPlanes);
  23653. };
  23654. /**
  23655. * Gets a ray in the forward direction from the camera.
  23656. * @param length Defines the length of the ray to create
  23657. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23658. * @param origin Defines the start point of the ray which defaults to the camera position
  23659. * @returns the forward ray
  23660. */
  23661. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23662. if (length === void 0) { length = 100; }
  23663. if (!transform) {
  23664. transform = this.getWorldMatrix();
  23665. }
  23666. if (!origin) {
  23667. origin = this.position;
  23668. }
  23669. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23670. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23671. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23672. return new BABYLON.Ray(origin, direction, length);
  23673. };
  23674. /**
  23675. * Releases resources associated with this node.
  23676. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23677. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23678. */
  23679. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23680. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23681. // Observables
  23682. this.onViewMatrixChangedObservable.clear();
  23683. this.onProjectionMatrixChangedObservable.clear();
  23684. this.onAfterCheckInputsObservable.clear();
  23685. this.onRestoreStateObservable.clear();
  23686. // Inputs
  23687. if (this.inputs) {
  23688. this.inputs.clear();
  23689. }
  23690. // Animations
  23691. this.getScene().stopAnimation(this);
  23692. // Remove from scene
  23693. this.getScene().removeCamera(this);
  23694. while (this._rigCameras.length > 0) {
  23695. var camera = this._rigCameras.pop();
  23696. if (camera) {
  23697. camera.dispose();
  23698. }
  23699. }
  23700. // Postprocesses
  23701. if (this._rigPostProcess) {
  23702. this._rigPostProcess.dispose(this);
  23703. this._rigPostProcess = null;
  23704. this._postProcesses = [];
  23705. }
  23706. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23707. this._rigPostProcess = null;
  23708. this._postProcesses = [];
  23709. }
  23710. else {
  23711. var i = this._postProcesses.length;
  23712. while (--i >= 0) {
  23713. var postProcess = this._postProcesses[i];
  23714. if (postProcess) {
  23715. postProcess.dispose(this);
  23716. }
  23717. }
  23718. }
  23719. // Render targets
  23720. var i = this.customRenderTargets.length;
  23721. while (--i >= 0) {
  23722. this.customRenderTargets[i].dispose();
  23723. }
  23724. this.customRenderTargets = [];
  23725. // Active Meshes
  23726. this._activeMeshes.dispose();
  23727. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23728. };
  23729. Object.defineProperty(Camera.prototype, "leftCamera", {
  23730. /**
  23731. * Gets the left camera of a rig setup in case of Rigged Camera
  23732. */
  23733. get: function () {
  23734. if (this._rigCameras.length < 1) {
  23735. return null;
  23736. }
  23737. return this._rigCameras[0];
  23738. },
  23739. enumerable: true,
  23740. configurable: true
  23741. });
  23742. Object.defineProperty(Camera.prototype, "rightCamera", {
  23743. /**
  23744. * Gets the right camera of a rig setup in case of Rigged Camera
  23745. */
  23746. get: function () {
  23747. if (this._rigCameras.length < 2) {
  23748. return null;
  23749. }
  23750. return this._rigCameras[1];
  23751. },
  23752. enumerable: true,
  23753. configurable: true
  23754. });
  23755. /**
  23756. * Gets the left camera target of a rig setup in case of Rigged Camera
  23757. * @returns the target position
  23758. */
  23759. Camera.prototype.getLeftTarget = function () {
  23760. if (this._rigCameras.length < 1) {
  23761. return null;
  23762. }
  23763. return this._rigCameras[0].getTarget();
  23764. };
  23765. /**
  23766. * Gets the right camera target of a rig setup in case of Rigged Camera
  23767. * @returns the target position
  23768. */
  23769. Camera.prototype.getRightTarget = function () {
  23770. if (this._rigCameras.length < 2) {
  23771. return null;
  23772. }
  23773. return this._rigCameras[1].getTarget();
  23774. };
  23775. /**
  23776. * @hidden
  23777. */
  23778. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23779. if (this.cameraRigMode === mode) {
  23780. return;
  23781. }
  23782. while (this._rigCameras.length > 0) {
  23783. var camera = this._rigCameras.pop();
  23784. if (camera) {
  23785. camera.dispose();
  23786. }
  23787. }
  23788. this.cameraRigMode = mode;
  23789. this._cameraRigParams = {};
  23790. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23791. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23792. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23793. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23794. // create the rig cameras, unless none
  23795. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23796. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23797. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23798. if (leftCamera && rightCamera) {
  23799. this._rigCameras.push(leftCamera);
  23800. this._rigCameras.push(rightCamera);
  23801. }
  23802. }
  23803. switch (this.cameraRigMode) {
  23804. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23805. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23806. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23807. break;
  23808. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23809. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23810. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23811. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23812. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23813. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23814. break;
  23815. case Camera.RIG_MODE_VR:
  23816. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23817. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23818. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23819. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23820. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23821. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23822. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23823. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23824. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23825. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23826. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23827. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23828. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23829. if (metrics.compensateDistortion) {
  23830. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23831. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23832. }
  23833. break;
  23834. case Camera.RIG_MODE_WEBVR:
  23835. if (rigParams.vrDisplay) {
  23836. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23837. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23838. //Left eye
  23839. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23840. this._rigCameras[0].setCameraRigParameter("left", true);
  23841. //leaving this for future reference
  23842. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23843. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23844. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23845. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23846. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23847. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23848. this._rigCameras[0].parent = this;
  23849. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23850. //Right eye
  23851. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23852. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23853. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23854. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23855. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23856. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23857. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23858. this._rigCameras[1].parent = this;
  23859. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23860. if (Camera.UseAlternateWebVRRendering) {
  23861. this._rigCameras[1]._skipRendering = true;
  23862. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23863. }
  23864. }
  23865. break;
  23866. }
  23867. this._cascadePostProcessesToRigCams();
  23868. this.update();
  23869. };
  23870. Camera.prototype._getVRProjectionMatrix = function () {
  23871. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23872. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23873. return this._projectionMatrix;
  23874. };
  23875. Camera.prototype._updateCameraRotationMatrix = function () {
  23876. //Here for WebVR
  23877. };
  23878. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23879. //Here for WebVR
  23880. };
  23881. /**
  23882. * This function MUST be overwritten by the different WebVR cameras available.
  23883. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23884. */
  23885. Camera.prototype._getWebVRProjectionMatrix = function () {
  23886. return BABYLON.Matrix.Identity();
  23887. };
  23888. /**
  23889. * This function MUST be overwritten by the different WebVR cameras available.
  23890. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23891. */
  23892. Camera.prototype._getWebVRViewMatrix = function () {
  23893. return BABYLON.Matrix.Identity();
  23894. };
  23895. /** @hidden */
  23896. Camera.prototype.setCameraRigParameter = function (name, value) {
  23897. if (!this._cameraRigParams) {
  23898. this._cameraRigParams = {};
  23899. }
  23900. this._cameraRigParams[name] = value;
  23901. //provisionnally:
  23902. if (name === "interaxialDistance") {
  23903. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23904. }
  23905. };
  23906. /**
  23907. * needs to be overridden by children so sub has required properties to be copied
  23908. * @hidden
  23909. */
  23910. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23911. return null;
  23912. };
  23913. /**
  23914. * May need to be overridden by children
  23915. * @hidden
  23916. */
  23917. Camera.prototype._updateRigCameras = function () {
  23918. for (var i = 0; i < this._rigCameras.length; i++) {
  23919. this._rigCameras[i].minZ = this.minZ;
  23920. this._rigCameras[i].maxZ = this.maxZ;
  23921. this._rigCameras[i].fov = this.fov;
  23922. }
  23923. // only update viewport when ANAGLYPH
  23924. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23925. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23926. }
  23927. };
  23928. /** @hidden */
  23929. Camera.prototype._setupInputs = function () {
  23930. };
  23931. /**
  23932. * Serialiaze the camera setup to a json represention
  23933. * @returns the JSON representation
  23934. */
  23935. Camera.prototype.serialize = function () {
  23936. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23937. // Type
  23938. serializationObject.type = this.getClassName();
  23939. // Parent
  23940. if (this.parent) {
  23941. serializationObject.parentId = this.parent.id;
  23942. }
  23943. if (this.inputs) {
  23944. this.inputs.serialize(serializationObject);
  23945. }
  23946. // Animations
  23947. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23948. serializationObject.ranges = this.serializeAnimationRanges();
  23949. return serializationObject;
  23950. };
  23951. /**
  23952. * Clones the current camera.
  23953. * @param name The cloned camera name
  23954. * @returns the cloned camera
  23955. */
  23956. Camera.prototype.clone = function (name) {
  23957. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23958. };
  23959. /**
  23960. * Gets the direction of the camera relative to a given local axis.
  23961. * @param localAxis Defines the reference axis to provide a relative direction.
  23962. * @return the direction
  23963. */
  23964. Camera.prototype.getDirection = function (localAxis) {
  23965. var result = BABYLON.Vector3.Zero();
  23966. this.getDirectionToRef(localAxis, result);
  23967. return result;
  23968. };
  23969. /**
  23970. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23971. * @param localAxis Defines the reference axis to provide a relative direction.
  23972. * @param result Defines the vector to store the result in
  23973. */
  23974. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23975. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23976. };
  23977. /**
  23978. * Gets a camera constructor for a given camera type
  23979. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  23980. * @param name The name of the camera the result will be able to instantiate
  23981. * @param scene The scene the result will construct the camera in
  23982. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  23983. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  23984. * @returns a factory method to construc the camera
  23985. */
  23986. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23987. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23988. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23989. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  23990. interaxial_distance: interaxial_distance,
  23991. isStereoscopicSideBySide: isStereoscopicSideBySide
  23992. });
  23993. if (constructorFunc) {
  23994. return constructorFunc;
  23995. }
  23996. // Default to universal camera
  23997. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23998. };
  23999. /**
  24000. * Compute the world matrix of the camera.
  24001. * @returns the camera workd matrix
  24002. */
  24003. Camera.prototype.computeWorldMatrix = function () {
  24004. return this.getWorldMatrix();
  24005. };
  24006. /**
  24007. * Parse a JSON and creates the camera from the parsed information
  24008. * @param parsedCamera The JSON to parse
  24009. * @param scene The scene to instantiate the camera in
  24010. * @returns the newly constructed camera
  24011. */
  24012. Camera.Parse = function (parsedCamera, scene) {
  24013. var type = parsedCamera.type;
  24014. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24015. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24016. // Parent
  24017. if (parsedCamera.parentId) {
  24018. camera._waitingParentId = parsedCamera.parentId;
  24019. }
  24020. //If camera has an input manager, let it parse inputs settings
  24021. if (camera.inputs) {
  24022. camera.inputs.parse(parsedCamera);
  24023. camera._setupInputs();
  24024. }
  24025. if (camera.setPosition) { // need to force position
  24026. camera.position.copyFromFloats(0, 0, 0);
  24027. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24028. }
  24029. // Target
  24030. if (parsedCamera.target) {
  24031. if (camera.setTarget) {
  24032. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24033. }
  24034. }
  24035. // Apply 3d rig, when found
  24036. if (parsedCamera.cameraRigMode) {
  24037. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24038. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24039. }
  24040. // Animations
  24041. if (parsedCamera.animations) {
  24042. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24043. var parsedAnimation = parsedCamera.animations[animationIndex];
  24044. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24045. }
  24046. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24047. }
  24048. if (parsedCamera.autoAnimate) {
  24049. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24050. }
  24051. return camera;
  24052. };
  24053. /**
  24054. * This is the default projection mode used by the cameras.
  24055. * It helps recreating a feeling of perspective and better appreciate depth.
  24056. * This is the best way to simulate real life cameras.
  24057. */
  24058. Camera.PERSPECTIVE_CAMERA = 0;
  24059. /**
  24060. * This helps creating camera with an orthographic mode.
  24061. * 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.
  24062. */
  24063. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24064. /**
  24065. * This is the default FOV mode for perspective cameras.
  24066. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24067. */
  24068. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24069. /**
  24070. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24071. */
  24072. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24073. /**
  24074. * This specifies ther is no need for a camera rig.
  24075. * Basically only one eye is rendered corresponding to the camera.
  24076. */
  24077. Camera.RIG_MODE_NONE = 0;
  24078. /**
  24079. * Simulates a camera Rig with one blue eye and one red eye.
  24080. * This can be use with 3d blue and red glasses.
  24081. */
  24082. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24083. /**
  24084. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24085. */
  24086. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24087. /**
  24088. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24089. */
  24090. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24091. /**
  24092. * Defines that both eyes of the camera will be rendered over under each other.
  24093. */
  24094. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24095. /**
  24096. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24097. */
  24098. Camera.RIG_MODE_VR = 20;
  24099. /**
  24100. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24101. */
  24102. Camera.RIG_MODE_WEBVR = 21;
  24103. /**
  24104. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24105. */
  24106. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24107. /**
  24108. * @hidden
  24109. * Might be removed once multiview will be a thing
  24110. */
  24111. Camera.UseAlternateWebVRRendering = false;
  24112. __decorate([
  24113. BABYLON.serializeAsVector3()
  24114. ], Camera.prototype, "position", void 0);
  24115. __decorate([
  24116. BABYLON.serializeAsVector3()
  24117. ], Camera.prototype, "upVector", void 0);
  24118. __decorate([
  24119. BABYLON.serialize()
  24120. ], Camera.prototype, "orthoLeft", void 0);
  24121. __decorate([
  24122. BABYLON.serialize()
  24123. ], Camera.prototype, "orthoRight", void 0);
  24124. __decorate([
  24125. BABYLON.serialize()
  24126. ], Camera.prototype, "orthoBottom", void 0);
  24127. __decorate([
  24128. BABYLON.serialize()
  24129. ], Camera.prototype, "orthoTop", void 0);
  24130. __decorate([
  24131. BABYLON.serialize()
  24132. ], Camera.prototype, "fov", void 0);
  24133. __decorate([
  24134. BABYLON.serialize()
  24135. ], Camera.prototype, "minZ", void 0);
  24136. __decorate([
  24137. BABYLON.serialize()
  24138. ], Camera.prototype, "maxZ", void 0);
  24139. __decorate([
  24140. BABYLON.serialize()
  24141. ], Camera.prototype, "inertia", void 0);
  24142. __decorate([
  24143. BABYLON.serialize()
  24144. ], Camera.prototype, "mode", void 0);
  24145. __decorate([
  24146. BABYLON.serialize()
  24147. ], Camera.prototype, "layerMask", void 0);
  24148. __decorate([
  24149. BABYLON.serialize()
  24150. ], Camera.prototype, "fovMode", void 0);
  24151. __decorate([
  24152. BABYLON.serialize()
  24153. ], Camera.prototype, "cameraRigMode", void 0);
  24154. __decorate([
  24155. BABYLON.serialize()
  24156. ], Camera.prototype, "interaxialDistance", void 0);
  24157. __decorate([
  24158. BABYLON.serialize()
  24159. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24160. return Camera;
  24161. }(BABYLON.Node));
  24162. BABYLON.Camera = Camera;
  24163. })(BABYLON || (BABYLON = {}));
  24164. //# sourceMappingURL=babylon.camera.js.map
  24165. var BABYLON;
  24166. (function (BABYLON) {
  24167. /**
  24168. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24169. * It is enable to manage the different groups as well as the different necessary sort functions.
  24170. * This should not be used directly aside of the few static configurations
  24171. */
  24172. var RenderingManager = /** @class */ (function () {
  24173. /**
  24174. * Instantiates a new rendering group for a particular scene
  24175. * @param scene Defines the scene the groups belongs to
  24176. */
  24177. function RenderingManager(scene) {
  24178. /**
  24179. * @hidden
  24180. */
  24181. this._useSceneAutoClearSetup = false;
  24182. this._renderingGroups = new Array();
  24183. this._autoClearDepthStencil = {};
  24184. this._customOpaqueSortCompareFn = {};
  24185. this._customAlphaTestSortCompareFn = {};
  24186. this._customTransparentSortCompareFn = {};
  24187. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24188. this._scene = scene;
  24189. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24190. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24191. }
  24192. }
  24193. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24194. if (depth === void 0) { depth = true; }
  24195. if (stencil === void 0) { stencil = true; }
  24196. if (this._depthStencilBufferAlreadyCleaned) {
  24197. return;
  24198. }
  24199. this._scene.getEngine().clear(null, false, depth, stencil);
  24200. this._depthStencilBufferAlreadyCleaned = true;
  24201. };
  24202. /**
  24203. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24204. * @hidden
  24205. */
  24206. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24207. // Update the observable context (not null as it only goes away on dispose)
  24208. var info = this._renderingGroupInfo;
  24209. info.scene = this._scene;
  24210. info.camera = this._scene.activeCamera;
  24211. // Dispatch sprites
  24212. if (this._scene.spriteManagers && renderSprites) {
  24213. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24214. var manager = this._scene.spriteManagers[index];
  24215. this.dispatchSprites(manager);
  24216. }
  24217. }
  24218. // Render
  24219. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24220. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24221. var renderingGroup = this._renderingGroups[index];
  24222. if (!renderingGroup)
  24223. continue;
  24224. var renderingGroupMask = Math.pow(2, index);
  24225. info.renderingGroupId = index;
  24226. // Before Observable
  24227. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24228. // Clear depth/stencil if needed
  24229. if (RenderingManager.AUTOCLEAR) {
  24230. var autoClear = this._useSceneAutoClearSetup ?
  24231. this._scene.getAutoClearDepthStencilSetup(index) :
  24232. this._autoClearDepthStencil[index];
  24233. if (autoClear && autoClear.autoClear) {
  24234. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24235. }
  24236. }
  24237. // Render
  24238. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24239. var step = _a[_i];
  24240. step.action(index);
  24241. }
  24242. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24243. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24244. var step = _c[_b];
  24245. step.action(index);
  24246. }
  24247. // After Observable
  24248. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24249. }
  24250. };
  24251. /**
  24252. * Resets the different information of the group to prepare a new frame
  24253. * @hidden
  24254. */
  24255. RenderingManager.prototype.reset = function () {
  24256. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24257. var renderingGroup = this._renderingGroups[index];
  24258. if (renderingGroup) {
  24259. renderingGroup.prepare();
  24260. }
  24261. }
  24262. };
  24263. /**
  24264. * Dispose and release the group and its associated resources.
  24265. * @hidden
  24266. */
  24267. RenderingManager.prototype.dispose = function () {
  24268. this.freeRenderingGroups();
  24269. this._renderingGroups.length = 0;
  24270. this._renderingGroupInfo = null;
  24271. };
  24272. /**
  24273. * Clear the info related to rendering groups preventing retention points during dispose.
  24274. */
  24275. RenderingManager.prototype.freeRenderingGroups = function () {
  24276. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24277. var renderingGroup = this._renderingGroups[index];
  24278. if (renderingGroup) {
  24279. renderingGroup.dispose();
  24280. }
  24281. }
  24282. };
  24283. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24284. if (this._renderingGroups[renderingGroupId] === undefined) {
  24285. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24286. }
  24287. };
  24288. /**
  24289. * Add a sprite manager to the rendering manager in order to render it this frame.
  24290. * @param spriteManager Define the sprite manager to render
  24291. */
  24292. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24293. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24294. this._prepareRenderingGroup(renderingGroupId);
  24295. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24296. };
  24297. /**
  24298. * Add a particle system to the rendering manager in order to render it this frame.
  24299. * @param particleSystem Define the particle system to render
  24300. */
  24301. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24302. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24303. this._prepareRenderingGroup(renderingGroupId);
  24304. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24305. };
  24306. /**
  24307. * Add a submesh to the manager in order to render it this frame
  24308. * @param subMesh The submesh to dispatch
  24309. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24310. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24311. */
  24312. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24313. if (mesh === undefined) {
  24314. mesh = subMesh.getMesh();
  24315. }
  24316. var renderingGroupId = mesh.renderingGroupId || 0;
  24317. this._prepareRenderingGroup(renderingGroupId);
  24318. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24319. };
  24320. /**
  24321. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24322. * This allowed control for front to back rendering or reversly depending of the special needs.
  24323. *
  24324. * @param renderingGroupId The rendering group id corresponding to its index
  24325. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24326. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24327. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24328. */
  24329. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24330. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24331. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24332. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24333. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24334. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24335. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24336. if (this._renderingGroups[renderingGroupId]) {
  24337. var group = this._renderingGroups[renderingGroupId];
  24338. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24339. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24340. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24341. }
  24342. };
  24343. /**
  24344. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24345. *
  24346. * @param renderingGroupId The rendering group id corresponding to its index
  24347. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24348. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24349. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24350. */
  24351. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24352. if (depth === void 0) { depth = true; }
  24353. if (stencil === void 0) { stencil = true; }
  24354. this._autoClearDepthStencil[renderingGroupId] = {
  24355. autoClear: autoClearDepthStencil,
  24356. depth: depth,
  24357. stencil: stencil
  24358. };
  24359. };
  24360. /**
  24361. * Gets the current auto clear configuration for one rendering group of the rendering
  24362. * manager.
  24363. * @param index the rendering group index to get the information for
  24364. * @returns The auto clear setup for the requested rendering group
  24365. */
  24366. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24367. return this._autoClearDepthStencil[index];
  24368. };
  24369. /**
  24370. * The max id used for rendering groups (not included)
  24371. */
  24372. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24373. /**
  24374. * The min id used for rendering groups (included)
  24375. */
  24376. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24377. /**
  24378. * Used to globally prevent autoclearing scenes.
  24379. */
  24380. RenderingManager.AUTOCLEAR = true;
  24381. return RenderingManager;
  24382. }());
  24383. BABYLON.RenderingManager = RenderingManager;
  24384. })(BABYLON || (BABYLON = {}));
  24385. //# sourceMappingURL=babylon.renderingManager.js.map
  24386. var BABYLON;
  24387. (function (BABYLON) {
  24388. /**
  24389. * This represents the object necessary to create a rendering group.
  24390. * This is exclusively used and created by the rendering manager.
  24391. * To modify the behavior, you use the available helpers in your scene or meshes.
  24392. * @hidden
  24393. */
  24394. var RenderingGroup = /** @class */ (function () {
  24395. /**
  24396. * Creates a new rendering group.
  24397. * @param index The rendering group index
  24398. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24399. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24400. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24401. */
  24402. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24403. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24404. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24405. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24406. this.index = index;
  24407. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24408. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24409. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24410. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24411. this._particleSystems = new BABYLON.SmartArray(256);
  24412. this._spriteManagers = new BABYLON.SmartArray(256);
  24413. this._edgesRenderers = new BABYLON.SmartArray(16);
  24414. this._scene = scene;
  24415. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24416. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24417. this.transparentSortCompareFn = transparentSortCompareFn;
  24418. }
  24419. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24420. /**
  24421. * Set the opaque sort comparison function.
  24422. * If null the sub meshes will be render in the order they were created
  24423. */
  24424. set: function (value) {
  24425. this._opaqueSortCompareFn = value;
  24426. if (value) {
  24427. this._renderOpaque = this.renderOpaqueSorted;
  24428. }
  24429. else {
  24430. this._renderOpaque = RenderingGroup.renderUnsorted;
  24431. }
  24432. },
  24433. enumerable: true,
  24434. configurable: true
  24435. });
  24436. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24437. /**
  24438. * Set the alpha test sort comparison function.
  24439. * If null the sub meshes will be render in the order they were created
  24440. */
  24441. set: function (value) {
  24442. this._alphaTestSortCompareFn = value;
  24443. if (value) {
  24444. this._renderAlphaTest = this.renderAlphaTestSorted;
  24445. }
  24446. else {
  24447. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24448. }
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24454. /**
  24455. * Set the transparent sort comparison function.
  24456. * If null the sub meshes will be render in the order they were created
  24457. */
  24458. set: function (value) {
  24459. if (value) {
  24460. this._transparentSortCompareFn = value;
  24461. }
  24462. else {
  24463. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24464. }
  24465. this._renderTransparent = this.renderTransparentSorted;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. /**
  24471. * Render all the sub meshes contained in the group.
  24472. * @param customRenderFunction Used to override the default render behaviour of the group.
  24473. * @returns true if rendered some submeshes.
  24474. */
  24475. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24476. if (customRenderFunction) {
  24477. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24478. return;
  24479. }
  24480. var engine = this._scene.getEngine();
  24481. // Depth only
  24482. if (this._depthOnlySubMeshes.length !== 0) {
  24483. engine.setColorWrite(false);
  24484. this._renderAlphaTest(this._depthOnlySubMeshes);
  24485. engine.setColorWrite(true);
  24486. }
  24487. // Opaque
  24488. if (this._opaqueSubMeshes.length !== 0) {
  24489. this._renderOpaque(this._opaqueSubMeshes);
  24490. }
  24491. // Alpha test
  24492. if (this._alphaTestSubMeshes.length !== 0) {
  24493. this._renderAlphaTest(this._alphaTestSubMeshes);
  24494. }
  24495. var stencilState = engine.getStencilBuffer();
  24496. engine.setStencilBuffer(false);
  24497. // Sprites
  24498. if (renderSprites) {
  24499. this._renderSprites();
  24500. }
  24501. // Particles
  24502. if (renderParticles) {
  24503. this._renderParticles(activeMeshes);
  24504. }
  24505. if (this.onBeforeTransparentRendering) {
  24506. this.onBeforeTransparentRendering();
  24507. }
  24508. // Transparent
  24509. if (this._transparentSubMeshes.length !== 0) {
  24510. this._renderTransparent(this._transparentSubMeshes);
  24511. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24512. }
  24513. // Set back stencil to false in case it changes before the edge renderer.
  24514. engine.setStencilBuffer(false);
  24515. // Edges
  24516. if (this._edgesRenderers.length) {
  24517. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24518. this._edgesRenderers.data[edgesRendererIndex].render();
  24519. }
  24520. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24521. }
  24522. // Restore Stencil state.
  24523. engine.setStencilBuffer(stencilState);
  24524. };
  24525. /**
  24526. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24527. * @param subMeshes The submeshes to render
  24528. */
  24529. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24530. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24531. };
  24532. /**
  24533. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24534. * @param subMeshes The submeshes to render
  24535. */
  24536. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24537. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24538. };
  24539. /**
  24540. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24541. * @param subMeshes The submeshes to render
  24542. */
  24543. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24544. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24545. };
  24546. /**
  24547. * Renders the submeshes in a specified order.
  24548. * @param subMeshes The submeshes to sort before render
  24549. * @param sortCompareFn The comparison function use to sort
  24550. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24551. * @param transparent Specifies to activate blending if true
  24552. */
  24553. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24554. var subIndex = 0;
  24555. var subMesh;
  24556. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24557. for (; subIndex < subMeshes.length; subIndex++) {
  24558. subMesh = subMeshes.data[subIndex];
  24559. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24560. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24561. }
  24562. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24563. if (sortCompareFn) {
  24564. sortedArray.sort(sortCompareFn);
  24565. }
  24566. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24567. subMesh = sortedArray[subIndex];
  24568. if (transparent) {
  24569. var material = subMesh.getMaterial();
  24570. if (material && material.needDepthPrePass) {
  24571. var engine = material.getScene().getEngine();
  24572. engine.setColorWrite(false);
  24573. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24574. subMesh.render(false);
  24575. engine.setColorWrite(true);
  24576. }
  24577. }
  24578. subMesh.render(transparent);
  24579. }
  24580. };
  24581. /**
  24582. * Renders the submeshes in the order they were dispatched (no sort applied).
  24583. * @param subMeshes The submeshes to render
  24584. */
  24585. RenderingGroup.renderUnsorted = function (subMeshes) {
  24586. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24587. var submesh = subMeshes.data[subIndex];
  24588. submesh.render(false);
  24589. }
  24590. };
  24591. /**
  24592. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24593. * are rendered back to front if in the same alpha index.
  24594. *
  24595. * @param a The first submesh
  24596. * @param b The second submesh
  24597. * @returns The result of the comparison
  24598. */
  24599. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24600. // Alpha index first
  24601. if (a._alphaIndex > b._alphaIndex) {
  24602. return 1;
  24603. }
  24604. if (a._alphaIndex < b._alphaIndex) {
  24605. return -1;
  24606. }
  24607. // Then distance to camera
  24608. return RenderingGroup.backToFrontSortCompare(a, b);
  24609. };
  24610. /**
  24611. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24612. * are rendered back to front.
  24613. *
  24614. * @param a The first submesh
  24615. * @param b The second submesh
  24616. * @returns The result of the comparison
  24617. */
  24618. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24619. // Then distance to camera
  24620. if (a._distanceToCamera < b._distanceToCamera) {
  24621. return 1;
  24622. }
  24623. if (a._distanceToCamera > b._distanceToCamera) {
  24624. return -1;
  24625. }
  24626. return 0;
  24627. };
  24628. /**
  24629. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24630. * are rendered front to back (prevent overdraw).
  24631. *
  24632. * @param a The first submesh
  24633. * @param b The second submesh
  24634. * @returns The result of the comparison
  24635. */
  24636. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24637. // Then distance to camera
  24638. if (a._distanceToCamera < b._distanceToCamera) {
  24639. return -1;
  24640. }
  24641. if (a._distanceToCamera > b._distanceToCamera) {
  24642. return 1;
  24643. }
  24644. return 0;
  24645. };
  24646. /**
  24647. * Resets the different lists of submeshes to prepare a new frame.
  24648. */
  24649. RenderingGroup.prototype.prepare = function () {
  24650. this._opaqueSubMeshes.reset();
  24651. this._transparentSubMeshes.reset();
  24652. this._alphaTestSubMeshes.reset();
  24653. this._depthOnlySubMeshes.reset();
  24654. this._particleSystems.reset();
  24655. this._spriteManagers.reset();
  24656. this._edgesRenderers.reset();
  24657. };
  24658. RenderingGroup.prototype.dispose = function () {
  24659. this._opaqueSubMeshes.dispose();
  24660. this._transparentSubMeshes.dispose();
  24661. this._alphaTestSubMeshes.dispose();
  24662. this._depthOnlySubMeshes.dispose();
  24663. this._particleSystems.dispose();
  24664. this._spriteManagers.dispose();
  24665. this._edgesRenderers.dispose();
  24666. };
  24667. /**
  24668. * Inserts the submesh in its correct queue depending on its material.
  24669. * @param subMesh The submesh to dispatch
  24670. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24671. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24672. */
  24673. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24674. // Get mesh and materials if not provided
  24675. if (mesh === undefined) {
  24676. mesh = subMesh.getMesh();
  24677. }
  24678. if (material === undefined) {
  24679. material = subMesh.getMaterial();
  24680. }
  24681. if (material === null || material === undefined) {
  24682. return;
  24683. }
  24684. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24685. this._transparentSubMeshes.push(subMesh);
  24686. }
  24687. else if (material.needAlphaTesting()) { // Alpha test
  24688. if (material.needDepthPrePass) {
  24689. this._depthOnlySubMeshes.push(subMesh);
  24690. }
  24691. this._alphaTestSubMeshes.push(subMesh);
  24692. }
  24693. else {
  24694. if (material.needDepthPrePass) {
  24695. this._depthOnlySubMeshes.push(subMesh);
  24696. }
  24697. this._opaqueSubMeshes.push(subMesh); // Opaque
  24698. }
  24699. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24700. this._edgesRenderers.push(mesh._edgesRenderer);
  24701. }
  24702. };
  24703. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24704. this._spriteManagers.push(spriteManager);
  24705. };
  24706. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24707. this._particleSystems.push(particleSystem);
  24708. };
  24709. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24710. if (this._particleSystems.length === 0) {
  24711. return;
  24712. }
  24713. // Particles
  24714. var activeCamera = this._scene.activeCamera;
  24715. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24716. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24717. var particleSystem = this._particleSystems.data[particleIndex];
  24718. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24719. continue;
  24720. }
  24721. var emitter = particleSystem.emitter;
  24722. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24723. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24724. }
  24725. }
  24726. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24727. };
  24728. RenderingGroup.prototype._renderSprites = function () {
  24729. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24730. return;
  24731. }
  24732. // Sprites
  24733. var activeCamera = this._scene.activeCamera;
  24734. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24735. for (var id = 0; id < this._spriteManagers.length; id++) {
  24736. var spriteManager = this._spriteManagers.data[id];
  24737. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24738. spriteManager.render();
  24739. }
  24740. }
  24741. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24742. };
  24743. return RenderingGroup;
  24744. }());
  24745. BABYLON.RenderingGroup = RenderingGroup;
  24746. })(BABYLON || (BABYLON = {}));
  24747. //# sourceMappingURL=babylon.renderingGroup.js.map
  24748. var BABYLON;
  24749. (function (BABYLON) {
  24750. /**
  24751. * Groups all the scene component constants in one place to ease maintenance.
  24752. * @hidden
  24753. */
  24754. var SceneComponentConstants = /** @class */ (function () {
  24755. function SceneComponentConstants() {
  24756. }
  24757. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24758. SceneComponentConstants.NAME_LAYER = "Layer";
  24759. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24760. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24761. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24762. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24763. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24764. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24765. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24766. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24767. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24768. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24769. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24770. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24771. SceneComponentConstants.NAME_OCTREE = "Octree";
  24772. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24773. SceneComponentConstants.NAME_AUDIO = "Audio";
  24774. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24775. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24776. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24777. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24778. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24779. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24780. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24781. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24782. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24783. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24784. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24785. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24786. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24787. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24788. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24789. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24790. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24791. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24792. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24793. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24794. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24795. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24796. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24797. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24798. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24799. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24800. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24801. return SceneComponentConstants;
  24802. }());
  24803. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24804. /**
  24805. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24806. * @hidden
  24807. */
  24808. var Stage = /** @class */ (function (_super) {
  24809. __extends(Stage, _super);
  24810. /**
  24811. * Hide ctor from the rest of the world.
  24812. * @param items The items to add.
  24813. */
  24814. function Stage(items) {
  24815. return _super.apply(this, items) || this;
  24816. }
  24817. /**
  24818. * Creates a new Stage.
  24819. * @returns A new instance of a Stage
  24820. */
  24821. Stage.Create = function () {
  24822. return Object.create(Stage.prototype);
  24823. };
  24824. /**
  24825. * Registers a step in an ordered way in the targeted stage.
  24826. * @param index Defines the position to register the step in
  24827. * @param component Defines the component attached to the step
  24828. * @param action Defines the action to launch during the step
  24829. */
  24830. Stage.prototype.registerStep = function (index, component, action) {
  24831. var i = 0;
  24832. var maxIndex = Number.MAX_VALUE;
  24833. for (; i < this.length; i++) {
  24834. var step = this[i];
  24835. maxIndex = step.index;
  24836. if (index < maxIndex) {
  24837. break;
  24838. }
  24839. }
  24840. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24841. };
  24842. /**
  24843. * Clears all the steps from the stage.
  24844. */
  24845. Stage.prototype.clear = function () {
  24846. this.length = 0;
  24847. };
  24848. return Stage;
  24849. }(Array));
  24850. BABYLON.Stage = Stage;
  24851. })(BABYLON || (BABYLON = {}));
  24852. //# sourceMappingURL=babylon.sceneComponent.js.map
  24853. var BABYLON;
  24854. (function (BABYLON) {
  24855. /**
  24856. * Base class of the scene acting as a container for the different elements composing a scene.
  24857. * This class is dynamically extended by the different components of the scene increasing
  24858. * flexibility and reducing coupling
  24859. */
  24860. var AbstractScene = /** @class */ (function () {
  24861. function AbstractScene() {
  24862. /**
  24863. * Gets the list of root nodes (ie. nodes with no parent)
  24864. */
  24865. this.rootNodes = new Array();
  24866. /** All of the cameras added to this scene
  24867. * @see http://doc.babylonjs.com/babylon101/cameras
  24868. */
  24869. this.cameras = new Array();
  24870. /**
  24871. * All of the lights added to this scene
  24872. * @see http://doc.babylonjs.com/babylon101/lights
  24873. */
  24874. this.lights = new Array();
  24875. /**
  24876. * All of the (abstract) meshes added to this scene
  24877. */
  24878. this.meshes = new Array();
  24879. /**
  24880. * The list of skeletons added to the scene
  24881. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24882. */
  24883. this.skeletons = new Array();
  24884. /**
  24885. * All of the particle systems added to this scene
  24886. * @see http://doc.babylonjs.com/babylon101/particles
  24887. */
  24888. this.particleSystems = new Array();
  24889. /**
  24890. * Gets a list of Animations associated with the scene
  24891. */
  24892. this.animations = [];
  24893. /**
  24894. * All of the animation groups added to this scene
  24895. * @see http://doc.babylonjs.com/how_to/group
  24896. */
  24897. this.animationGroups = new Array();
  24898. /**
  24899. * All of the multi-materials added to this scene
  24900. * @see http://doc.babylonjs.com/how_to/multi_materials
  24901. */
  24902. this.multiMaterials = new Array();
  24903. /**
  24904. * All of the materials added to this scene
  24905. * @see http://doc.babylonjs.com/babylon101/materials
  24906. */
  24907. this.materials = new Array();
  24908. /**
  24909. * The list of morph target managers added to the scene
  24910. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24911. */
  24912. this.morphTargetManagers = new Array();
  24913. /**
  24914. * The list of geometries used in the scene.
  24915. */
  24916. this.geometries = new Array();
  24917. /**
  24918. * All of the tranform nodes added to this scene
  24919. * @see http://doc.babylonjs.com/how_to/transformnode
  24920. */
  24921. this.transformNodes = new Array();
  24922. /**
  24923. * ActionManagers available on the scene.
  24924. */
  24925. this.actionManagers = new Array();
  24926. /**
  24927. * Textures to keep.
  24928. */
  24929. this.textures = new Array();
  24930. }
  24931. /**
  24932. * Adds a parser in the list of available ones
  24933. * @param name Defines the name of the parser
  24934. * @param parser Defines the parser to add
  24935. */
  24936. AbstractScene.AddParser = function (name, parser) {
  24937. this._BabylonFileParsers[name] = parser;
  24938. };
  24939. /**
  24940. * Gets a general parser from the list of avaialble ones
  24941. * @param name Defines the name of the parser
  24942. * @returns the requested parser or null
  24943. */
  24944. AbstractScene.GetParser = function (name) {
  24945. if (this._BabylonFileParsers[name]) {
  24946. return this._BabylonFileParsers[name];
  24947. }
  24948. return null;
  24949. };
  24950. /**
  24951. * Adds n individual parser in the list of available ones
  24952. * @param name Defines the name of the parser
  24953. * @param parser Defines the parser to add
  24954. */
  24955. AbstractScene.AddIndividualParser = function (name, parser) {
  24956. this._IndividualBabylonFileParsers[name] = parser;
  24957. };
  24958. /**
  24959. * Gets an individual parser from the list of avaialble ones
  24960. * @param name Defines the name of the parser
  24961. * @returns the requested parser or null
  24962. */
  24963. AbstractScene.GetIndividualParser = function (name) {
  24964. if (this._IndividualBabylonFileParsers[name]) {
  24965. return this._IndividualBabylonFileParsers[name];
  24966. }
  24967. return null;
  24968. };
  24969. /**
  24970. * Parser json data and populate both a scene and its associated container object
  24971. * @param jsonData Defines the data to parse
  24972. * @param scene Defines the scene to parse the data for
  24973. * @param container Defines the container attached to the parsing sequence
  24974. * @param rootUrl Defines the root url of the data
  24975. */
  24976. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  24977. for (var parserName in this._BabylonFileParsers) {
  24978. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  24979. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  24980. }
  24981. }
  24982. };
  24983. /**
  24984. * Stores the list of available parsers in the application.
  24985. */
  24986. AbstractScene._BabylonFileParsers = {};
  24987. /**
  24988. * Stores the list of available individual parsers in the application.
  24989. */
  24990. AbstractScene._IndividualBabylonFileParsers = {};
  24991. return AbstractScene;
  24992. }());
  24993. BABYLON.AbstractScene = AbstractScene;
  24994. })(BABYLON || (BABYLON = {}));
  24995. //# sourceMappingURL=babylon.abstractScene.js.map
  24996. var BABYLON;
  24997. (function (BABYLON) {
  24998. /** @hidden */
  24999. var ClickInfo = /** @class */ (function () {
  25000. function ClickInfo() {
  25001. this._singleClick = false;
  25002. this._doubleClick = false;
  25003. this._hasSwiped = false;
  25004. this._ignore = false;
  25005. }
  25006. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25007. get: function () {
  25008. return this._singleClick;
  25009. },
  25010. set: function (b) {
  25011. this._singleClick = b;
  25012. },
  25013. enumerable: true,
  25014. configurable: true
  25015. });
  25016. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25017. get: function () {
  25018. return this._doubleClick;
  25019. },
  25020. set: function (b) {
  25021. this._doubleClick = b;
  25022. },
  25023. enumerable: true,
  25024. configurable: true
  25025. });
  25026. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25027. get: function () {
  25028. return this._hasSwiped;
  25029. },
  25030. set: function (b) {
  25031. this._hasSwiped = b;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25037. get: function () {
  25038. return this._ignore;
  25039. },
  25040. set: function (b) {
  25041. this._ignore = b;
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. return ClickInfo;
  25047. }());
  25048. /**
  25049. * This class is used by the onRenderingGroupObservable
  25050. */
  25051. var RenderingGroupInfo = /** @class */ (function () {
  25052. function RenderingGroupInfo() {
  25053. }
  25054. return RenderingGroupInfo;
  25055. }());
  25056. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25057. /**
  25058. * Represents a scene to be rendered by the engine.
  25059. * @see http://doc.babylonjs.com/features/scene
  25060. */
  25061. var Scene = /** @class */ (function (_super) {
  25062. __extends(Scene, _super);
  25063. /**
  25064. * Creates a new Scene
  25065. * @param engine defines the engine to use to render this scene
  25066. */
  25067. function Scene(engine) {
  25068. var _this = _super.call(this) || this;
  25069. // Members
  25070. /**
  25071. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25072. */
  25073. _this.autoClear = true;
  25074. /**
  25075. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25076. */
  25077. _this.autoClearDepthAndStencil = true;
  25078. /**
  25079. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25080. */
  25081. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25082. /**
  25083. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25084. */
  25085. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25086. _this._forceWireframe = false;
  25087. _this._forcePointsCloud = false;
  25088. /**
  25089. * Gets or sets a boolean indicating if animations are enabled
  25090. */
  25091. _this.animationsEnabled = true;
  25092. _this._animationPropertiesOverride = null;
  25093. /**
  25094. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25095. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25096. */
  25097. _this.useConstantAnimationDeltaTime = false;
  25098. /**
  25099. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25100. * Please note that it requires to run a ray cast through the scene on every frame
  25101. */
  25102. _this.constantlyUpdateMeshUnderPointer = false;
  25103. /**
  25104. * Defines the HTML cursor to use when hovering over interactive elements
  25105. */
  25106. _this.hoverCursor = "pointer";
  25107. /**
  25108. * Defines the HTML default cursor to use (empty by default)
  25109. */
  25110. _this.defaultCursor = "";
  25111. /**
  25112. * This is used to call preventDefault() on pointer down
  25113. * in order to block unwanted artifacts like system double clicks
  25114. */
  25115. _this.preventDefaultOnPointerDown = true;
  25116. // Metadata
  25117. /**
  25118. * Gets or sets user defined metadata
  25119. */
  25120. _this.metadata = null;
  25121. /**
  25122. * Use this array to add regular expressions used to disable offline support for specific urls
  25123. */
  25124. _this.disableOfflineSupportExceptionRules = new Array();
  25125. /**
  25126. * An event triggered when the scene is disposed.
  25127. */
  25128. _this.onDisposeObservable = new BABYLON.Observable();
  25129. _this._onDisposeObserver = null;
  25130. /**
  25131. * An event triggered before rendering the scene (right after animations and physics)
  25132. */
  25133. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25134. _this._onBeforeRenderObserver = null;
  25135. /**
  25136. * An event triggered after rendering the scene
  25137. */
  25138. _this.onAfterRenderObservable = new BABYLON.Observable();
  25139. _this._onAfterRenderObserver = null;
  25140. /**
  25141. * An event triggered before animating the scene
  25142. */
  25143. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25144. /**
  25145. * An event triggered after animations processing
  25146. */
  25147. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25148. /**
  25149. * An event triggered before draw calls are ready to be sent
  25150. */
  25151. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25152. /**
  25153. * An event triggered after draw calls have been sent
  25154. */
  25155. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25156. /**
  25157. * An event triggered when the scene is ready
  25158. */
  25159. _this.onReadyObservable = new BABYLON.Observable();
  25160. /**
  25161. * An event triggered before rendering a camera
  25162. */
  25163. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25164. _this._onBeforeCameraRenderObserver = null;
  25165. /**
  25166. * An event triggered after rendering a camera
  25167. */
  25168. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25169. _this._onAfterCameraRenderObserver = null;
  25170. /**
  25171. * An event triggered when active meshes evaluation is about to start
  25172. */
  25173. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25174. /**
  25175. * An event triggered when active meshes evaluation is done
  25176. */
  25177. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25178. /**
  25179. * An event triggered when particles rendering is about to start
  25180. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25181. */
  25182. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25183. /**
  25184. * An event triggered when particles rendering is done
  25185. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25186. */
  25187. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25188. /**
  25189. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25190. */
  25191. _this.onDataLoadedObservable = new BABYLON.Observable();
  25192. /**
  25193. * An event triggered when a camera is created
  25194. */
  25195. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25196. /**
  25197. * An event triggered when a camera is removed
  25198. */
  25199. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25200. /**
  25201. * An event triggered when a light is created
  25202. */
  25203. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25204. /**
  25205. * An event triggered when a light is removed
  25206. */
  25207. _this.onLightRemovedObservable = new BABYLON.Observable();
  25208. /**
  25209. * An event triggered when a geometry is created
  25210. */
  25211. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25212. /**
  25213. * An event triggered when a geometry is removed
  25214. */
  25215. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25216. /**
  25217. * An event triggered when a transform node is created
  25218. */
  25219. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25220. /**
  25221. * An event triggered when a transform node is removed
  25222. */
  25223. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25224. /**
  25225. * An event triggered when a mesh is created
  25226. */
  25227. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25228. /**
  25229. * An event triggered when a mesh is removed
  25230. */
  25231. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25232. /**
  25233. * An event triggered when a material is created
  25234. */
  25235. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25236. /**
  25237. * An event triggered when a material is removed
  25238. */
  25239. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25240. /**
  25241. * An event triggered when a texture is created
  25242. */
  25243. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25244. /**
  25245. * An event triggered when a texture is removed
  25246. */
  25247. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25248. /**
  25249. * An event triggered when render targets are about to be rendered
  25250. * Can happen multiple times per frame.
  25251. */
  25252. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25253. /**
  25254. * An event triggered when render targets were rendered.
  25255. * Can happen multiple times per frame.
  25256. */
  25257. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25258. /**
  25259. * An event triggered before calculating deterministic simulation step
  25260. */
  25261. _this.onBeforeStepObservable = new BABYLON.Observable();
  25262. /**
  25263. * An event triggered after calculating deterministic simulation step
  25264. */
  25265. _this.onAfterStepObservable = new BABYLON.Observable();
  25266. /**
  25267. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25268. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25269. * 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)
  25270. */
  25271. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25272. /**
  25273. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25274. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25275. * 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)
  25276. */
  25277. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25278. /**
  25279. * This Observable will when a mesh has been imported into the scene.
  25280. */
  25281. _this.onMeshImportedObservable = new BABYLON.Observable();
  25282. // Animations
  25283. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25284. /**
  25285. * 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).
  25286. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25287. */
  25288. _this.onPrePointerObservable = new BABYLON.Observable();
  25289. /**
  25290. * Observable event triggered each time an input event is received from the rendering canvas
  25291. */
  25292. _this.onPointerObservable = new BABYLON.Observable();
  25293. _this._meshPickProceed = false;
  25294. _this._currentPickResult = null;
  25295. _this._previousPickResult = null;
  25296. _this._totalPointersPressed = 0;
  25297. _this._doubleClickOccured = false;
  25298. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25299. _this.cameraToUseForPointers = null;
  25300. _this._pointerX = 0;
  25301. _this._pointerY = 0;
  25302. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25303. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25304. _this._startingPointerTime = 0;
  25305. _this._previousStartingPointerTime = 0;
  25306. _this._pointerCaptures = {};
  25307. // Deterministic lockstep
  25308. _this._timeAccumulator = 0;
  25309. _this._currentStepId = 0;
  25310. _this._currentInternalStep = 0;
  25311. // Keyboard
  25312. /**
  25313. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25314. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25315. */
  25316. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25317. /**
  25318. * Observable event triggered each time an keyboard event is received from the hosting window
  25319. */
  25320. _this.onKeyboardObservable = new BABYLON.Observable();
  25321. // Coordinates system
  25322. _this._useRightHandedSystem = false;
  25323. // Fog
  25324. _this._fogEnabled = true;
  25325. _this._fogMode = Scene.FOGMODE_NONE;
  25326. /**
  25327. * Gets or sets the fog color to use
  25328. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25329. * (Default is Color3(0.2, 0.2, 0.3))
  25330. */
  25331. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25332. /**
  25333. * Gets or sets the fog density to use
  25334. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25335. * (Default is 0.1)
  25336. */
  25337. _this.fogDensity = 0.1;
  25338. /**
  25339. * Gets or sets the fog start distance to use
  25340. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25341. * (Default is 0)
  25342. */
  25343. _this.fogStart = 0;
  25344. /**
  25345. * Gets or sets the fog end distance to use
  25346. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25347. * (Default is 1000)
  25348. */
  25349. _this.fogEnd = 1000.0;
  25350. // Lights
  25351. _this._shadowsEnabled = true;
  25352. _this._lightsEnabled = true;
  25353. /** All of the active cameras added to this scene. */
  25354. _this.activeCameras = new Array();
  25355. // Textures
  25356. _this._texturesEnabled = true;
  25357. // Particles
  25358. /**
  25359. * Gets or sets a boolean indicating if particles are enabled on this scene
  25360. */
  25361. _this.particlesEnabled = true;
  25362. // Sprites
  25363. /**
  25364. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25365. */
  25366. _this.spritesEnabled = true;
  25367. // Skeletons
  25368. _this._skeletonsEnabled = true;
  25369. // Lens flares
  25370. /**
  25371. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25372. */
  25373. _this.lensFlaresEnabled = true;
  25374. // Collisions
  25375. /**
  25376. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25377. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25378. */
  25379. _this.collisionsEnabled = true;
  25380. /**
  25381. * Defines the gravity applied to this scene (used only for collisions)
  25382. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25383. */
  25384. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25385. // Postprocesses
  25386. /**
  25387. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25388. */
  25389. _this.postProcessesEnabled = true;
  25390. /**
  25391. * The list of postprocesses added to the scene
  25392. */
  25393. _this.postProcesses = new Array();
  25394. // Customs render targets
  25395. /**
  25396. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25397. */
  25398. _this.renderTargetsEnabled = true;
  25399. /**
  25400. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25401. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25402. */
  25403. _this.dumpNextRenderTargets = false;
  25404. /**
  25405. * The list of user defined render targets added to the scene
  25406. */
  25407. _this.customRenderTargets = new Array();
  25408. /**
  25409. * Gets the list of meshes imported to the scene through SceneLoader
  25410. */
  25411. _this.importedMeshesFiles = new Array();
  25412. // Probes
  25413. /**
  25414. * Gets or sets a boolean indicating if probes are enabled on this scene
  25415. */
  25416. _this.probesEnabled = true;
  25417. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25418. // Procedural textures
  25419. /**
  25420. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25421. */
  25422. _this.proceduralTexturesEnabled = true;
  25423. // Performance counters
  25424. _this._totalVertices = new BABYLON.PerfCounter();
  25425. /** @hidden */
  25426. _this._activeIndices = new BABYLON.PerfCounter();
  25427. /** @hidden */
  25428. _this._activeParticles = new BABYLON.PerfCounter();
  25429. /** @hidden */
  25430. _this._activeBones = new BABYLON.PerfCounter();
  25431. _this._animationTime = 0;
  25432. /**
  25433. * Gets or sets a general scale for animation speed
  25434. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25435. */
  25436. _this.animationTimeScale = 1;
  25437. _this._renderId = 0;
  25438. _this._frameId = 0;
  25439. _this._executeWhenReadyTimeoutId = -1;
  25440. _this._intermediateRendering = false;
  25441. _this._viewUpdateFlag = -1;
  25442. _this._projectionUpdateFlag = -1;
  25443. _this._alternateViewUpdateFlag = -1;
  25444. _this._alternateProjectionUpdateFlag = -1;
  25445. /** @hidden */
  25446. _this._toBeDisposed = new Array(256);
  25447. _this._activeRequests = new Array();
  25448. _this._pendingData = new Array();
  25449. _this._isDisposed = false;
  25450. /**
  25451. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25452. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25453. */
  25454. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25455. _this._activeMeshes = new BABYLON.SmartArray(256);
  25456. _this._processedMaterials = new BABYLON.SmartArray(256);
  25457. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25458. /** @hidden */
  25459. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25460. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25461. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25462. /** @hidden */
  25463. _this._activeAnimatables = new Array();
  25464. _this._transformMatrix = BABYLON.Matrix.Zero();
  25465. _this._useAlternateCameraConfiguration = false;
  25466. _this._alternateRendering = false;
  25467. /**
  25468. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25469. * This is useful if there are more lights that the maximum simulteanous authorized
  25470. */
  25471. _this.requireLightSorting = false;
  25472. /**
  25473. * @hidden
  25474. * Backing store of defined scene components.
  25475. */
  25476. _this._components = [];
  25477. /**
  25478. * @hidden
  25479. * Backing store of defined scene components.
  25480. */
  25481. _this._serializableComponents = [];
  25482. /**
  25483. * List of components to register on the next registration step.
  25484. */
  25485. _this._transientComponents = [];
  25486. /**
  25487. * @hidden
  25488. * Defines the actions happening before camera updates.
  25489. */
  25490. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25491. /**
  25492. * @hidden
  25493. * Defines the actions happening before clear the canvas.
  25494. */
  25495. _this._beforeClearStage = BABYLON.Stage.Create();
  25496. /**
  25497. * @hidden
  25498. * Defines the actions when collecting render targets for the frame.
  25499. */
  25500. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25501. /**
  25502. * @hidden
  25503. * Defines the actions happening for one camera in the frame.
  25504. */
  25505. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25506. /**
  25507. * @hidden
  25508. * Defines the actions happening during the per mesh ready checks.
  25509. */
  25510. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25511. /**
  25512. * @hidden
  25513. * Defines the actions happening before evaluate active mesh checks.
  25514. */
  25515. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25516. /**
  25517. * @hidden
  25518. * Defines the actions happening during the evaluate sub mesh checks.
  25519. */
  25520. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25521. /**
  25522. * @hidden
  25523. * Defines the actions happening during the active mesh stage.
  25524. */
  25525. _this._activeMeshStage = BABYLON.Stage.Create();
  25526. /**
  25527. * @hidden
  25528. * Defines the actions happening during the per camera render target step.
  25529. */
  25530. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25531. /**
  25532. * @hidden
  25533. * Defines the actions happening just before the active camera is drawing.
  25534. */
  25535. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25536. /**
  25537. * @hidden
  25538. * Defines the actions happening just before a rendering group is drawing.
  25539. */
  25540. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25541. /**
  25542. * @hidden
  25543. * Defines the actions happening just before a mesh is drawing.
  25544. */
  25545. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25546. /**
  25547. * @hidden
  25548. * Defines the actions happening just after a mesh has been drawn.
  25549. */
  25550. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25551. /**
  25552. * @hidden
  25553. * Defines the actions happening just after a rendering group has been drawn.
  25554. */
  25555. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25556. /**
  25557. * @hidden
  25558. * Defines the actions happening just after the active camera has been drawn.
  25559. */
  25560. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25561. /**
  25562. * @hidden
  25563. * Defines the actions happening just after rendering all cameras and computing intersections.
  25564. */
  25565. _this._afterRenderStage = BABYLON.Stage.Create();
  25566. /**
  25567. * @hidden
  25568. * Defines the actions happening when a pointer move event happens.
  25569. */
  25570. _this._pointerMoveStage = BABYLON.Stage.Create();
  25571. /**
  25572. * @hidden
  25573. * Defines the actions happening when a pointer down event happens.
  25574. */
  25575. _this._pointerDownStage = BABYLON.Stage.Create();
  25576. /**
  25577. * @hidden
  25578. * Defines the actions happening when a pointer up event happens.
  25579. */
  25580. _this._pointerUpStage = BABYLON.Stage.Create();
  25581. _this._defaultMeshCandidates = {
  25582. data: [],
  25583. length: 0
  25584. };
  25585. _this._defaultSubMeshCandidates = {
  25586. data: [],
  25587. length: 0
  25588. };
  25589. _this._activeMeshesFrozen = false;
  25590. /** @hidden */
  25591. _this._allowPostProcessClearColor = true;
  25592. /**
  25593. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25594. */
  25595. _this.getDeterministicFrameTime = function () {
  25596. return 1000.0 / 60.0; // frame time in ms
  25597. };
  25598. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25599. _this._blockMaterialDirtyMechanism = false;
  25600. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25601. _this._engine.scenes.push(_this);
  25602. _this._uid = null;
  25603. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25604. if (BABYLON.PostProcessManager) {
  25605. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25606. }
  25607. if (BABYLON.Tools.IsWindowObjectExist()) {
  25608. _this.attachControl();
  25609. }
  25610. //collision coordinator initialization. For now legacy per default.
  25611. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25612. // Uniform Buffer
  25613. _this._createUbo();
  25614. // Default Image processing definition
  25615. if (BABYLON.ImageProcessingConfiguration) {
  25616. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25617. }
  25618. _this.setDefaultCandidateProviders();
  25619. return _this;
  25620. }
  25621. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25622. /**
  25623. * Texture used in all pbr material as the reflection texture.
  25624. * As in the majority of the scene they are the same (exception for multi room and so on),
  25625. * this is easier to reference from here than from all the materials.
  25626. */
  25627. get: function () {
  25628. return this._environmentTexture;
  25629. },
  25630. /**
  25631. * Texture used in all pbr material as the reflection texture.
  25632. * As in the majority of the scene they are the same (exception for multi room and so on),
  25633. * this is easier to set here than in all the materials.
  25634. */
  25635. set: function (value) {
  25636. if (this._environmentTexture === value) {
  25637. return;
  25638. }
  25639. this._environmentTexture = value;
  25640. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25641. },
  25642. enumerable: true,
  25643. configurable: true
  25644. });
  25645. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25646. /**
  25647. * Default image processing configuration used either in the rendering
  25648. * Forward main pass or through the imageProcessingPostProcess if present.
  25649. * As in the majority of the scene they are the same (exception for multi camera),
  25650. * this is easier to reference from here than from all the materials and post process.
  25651. *
  25652. * No setter as we it is a shared configuration, you can set the values instead.
  25653. */
  25654. get: function () {
  25655. return this._imageProcessingConfiguration;
  25656. },
  25657. enumerable: true,
  25658. configurable: true
  25659. });
  25660. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25661. get: function () {
  25662. return this._forceWireframe;
  25663. },
  25664. /**
  25665. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25666. */
  25667. set: function (value) {
  25668. if (this._forceWireframe === value) {
  25669. return;
  25670. }
  25671. this._forceWireframe = value;
  25672. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25673. },
  25674. enumerable: true,
  25675. configurable: true
  25676. });
  25677. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25678. get: function () {
  25679. return this._forcePointsCloud;
  25680. },
  25681. /**
  25682. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25683. */
  25684. set: function (value) {
  25685. if (this._forcePointsCloud === value) {
  25686. return;
  25687. }
  25688. this._forcePointsCloud = value;
  25689. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25690. },
  25691. enumerable: true,
  25692. configurable: true
  25693. });
  25694. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25695. /**
  25696. * Gets or sets the animation properties override
  25697. */
  25698. get: function () {
  25699. return this._animationPropertiesOverride;
  25700. },
  25701. set: function (value) {
  25702. this._animationPropertiesOverride = value;
  25703. },
  25704. enumerable: true,
  25705. configurable: true
  25706. });
  25707. Object.defineProperty(Scene.prototype, "onDispose", {
  25708. /** Sets a function to be executed when this scene is disposed. */
  25709. set: function (callback) {
  25710. if (this._onDisposeObserver) {
  25711. this.onDisposeObservable.remove(this._onDisposeObserver);
  25712. }
  25713. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25714. },
  25715. enumerable: true,
  25716. configurable: true
  25717. });
  25718. Object.defineProperty(Scene.prototype, "beforeRender", {
  25719. /** Sets a function to be executed before rendering this scene */
  25720. set: function (callback) {
  25721. if (this._onBeforeRenderObserver) {
  25722. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25723. }
  25724. if (callback) {
  25725. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25726. }
  25727. },
  25728. enumerable: true,
  25729. configurable: true
  25730. });
  25731. Object.defineProperty(Scene.prototype, "afterRender", {
  25732. /** Sets a function to be executed after rendering this scene */
  25733. set: function (callback) {
  25734. if (this._onAfterRenderObserver) {
  25735. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25736. }
  25737. if (callback) {
  25738. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25739. }
  25740. },
  25741. enumerable: true,
  25742. configurable: true
  25743. });
  25744. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25745. /** Sets a function to be executed before rendering a camera*/
  25746. set: function (callback) {
  25747. if (this._onBeforeCameraRenderObserver) {
  25748. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25749. }
  25750. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25751. },
  25752. enumerable: true,
  25753. configurable: true
  25754. });
  25755. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25756. /** Sets a function to be executed after rendering a camera*/
  25757. set: function (callback) {
  25758. if (this._onAfterCameraRenderObserver) {
  25759. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25760. }
  25761. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25762. },
  25763. enumerable: true,
  25764. configurable: true
  25765. });
  25766. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25767. /**
  25768. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25769. */
  25770. get: function () {
  25771. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25772. },
  25773. enumerable: true,
  25774. configurable: true
  25775. });
  25776. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25777. get: function () {
  25778. return this._useRightHandedSystem;
  25779. },
  25780. /**
  25781. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25782. */
  25783. set: function (value) {
  25784. if (this._useRightHandedSystem === value) {
  25785. return;
  25786. }
  25787. this._useRightHandedSystem = value;
  25788. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. /**
  25794. * Sets the step Id used by deterministic lock step
  25795. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25796. * @param newStepId defines the step Id
  25797. */
  25798. Scene.prototype.setStepId = function (newStepId) {
  25799. this._currentStepId = newStepId;
  25800. };
  25801. ;
  25802. /**
  25803. * Gets the step Id used by deterministic lock step
  25804. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25805. * @returns the step Id
  25806. */
  25807. Scene.prototype.getStepId = function () {
  25808. return this._currentStepId;
  25809. };
  25810. ;
  25811. /**
  25812. * Gets the internal step used by deterministic lock step
  25813. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25814. * @returns the internal step
  25815. */
  25816. Scene.prototype.getInternalStep = function () {
  25817. return this._currentInternalStep;
  25818. };
  25819. ;
  25820. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25821. get: function () {
  25822. return this._fogEnabled;
  25823. },
  25824. /**
  25825. * Gets or sets a boolean indicating if fog is enabled on this scene
  25826. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25827. * (Default is true)
  25828. */
  25829. set: function (value) {
  25830. if (this._fogEnabled === value) {
  25831. return;
  25832. }
  25833. this._fogEnabled = value;
  25834. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25835. },
  25836. enumerable: true,
  25837. configurable: true
  25838. });
  25839. Object.defineProperty(Scene.prototype, "fogMode", {
  25840. get: function () {
  25841. return this._fogMode;
  25842. },
  25843. /**
  25844. * Gets or sets the fog mode to use
  25845. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25846. * | mode | value |
  25847. * | --- | --- |
  25848. * | FOGMODE_NONE | 0 |
  25849. * | FOGMODE_EXP | 1 |
  25850. * | FOGMODE_EXP2 | 2 |
  25851. * | FOGMODE_LINEAR | 3 |
  25852. */
  25853. set: function (value) {
  25854. if (this._fogMode === value) {
  25855. return;
  25856. }
  25857. this._fogMode = value;
  25858. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25859. },
  25860. enumerable: true,
  25861. configurable: true
  25862. });
  25863. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25864. get: function () {
  25865. return this._shadowsEnabled;
  25866. },
  25867. /**
  25868. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25869. */
  25870. set: function (value) {
  25871. if (this._shadowsEnabled === value) {
  25872. return;
  25873. }
  25874. this._shadowsEnabled = value;
  25875. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25881. get: function () {
  25882. return this._lightsEnabled;
  25883. },
  25884. /**
  25885. * Gets or sets a boolean indicating if lights are enabled on this scene
  25886. */
  25887. set: function (value) {
  25888. if (this._lightsEnabled === value) {
  25889. return;
  25890. }
  25891. this._lightsEnabled = value;
  25892. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25893. },
  25894. enumerable: true,
  25895. configurable: true
  25896. });
  25897. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25898. /** The default material used on meshes when no material is affected */
  25899. get: function () {
  25900. if (!this._defaultMaterial) {
  25901. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25902. }
  25903. return this._defaultMaterial;
  25904. },
  25905. /** The default material used on meshes when no material is affected */
  25906. set: function (value) {
  25907. this._defaultMaterial = value;
  25908. },
  25909. enumerable: true,
  25910. configurable: true
  25911. });
  25912. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25913. get: function () {
  25914. return this._texturesEnabled;
  25915. },
  25916. /**
  25917. * Gets or sets a boolean indicating if textures are enabled on this scene
  25918. */
  25919. set: function (value) {
  25920. if (this._texturesEnabled === value) {
  25921. return;
  25922. }
  25923. this._texturesEnabled = value;
  25924. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25930. get: function () {
  25931. return this._skeletonsEnabled;
  25932. },
  25933. /**
  25934. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25935. */
  25936. set: function (value) {
  25937. if (this._skeletonsEnabled === value) {
  25938. return;
  25939. }
  25940. this._skeletonsEnabled = value;
  25941. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25942. },
  25943. enumerable: true,
  25944. configurable: true
  25945. });
  25946. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25947. /** @hidden */
  25948. get: function () {
  25949. return this._alternateRendering;
  25950. },
  25951. enumerable: true,
  25952. configurable: true
  25953. });
  25954. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25955. /**
  25956. * Gets the list of frustum planes (built from the active camera)
  25957. */
  25958. get: function () {
  25959. return this._frustumPlanes;
  25960. },
  25961. enumerable: true,
  25962. configurable: true
  25963. });
  25964. /**
  25965. * Registers the transient components if needed.
  25966. */
  25967. Scene.prototype._registerTransientComponents = function () {
  25968. // Register components that have been associated lately to the scene.
  25969. if (this._transientComponents.length > 0) {
  25970. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25971. var component = _a[_i];
  25972. component.register();
  25973. }
  25974. this._transientComponents = [];
  25975. }
  25976. };
  25977. /**
  25978. * @hidden
  25979. * Add a component to the scene.
  25980. * Note that the ccomponent could be registered on th next frame if this is called after
  25981. * the register component stage.
  25982. * @param component Defines the component to add to the scene
  25983. */
  25984. Scene.prototype._addComponent = function (component) {
  25985. this._components.push(component);
  25986. this._transientComponents.push(component);
  25987. var serializableComponent = component;
  25988. if (serializableComponent.addFromContainer) {
  25989. this._serializableComponents.push(serializableComponent);
  25990. }
  25991. };
  25992. /**
  25993. * @hidden
  25994. * Gets a component from the scene.
  25995. * @param name defines the name of the component to retrieve
  25996. * @returns the component or null if not present
  25997. */
  25998. Scene.prototype._getComponent = function (name) {
  25999. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26000. var component = _a[_i];
  26001. if (component.name === name) {
  26002. return component;
  26003. }
  26004. }
  26005. return null;
  26006. };
  26007. /**
  26008. * @hidden
  26009. */
  26010. Scene.prototype._getDefaultMeshCandidates = function () {
  26011. this._defaultMeshCandidates.data = this.meshes;
  26012. this._defaultMeshCandidates.length = this.meshes.length;
  26013. return this._defaultMeshCandidates;
  26014. };
  26015. /**
  26016. * @hidden
  26017. */
  26018. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26019. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26020. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26021. return this._defaultSubMeshCandidates;
  26022. };
  26023. /**
  26024. * Sets the default candidate providers for the scene.
  26025. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26026. * and getCollidingSubMeshCandidates to their default function
  26027. */
  26028. Scene.prototype.setDefaultCandidateProviders = function () {
  26029. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26030. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26031. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26032. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26033. };
  26034. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26035. /**
  26036. * Gets a boolean indicating if collisions are processed on a web worker
  26037. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26038. */
  26039. get: function () {
  26040. return this._workerCollisions;
  26041. },
  26042. set: function (enabled) {
  26043. if (!BABYLON.CollisionCoordinatorLegacy) {
  26044. return;
  26045. }
  26046. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26047. this._workerCollisions = enabled;
  26048. if (this.collisionCoordinator) {
  26049. this.collisionCoordinator.destroy();
  26050. }
  26051. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26052. this.collisionCoordinator.init(this);
  26053. },
  26054. enumerable: true,
  26055. configurable: true
  26056. });
  26057. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26058. /**
  26059. * Gets the mesh that is currently under the pointer
  26060. */
  26061. get: function () {
  26062. return this._pointerOverMesh;
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. Object.defineProperty(Scene.prototype, "pointerX", {
  26068. /**
  26069. * Gets the current on-screen X position of the pointer
  26070. */
  26071. get: function () {
  26072. return this._pointerX;
  26073. },
  26074. enumerable: true,
  26075. configurable: true
  26076. });
  26077. Object.defineProperty(Scene.prototype, "pointerY", {
  26078. /**
  26079. * Gets the current on-screen Y position of the pointer
  26080. */
  26081. get: function () {
  26082. return this._pointerY;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. /**
  26088. * Gets the cached material (ie. the latest rendered one)
  26089. * @returns the cached material
  26090. */
  26091. Scene.prototype.getCachedMaterial = function () {
  26092. return this._cachedMaterial;
  26093. };
  26094. /**
  26095. * Gets the cached effect (ie. the latest rendered one)
  26096. * @returns the cached effect
  26097. */
  26098. Scene.prototype.getCachedEffect = function () {
  26099. return this._cachedEffect;
  26100. };
  26101. /**
  26102. * Gets the cached visibility state (ie. the latest rendered one)
  26103. * @returns the cached visibility state
  26104. */
  26105. Scene.prototype.getCachedVisibility = function () {
  26106. return this._cachedVisibility;
  26107. };
  26108. /**
  26109. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26110. * @param material defines the current material
  26111. * @param effect defines the current effect
  26112. * @param visibility defines the current visibility state
  26113. * @returns true if one parameter is not cached
  26114. */
  26115. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26116. if (visibility === void 0) { visibility = 1; }
  26117. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26118. };
  26119. /**
  26120. * Gets the engine associated with the scene
  26121. * @returns an Engine
  26122. */
  26123. Scene.prototype.getEngine = function () {
  26124. return this._engine;
  26125. };
  26126. /**
  26127. * Gets the total number of vertices rendered per frame
  26128. * @returns the total number of vertices rendered per frame
  26129. */
  26130. Scene.prototype.getTotalVertices = function () {
  26131. return this._totalVertices.current;
  26132. };
  26133. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26134. /**
  26135. * Gets the performance counter for total vertices
  26136. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26137. */
  26138. get: function () {
  26139. return this._totalVertices;
  26140. },
  26141. enumerable: true,
  26142. configurable: true
  26143. });
  26144. /**
  26145. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26146. * @returns the total number of active indices rendered per frame
  26147. */
  26148. Scene.prototype.getActiveIndices = function () {
  26149. return this._activeIndices.current;
  26150. };
  26151. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26152. /**
  26153. * Gets the performance counter for active indices
  26154. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26155. */
  26156. get: function () {
  26157. return this._activeIndices;
  26158. },
  26159. enumerable: true,
  26160. configurable: true
  26161. });
  26162. /**
  26163. * Gets the total number of active particles rendered per frame
  26164. * @returns the total number of active particles rendered per frame
  26165. */
  26166. Scene.prototype.getActiveParticles = function () {
  26167. return this._activeParticles.current;
  26168. };
  26169. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26170. /**
  26171. * Gets the performance counter for active particles
  26172. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26173. */
  26174. get: function () {
  26175. return this._activeParticles;
  26176. },
  26177. enumerable: true,
  26178. configurable: true
  26179. });
  26180. /**
  26181. * Gets the total number of active bones rendered per frame
  26182. * @returns the total number of active bones rendered per frame
  26183. */
  26184. Scene.prototype.getActiveBones = function () {
  26185. return this._activeBones.current;
  26186. };
  26187. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26188. /**
  26189. * Gets the performance counter for active bones
  26190. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26191. */
  26192. get: function () {
  26193. return this._activeBones;
  26194. },
  26195. enumerable: true,
  26196. configurable: true
  26197. });
  26198. /** @hidden */
  26199. Scene.prototype.getInterFramePerfCounter = function () {
  26200. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26201. return 0;
  26202. };
  26203. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26204. /** @hidden */
  26205. get: function () {
  26206. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26207. return null;
  26208. },
  26209. enumerable: true,
  26210. configurable: true
  26211. });
  26212. /** @hidden */
  26213. Scene.prototype.getLastFrameDuration = function () {
  26214. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26215. return 0;
  26216. };
  26217. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26218. /** @hidden */
  26219. get: function () {
  26220. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26221. return null;
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. /** @hidden */
  26227. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26228. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26229. return 0;
  26230. };
  26231. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26232. /** @hidden */
  26233. get: function () {
  26234. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26235. return null;
  26236. },
  26237. enumerable: true,
  26238. configurable: true
  26239. });
  26240. /**
  26241. * Gets the array of active meshes
  26242. * @returns an array of AbstractMesh
  26243. */
  26244. Scene.prototype.getActiveMeshes = function () {
  26245. return this._activeMeshes;
  26246. };
  26247. /** @hidden */
  26248. Scene.prototype.getRenderTargetsDuration = function () {
  26249. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26250. return 0;
  26251. };
  26252. /** @hidden */
  26253. Scene.prototype.getRenderDuration = function () {
  26254. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26255. return 0;
  26256. };
  26257. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26258. /** @hidden */
  26259. get: function () {
  26260. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26261. return null;
  26262. },
  26263. enumerable: true,
  26264. configurable: true
  26265. });
  26266. /** @hidden */
  26267. Scene.prototype.getParticlesDuration = function () {
  26268. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26269. return 0;
  26270. };
  26271. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26272. /** @hidden */
  26273. get: function () {
  26274. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26275. return null;
  26276. },
  26277. enumerable: true,
  26278. configurable: true
  26279. });
  26280. /** @hidden */
  26281. Scene.prototype.getSpritesDuration = function () {
  26282. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26283. return 0;
  26284. };
  26285. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26286. /** @hidden */
  26287. get: function () {
  26288. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26289. return null;
  26290. },
  26291. enumerable: true,
  26292. configurable: true
  26293. });
  26294. /**
  26295. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26296. * @returns a number
  26297. */
  26298. Scene.prototype.getAnimationRatio = function () {
  26299. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26300. };
  26301. /**
  26302. * Gets an unique Id for the current render phase
  26303. * @returns a number
  26304. */
  26305. Scene.prototype.getRenderId = function () {
  26306. return this._renderId;
  26307. };
  26308. /**
  26309. * Gets an unique Id for the current frame
  26310. * @returns a number
  26311. */
  26312. Scene.prototype.getFrameId = function () {
  26313. return this._frameId;
  26314. };
  26315. /** Call this function if you want to manually increment the render Id*/
  26316. Scene.prototype.incrementRenderId = function () {
  26317. this._renderId++;
  26318. };
  26319. Scene.prototype._updatePointerPosition = function (evt) {
  26320. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26321. if (!canvasRect) {
  26322. return;
  26323. }
  26324. this._pointerX = evt.clientX - canvasRect.left;
  26325. this._pointerY = evt.clientY - canvasRect.top;
  26326. this._unTranslatedPointerX = this._pointerX;
  26327. this._unTranslatedPointerY = this._pointerY;
  26328. };
  26329. Scene.prototype._createUbo = function () {
  26330. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26331. this._sceneUbo.addUniform("viewProjection", 16);
  26332. this._sceneUbo.addUniform("view", 16);
  26333. };
  26334. Scene.prototype._createAlternateUbo = function () {
  26335. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26336. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26337. this._alternateSceneUbo.addUniform("view", 16);
  26338. };
  26339. // Pointers handling
  26340. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26341. if (pointerInfo.pickInfo) {
  26342. if (!pointerInfo.pickInfo.ray) {
  26343. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26344. }
  26345. }
  26346. };
  26347. /**
  26348. * Use this method to simulate a pointer move on a mesh
  26349. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26350. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26351. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26352. * @returns the current scene
  26353. */
  26354. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26355. var evt = new PointerEvent("pointermove", pointerEventInit);
  26356. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26357. return this;
  26358. }
  26359. return this._processPointerMove(pickResult, evt);
  26360. };
  26361. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26362. var canvas = this._engine.getRenderingCanvas();
  26363. if (!canvas) {
  26364. return this;
  26365. }
  26366. // Restore pointer
  26367. canvas.style.cursor = this.defaultCursor;
  26368. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26369. if (isMeshPicked) {
  26370. this.setPointerOverMesh(pickResult.pickedMesh);
  26371. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26372. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26373. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26374. }
  26375. else {
  26376. canvas.style.cursor = this.hoverCursor;
  26377. }
  26378. }
  26379. }
  26380. else {
  26381. this.setPointerOverMesh(null);
  26382. }
  26383. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26384. var step = _a[_i];
  26385. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26386. }
  26387. if (pickResult) {
  26388. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26389. if (this.onPointerMove) {
  26390. this.onPointerMove(evt, pickResult, type);
  26391. }
  26392. if (this.onPointerObservable.hasObservers()) {
  26393. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26394. this._setRayOnPointerInfo(pi);
  26395. this.onPointerObservable.notifyObservers(pi, type);
  26396. }
  26397. }
  26398. return this;
  26399. };
  26400. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26401. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26402. if (pickResult) {
  26403. pi.ray = pickResult.ray;
  26404. }
  26405. this.onPrePointerObservable.notifyObservers(pi, type);
  26406. if (pi.skipOnPointerObservable) {
  26407. return true;
  26408. }
  26409. else {
  26410. return false;
  26411. }
  26412. };
  26413. /**
  26414. * Use this method to simulate a pointer down on a mesh
  26415. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26416. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26417. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26418. * @returns the current scene
  26419. */
  26420. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26421. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26422. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26423. return this;
  26424. }
  26425. return this._processPointerDown(pickResult, evt);
  26426. };
  26427. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26428. var _this = this;
  26429. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26430. this._pickedDownMesh = pickResult.pickedMesh;
  26431. var actionManager = pickResult.pickedMesh.actionManager;
  26432. if (actionManager) {
  26433. if (actionManager.hasPickTriggers) {
  26434. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26435. switch (evt.button) {
  26436. case 0:
  26437. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26438. break;
  26439. case 1:
  26440. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26441. break;
  26442. case 2:
  26443. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26444. break;
  26445. }
  26446. }
  26447. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26448. window.setTimeout(function () {
  26449. 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);
  26450. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26451. if (_this._totalPointersPressed !== 0 &&
  26452. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26453. !_this._isPointerSwiping()) {
  26454. _this._startingPointerTime = 0;
  26455. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26456. }
  26457. }
  26458. }, Scene.LongPressDelay);
  26459. }
  26460. }
  26461. }
  26462. else {
  26463. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26464. var step = _a[_i];
  26465. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26466. }
  26467. }
  26468. if (pickResult) {
  26469. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26470. if (this.onPointerDown) {
  26471. this.onPointerDown(evt, pickResult, type);
  26472. }
  26473. if (this.onPointerObservable.hasObservers()) {
  26474. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26475. this._setRayOnPointerInfo(pi);
  26476. this.onPointerObservable.notifyObservers(pi, type);
  26477. }
  26478. }
  26479. return this;
  26480. };
  26481. /**
  26482. * Use this method to simulate a pointer up on a mesh
  26483. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26484. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26485. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26486. * @returns the current scene
  26487. */
  26488. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26489. var evt = new PointerEvent("pointerup", pointerEventInit);
  26490. var clickInfo = new ClickInfo();
  26491. clickInfo.singleClick = true;
  26492. clickInfo.ignore = true;
  26493. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26494. return this;
  26495. }
  26496. return this._processPointerUp(pickResult, evt, clickInfo);
  26497. };
  26498. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26499. if (pickResult && pickResult && pickResult.pickedMesh) {
  26500. this._pickedUpMesh = pickResult.pickedMesh;
  26501. if (this._pickedDownMesh === this._pickedUpMesh) {
  26502. if (this.onPointerPick) {
  26503. this.onPointerPick(evt, pickResult);
  26504. }
  26505. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26506. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26507. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26508. this._setRayOnPointerInfo(pi);
  26509. this.onPointerObservable.notifyObservers(pi, type_1);
  26510. }
  26511. }
  26512. if (pickResult.pickedMesh.actionManager) {
  26513. if (clickInfo.ignore) {
  26514. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26515. }
  26516. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26517. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26518. }
  26519. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26520. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26521. }
  26522. }
  26523. }
  26524. else {
  26525. if (!clickInfo.ignore) {
  26526. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26527. var step = _a[_i];
  26528. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26529. }
  26530. }
  26531. }
  26532. if (this._pickedDownMesh &&
  26533. this._pickedDownMesh.actionManager &&
  26534. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26535. this._pickedDownMesh !== this._pickedUpMesh) {
  26536. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26537. }
  26538. var type = BABYLON.PointerEventTypes.POINTERUP;
  26539. if (this.onPointerObservable.hasObservers()) {
  26540. if (!clickInfo.ignore) {
  26541. if (!clickInfo.hasSwiped) {
  26542. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26543. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26544. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26545. this._setRayOnPointerInfo(pi);
  26546. this.onPointerObservable.notifyObservers(pi, type_2);
  26547. }
  26548. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26549. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26550. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26551. this._setRayOnPointerInfo(pi);
  26552. this.onPointerObservable.notifyObservers(pi, type_3);
  26553. }
  26554. }
  26555. }
  26556. else {
  26557. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26558. this._setRayOnPointerInfo(pi);
  26559. this.onPointerObservable.notifyObservers(pi, type);
  26560. }
  26561. }
  26562. if (this.onPointerUp) {
  26563. this.onPointerUp(evt, pickResult, type);
  26564. }
  26565. return this;
  26566. };
  26567. /**
  26568. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26569. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26570. * @returns true if the pointer was captured
  26571. */
  26572. Scene.prototype.isPointerCaptured = function (pointerId) {
  26573. if (pointerId === void 0) { pointerId = 0; }
  26574. return this._pointerCaptures[pointerId];
  26575. };
  26576. /** @hidden */
  26577. Scene.prototype._isPointerSwiping = function () {
  26578. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26579. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26580. };
  26581. /**
  26582. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26583. * @param attachUp defines if you want to attach events to pointerup
  26584. * @param attachDown defines if you want to attach events to pointerdown
  26585. * @param attachMove defines if you want to attach events to pointermove
  26586. */
  26587. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26588. var _this = this;
  26589. if (attachUp === void 0) { attachUp = true; }
  26590. if (attachDown === void 0) { attachDown = true; }
  26591. if (attachMove === void 0) { attachMove = true; }
  26592. this._initActionManager = function (act, clickInfo) {
  26593. if (!_this._meshPickProceed) {
  26594. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26595. _this._currentPickResult = pickResult;
  26596. if (pickResult) {
  26597. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26598. }
  26599. _this._meshPickProceed = true;
  26600. }
  26601. return act;
  26602. };
  26603. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26604. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26605. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26606. btn !== _this._previousButtonPressed) {
  26607. _this._doubleClickOccured = false;
  26608. clickInfo.singleClick = true;
  26609. clickInfo.ignore = false;
  26610. cb(clickInfo, _this._currentPickResult);
  26611. }
  26612. };
  26613. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26614. var clickInfo = new ClickInfo();
  26615. _this._currentPickResult = null;
  26616. var act = null;
  26617. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26618. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26619. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26620. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26621. act = _this._initActionManager(act, clickInfo);
  26622. if (act)
  26623. checkPicking = act.hasPickTriggers;
  26624. }
  26625. if (checkPicking) {
  26626. var btn = evt.button;
  26627. clickInfo.hasSwiped = _this._isPointerSwiping();
  26628. if (!clickInfo.hasSwiped) {
  26629. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26630. if (!checkSingleClickImmediately) {
  26631. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26632. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26633. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26634. act = _this._initActionManager(act, clickInfo);
  26635. if (act)
  26636. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26637. }
  26638. }
  26639. if (checkSingleClickImmediately) {
  26640. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26641. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26642. btn !== _this._previousButtonPressed) {
  26643. clickInfo.singleClick = true;
  26644. cb(clickInfo, _this._currentPickResult);
  26645. }
  26646. }
  26647. // at least one double click is required to be check and exclusive double click is enabled
  26648. else {
  26649. // wait that no double click has been raised during the double click delay
  26650. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26651. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26652. }
  26653. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26654. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26655. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26656. act = _this._initActionManager(act, clickInfo);
  26657. if (act)
  26658. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26659. }
  26660. if (checkDoubleClick) {
  26661. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26662. if (btn === _this._previousButtonPressed &&
  26663. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26664. !_this._doubleClickOccured) {
  26665. // pointer has not moved for 2 clicks, it's a double click
  26666. if (!clickInfo.hasSwiped &&
  26667. !_this._isPointerSwiping()) {
  26668. _this._previousStartingPointerTime = 0;
  26669. _this._doubleClickOccured = true;
  26670. clickInfo.doubleClick = true;
  26671. clickInfo.ignore = false;
  26672. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26673. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26674. }
  26675. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26676. cb(clickInfo, _this._currentPickResult);
  26677. }
  26678. // if the two successive clicks are too far, it's just two simple clicks
  26679. else {
  26680. _this._doubleClickOccured = false;
  26681. _this._previousStartingPointerTime = _this._startingPointerTime;
  26682. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26683. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26684. _this._previousButtonPressed = btn;
  26685. if (Scene.ExclusiveDoubleClickMode) {
  26686. if (_this._previousDelayedSimpleClickTimeout) {
  26687. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26688. }
  26689. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26690. cb(clickInfo, _this._previousPickResult);
  26691. }
  26692. else {
  26693. cb(clickInfo, _this._currentPickResult);
  26694. }
  26695. }
  26696. }
  26697. // just the first click of the double has been raised
  26698. else {
  26699. _this._doubleClickOccured = false;
  26700. _this._previousStartingPointerTime = _this._startingPointerTime;
  26701. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26702. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26703. _this._previousButtonPressed = btn;
  26704. }
  26705. }
  26706. }
  26707. }
  26708. clickInfo.ignore = true;
  26709. cb(clickInfo, _this._currentPickResult);
  26710. };
  26711. this._onPointerMove = function (evt) {
  26712. _this._updatePointerPosition(evt);
  26713. // PreObservable support
  26714. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26715. return;
  26716. }
  26717. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26718. return;
  26719. }
  26720. if (!_this.pointerMovePredicate) {
  26721. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26722. }
  26723. // Meshes
  26724. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26725. _this._processPointerMove(pickResult, evt);
  26726. };
  26727. this._onPointerDown = function (evt) {
  26728. _this._totalPointersPressed++;
  26729. _this._pickedDownMesh = null;
  26730. _this._meshPickProceed = false;
  26731. _this._updatePointerPosition(evt);
  26732. if (_this.preventDefaultOnPointerDown && canvas) {
  26733. evt.preventDefault();
  26734. canvas.focus();
  26735. }
  26736. // PreObservable support
  26737. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26738. return;
  26739. }
  26740. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26741. return;
  26742. }
  26743. _this._pointerCaptures[evt.pointerId] = true;
  26744. _this._startingPointerPosition.x = _this._pointerX;
  26745. _this._startingPointerPosition.y = _this._pointerY;
  26746. _this._startingPointerTime = Date.now();
  26747. if (!_this.pointerDownPredicate) {
  26748. _this.pointerDownPredicate = function (mesh) {
  26749. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26750. };
  26751. }
  26752. // Meshes
  26753. _this._pickedDownMesh = null;
  26754. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26755. _this._processPointerDown(pickResult, evt);
  26756. };
  26757. this._onPointerUp = function (evt) {
  26758. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26759. return; // So we need to test it the pointer down was pressed before.
  26760. }
  26761. _this._totalPointersPressed--;
  26762. _this._pickedUpMesh = null;
  26763. _this._meshPickProceed = false;
  26764. _this._updatePointerPosition(evt);
  26765. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26766. // PreObservable support
  26767. if (_this.onPrePointerObservable.hasObservers()) {
  26768. if (!clickInfo.ignore) {
  26769. if (!clickInfo.hasSwiped) {
  26770. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26771. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26772. return;
  26773. }
  26774. }
  26775. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26776. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26777. return;
  26778. }
  26779. }
  26780. }
  26781. }
  26782. else {
  26783. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26784. return;
  26785. }
  26786. }
  26787. }
  26788. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26789. return;
  26790. }
  26791. _this._pointerCaptures[evt.pointerId] = false;
  26792. if (!_this.pointerUpPredicate) {
  26793. _this.pointerUpPredicate = function (mesh) {
  26794. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26795. };
  26796. }
  26797. // Meshes
  26798. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26799. _this._initActionManager(null, clickInfo);
  26800. }
  26801. if (!pickResult) {
  26802. pickResult = _this._currentPickResult;
  26803. }
  26804. _this._processPointerUp(pickResult, evt, clickInfo);
  26805. _this._previousPickResult = _this._currentPickResult;
  26806. });
  26807. };
  26808. this._onKeyDown = function (evt) {
  26809. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26810. if (_this.onPreKeyboardObservable.hasObservers()) {
  26811. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26812. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26813. if (pi.skipOnPointerObservable) {
  26814. return;
  26815. }
  26816. }
  26817. if (_this.onKeyboardObservable.hasObservers()) {
  26818. var pi = new BABYLON.KeyboardInfo(type, evt);
  26819. _this.onKeyboardObservable.notifyObservers(pi, type);
  26820. }
  26821. if (_this.actionManager) {
  26822. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26823. }
  26824. };
  26825. this._onKeyUp = function (evt) {
  26826. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26827. if (_this.onPreKeyboardObservable.hasObservers()) {
  26828. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26829. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26830. if (pi.skipOnPointerObservable) {
  26831. return;
  26832. }
  26833. }
  26834. if (_this.onKeyboardObservable.hasObservers()) {
  26835. var pi = new BABYLON.KeyboardInfo(type, evt);
  26836. _this.onKeyboardObservable.notifyObservers(pi, type);
  26837. }
  26838. if (_this.actionManager) {
  26839. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26840. }
  26841. };
  26842. var engine = this.getEngine();
  26843. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26844. if (!canvas) {
  26845. return;
  26846. }
  26847. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26848. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26849. });
  26850. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26851. if (!canvas) {
  26852. return;
  26853. }
  26854. canvas.removeEventListener("keydown", _this._onKeyDown);
  26855. canvas.removeEventListener("keyup", _this._onKeyUp);
  26856. });
  26857. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26858. var canvas = this._engine.getRenderingCanvas();
  26859. if (!canvas) {
  26860. return;
  26861. }
  26862. if (attachMove) {
  26863. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26864. // Wheel
  26865. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26866. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26867. }
  26868. if (attachDown) {
  26869. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26870. }
  26871. if (attachUp) {
  26872. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26873. }
  26874. canvas.tabIndex = 1;
  26875. };
  26876. /** Detaches all event handlers*/
  26877. Scene.prototype.detachControl = function () {
  26878. var engine = this.getEngine();
  26879. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26880. var canvas = engine.getRenderingCanvas();
  26881. if (!canvas) {
  26882. return;
  26883. }
  26884. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26885. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26886. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26887. if (this._onCanvasBlurObserver) {
  26888. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26889. }
  26890. if (this._onCanvasFocusObserver) {
  26891. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26892. }
  26893. // Wheel
  26894. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26895. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26896. // Keyboard
  26897. canvas.removeEventListener("keydown", this._onKeyDown);
  26898. canvas.removeEventListener("keyup", this._onKeyUp);
  26899. // Observables
  26900. this.onKeyboardObservable.clear();
  26901. this.onPreKeyboardObservable.clear();
  26902. this.onPointerObservable.clear();
  26903. this.onPrePointerObservable.clear();
  26904. };
  26905. /**
  26906. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26907. * Delay loaded resources are not taking in account
  26908. * @return true if all required resources are ready
  26909. */
  26910. Scene.prototype.isReady = function () {
  26911. if (this._isDisposed) {
  26912. return false;
  26913. }
  26914. if (this._pendingData.length > 0) {
  26915. return false;
  26916. }
  26917. var index;
  26918. var engine = this.getEngine();
  26919. // Geometries
  26920. for (index = 0; index < this.geometries.length; index++) {
  26921. var geometry = this.geometries[index];
  26922. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26923. return false;
  26924. }
  26925. }
  26926. // Meshes
  26927. for (index = 0; index < this.meshes.length; index++) {
  26928. var mesh = this.meshes[index];
  26929. if (!mesh.isEnabled()) {
  26930. continue;
  26931. }
  26932. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26933. continue;
  26934. }
  26935. if (!mesh.isReady(true)) {
  26936. return false;
  26937. }
  26938. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26939. // Is Ready For Mesh
  26940. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26941. var step = _a[_i];
  26942. if (!step.action(mesh, hardwareInstancedRendering)) {
  26943. return false;
  26944. }
  26945. }
  26946. }
  26947. // Post-processes
  26948. if (this.activeCameras && this.activeCameras.length > 0) {
  26949. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26950. var camera = _c[_b];
  26951. if (!camera.isReady(true)) {
  26952. return false;
  26953. }
  26954. }
  26955. }
  26956. else if (this.activeCamera) {
  26957. if (!this.activeCamera.isReady(true)) {
  26958. return false;
  26959. }
  26960. }
  26961. // Particles
  26962. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26963. var particleSystem = _e[_d];
  26964. if (!particleSystem.isReady()) {
  26965. return false;
  26966. }
  26967. }
  26968. return true;
  26969. };
  26970. /** Resets all cached information relative to material (including effect and visibility) */
  26971. Scene.prototype.resetCachedMaterial = function () {
  26972. this._cachedMaterial = null;
  26973. this._cachedEffect = null;
  26974. this._cachedVisibility = null;
  26975. };
  26976. /**
  26977. * Registers a function to be called before every frame render
  26978. * @param func defines the function to register
  26979. */
  26980. Scene.prototype.registerBeforeRender = function (func) {
  26981. this.onBeforeRenderObservable.add(func);
  26982. };
  26983. /**
  26984. * Unregisters a function called before every frame render
  26985. * @param func defines the function to unregister
  26986. */
  26987. Scene.prototype.unregisterBeforeRender = function (func) {
  26988. this.onBeforeRenderObservable.removeCallback(func);
  26989. };
  26990. /**
  26991. * Registers a function to be called after every frame render
  26992. * @param func defines the function to register
  26993. */
  26994. Scene.prototype.registerAfterRender = function (func) {
  26995. this.onAfterRenderObservable.add(func);
  26996. };
  26997. /**
  26998. * Unregisters a function called after every frame render
  26999. * @param func defines the function to unregister
  27000. */
  27001. Scene.prototype.unregisterAfterRender = function (func) {
  27002. this.onAfterRenderObservable.removeCallback(func);
  27003. };
  27004. Scene.prototype._executeOnceBeforeRender = function (func) {
  27005. var _this = this;
  27006. var execFunc = function () {
  27007. func();
  27008. setTimeout(function () {
  27009. _this.unregisterBeforeRender(execFunc);
  27010. });
  27011. };
  27012. this.registerBeforeRender(execFunc);
  27013. };
  27014. /**
  27015. * The provided function will run before render once and will be disposed afterwards.
  27016. * A timeout delay can be provided so that the function will be executed in N ms.
  27017. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27018. * @param func The function to be executed.
  27019. * @param timeout optional delay in ms
  27020. */
  27021. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27022. var _this = this;
  27023. if (timeout !== undefined) {
  27024. setTimeout(function () {
  27025. _this._executeOnceBeforeRender(func);
  27026. }, timeout);
  27027. }
  27028. else {
  27029. this._executeOnceBeforeRender(func);
  27030. }
  27031. };
  27032. /** @hidden */
  27033. Scene.prototype._addPendingData = function (data) {
  27034. this._pendingData.push(data);
  27035. };
  27036. /** @hidden */
  27037. Scene.prototype._removePendingData = function (data) {
  27038. var wasLoading = this.isLoading;
  27039. var index = this._pendingData.indexOf(data);
  27040. if (index !== -1) {
  27041. this._pendingData.splice(index, 1);
  27042. }
  27043. if (wasLoading && !this.isLoading) {
  27044. this.onDataLoadedObservable.notifyObservers(this);
  27045. }
  27046. };
  27047. /**
  27048. * Returns the number of items waiting to be loaded
  27049. * @returns the number of items waiting to be loaded
  27050. */
  27051. Scene.prototype.getWaitingItemsCount = function () {
  27052. return this._pendingData.length;
  27053. };
  27054. Object.defineProperty(Scene.prototype, "isLoading", {
  27055. /**
  27056. * Returns a boolean indicating if the scene is still loading data
  27057. */
  27058. get: function () {
  27059. return this._pendingData.length > 0;
  27060. },
  27061. enumerable: true,
  27062. configurable: true
  27063. });
  27064. /**
  27065. * Registers a function to be executed when the scene is ready
  27066. * @param {Function} func - the function to be executed
  27067. */
  27068. Scene.prototype.executeWhenReady = function (func) {
  27069. var _this = this;
  27070. this.onReadyObservable.add(func);
  27071. if (this._executeWhenReadyTimeoutId !== -1) {
  27072. return;
  27073. }
  27074. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27075. _this._checkIsReady();
  27076. }, 150);
  27077. };
  27078. /**
  27079. * Returns a promise that resolves when the scene is ready
  27080. * @returns A promise that resolves when the scene is ready
  27081. */
  27082. Scene.prototype.whenReadyAsync = function () {
  27083. var _this = this;
  27084. return new Promise(function (resolve) {
  27085. _this.executeWhenReady(function () {
  27086. resolve();
  27087. });
  27088. });
  27089. };
  27090. /** @hidden */
  27091. Scene.prototype._checkIsReady = function () {
  27092. var _this = this;
  27093. this._registerTransientComponents();
  27094. if (this.isReady()) {
  27095. this.onReadyObservable.notifyObservers(this);
  27096. this.onReadyObservable.clear();
  27097. this._executeWhenReadyTimeoutId = -1;
  27098. return;
  27099. }
  27100. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27101. _this._checkIsReady();
  27102. }, 150);
  27103. };
  27104. // Animations
  27105. /**
  27106. * Will start the animation sequence of a given target
  27107. * @param target defines the target
  27108. * @param from defines from which frame should animation start
  27109. * @param to defines until which frame should animation run.
  27110. * @param weight defines the weight to apply to the animation (1.0 by default)
  27111. * @param loop defines if the animation loops
  27112. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27113. * @param onAnimationEnd defines the function to be executed when the animation ends
  27114. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27115. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27116. * @returns the animatable object created for this animation
  27117. */
  27118. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27119. if (weight === void 0) { weight = 1.0; }
  27120. if (speedRatio === void 0) { speedRatio = 1.0; }
  27121. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27122. returnedAnimatable.weight = weight;
  27123. return returnedAnimatable;
  27124. };
  27125. /**
  27126. * Will start the animation sequence of a given target
  27127. * @param target defines the target
  27128. * @param from defines from which frame should animation start
  27129. * @param to defines until which frame should animation run.
  27130. * @param loop defines if the animation loops
  27131. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27132. * @param onAnimationEnd defines the function to be executed when the animation ends
  27133. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27134. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27135. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27136. * @returns the animatable object created for this animation
  27137. */
  27138. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27139. if (speedRatio === void 0) { speedRatio = 1.0; }
  27140. if (stopCurrent === void 0) { stopCurrent = true; }
  27141. if (from > to && speedRatio > 0) {
  27142. speedRatio *= -1;
  27143. }
  27144. if (stopCurrent) {
  27145. this.stopAnimation(target, undefined, targetMask);
  27146. }
  27147. if (!animatable) {
  27148. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27149. }
  27150. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27151. // Local animations
  27152. if (target.animations && shouldRunTargetAnimations) {
  27153. animatable.appendAnimations(target, target.animations);
  27154. }
  27155. // Children animations
  27156. if (target.getAnimatables) {
  27157. var animatables = target.getAnimatables();
  27158. for (var index = 0; index < animatables.length; index++) {
  27159. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27160. }
  27161. }
  27162. animatable.reset();
  27163. return animatable;
  27164. };
  27165. /**
  27166. * Begin a new animation on a given node
  27167. * @param target defines the target where the animation will take place
  27168. * @param animations defines the list of animations to start
  27169. * @param from defines the initial value
  27170. * @param to defines the final value
  27171. * @param loop defines if you want animation to loop (off by default)
  27172. * @param speedRatio defines the speed ratio to apply to all animations
  27173. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27174. * @returns the list of created animatables
  27175. */
  27176. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27177. if (speedRatio === undefined) {
  27178. speedRatio = 1.0;
  27179. }
  27180. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27181. return animatable;
  27182. };
  27183. /**
  27184. * Begin a new animation on a given node and its hierarchy
  27185. * @param target defines the root node where the animation will take place
  27186. * @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.
  27187. * @param animations defines the list of animations to start
  27188. * @param from defines the initial value
  27189. * @param to defines the final value
  27190. * @param loop defines if you want animation to loop (off by default)
  27191. * @param speedRatio defines the speed ratio to apply to all animations
  27192. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27193. * @returns the list of animatables created for all nodes
  27194. */
  27195. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27196. var children = target.getDescendants(directDescendantsOnly);
  27197. var result = [];
  27198. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27199. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27200. var child = children_1[_i];
  27201. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27202. }
  27203. return result;
  27204. };
  27205. /**
  27206. * Gets the animatable associated with a specific target
  27207. * @param target defines the target of the animatable
  27208. * @returns the required animatable if found
  27209. */
  27210. Scene.prototype.getAnimatableByTarget = function (target) {
  27211. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27212. if (this._activeAnimatables[index].target === target) {
  27213. return this._activeAnimatables[index];
  27214. }
  27215. }
  27216. return null;
  27217. };
  27218. /**
  27219. * Gets all animatables associated with a given target
  27220. * @param target defines the target to look animatables for
  27221. * @returns an array of Animatables
  27222. */
  27223. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27224. var result = [];
  27225. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27226. if (this._activeAnimatables[index].target === target) {
  27227. result.push(this._activeAnimatables[index]);
  27228. }
  27229. }
  27230. return result;
  27231. };
  27232. Object.defineProperty(Scene.prototype, "animatables", {
  27233. /**
  27234. * Gets all animatable attached to the scene
  27235. */
  27236. get: function () {
  27237. return this._activeAnimatables;
  27238. },
  27239. enumerable: true,
  27240. configurable: true
  27241. });
  27242. /**
  27243. * Will stop the animation of the given target
  27244. * @param target - the target
  27245. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27246. * @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)
  27247. */
  27248. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27249. var animatables = this.getAllAnimatablesByTarget(target);
  27250. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27251. var animatable = animatables_1[_i];
  27252. animatable.stop(animationName, targetMask);
  27253. }
  27254. };
  27255. /**
  27256. * Stops and removes all animations that have been applied to the scene
  27257. */
  27258. Scene.prototype.stopAllAnimations = function () {
  27259. if (this._activeAnimatables) {
  27260. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27261. this._activeAnimatables[i].stop();
  27262. }
  27263. this._activeAnimatables = [];
  27264. }
  27265. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27266. var group = _a[_i];
  27267. group.stop();
  27268. }
  27269. };
  27270. Scene.prototype._animate = function () {
  27271. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27272. return;
  27273. }
  27274. // Getting time
  27275. var now = BABYLON.Tools.Now;
  27276. if (!this._animationTimeLast) {
  27277. if (this._pendingData.length > 0) {
  27278. return;
  27279. }
  27280. this._animationTimeLast = now;
  27281. }
  27282. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27283. this._animationTime += deltaTime;
  27284. this._animationTimeLast = now;
  27285. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27286. this._activeAnimatables[index]._animate(this._animationTime);
  27287. }
  27288. // Late animation bindings
  27289. this._processLateAnimationBindings();
  27290. };
  27291. /** @hidden */
  27292. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27293. var target = runtimeAnimation.target;
  27294. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27295. if (!target._lateAnimationHolders) {
  27296. target._lateAnimationHolders = {};
  27297. }
  27298. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27299. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27300. totalWeight: 0,
  27301. animations: [],
  27302. originalValue: originalValue
  27303. };
  27304. }
  27305. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27306. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27307. };
  27308. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27309. var normalizer = 1.0;
  27310. var finalPosition = BABYLON.Tmp.Vector3[0];
  27311. var finalScaling = BABYLON.Tmp.Vector3[1];
  27312. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27313. var startIndex = 0;
  27314. var originalAnimation = holder.animations[0];
  27315. var originalValue = holder.originalValue;
  27316. var scale = 1;
  27317. if (holder.totalWeight < 1.0) {
  27318. // We need to mix the original value in
  27319. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27320. scale = 1.0 - holder.totalWeight;
  27321. }
  27322. else {
  27323. startIndex = 1;
  27324. // We need to normalize the weights
  27325. normalizer = holder.totalWeight;
  27326. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27327. scale = originalAnimation.weight / normalizer;
  27328. if (scale == 1) {
  27329. return originalAnimation.currentValue;
  27330. }
  27331. }
  27332. finalScaling.scaleInPlace(scale);
  27333. finalPosition.scaleInPlace(scale);
  27334. finalQuaternion.scaleInPlace(scale);
  27335. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27336. var runtimeAnimation = holder.animations[animIndex];
  27337. var scale = runtimeAnimation.weight / normalizer;
  27338. var currentPosition = BABYLON.Tmp.Vector3[2];
  27339. var currentScaling = BABYLON.Tmp.Vector3[3];
  27340. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27341. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27342. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27343. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27344. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27345. }
  27346. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27347. return originalAnimation._workValue;
  27348. };
  27349. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27350. var originalAnimation = holder.animations[0];
  27351. var originalValue = holder.originalValue;
  27352. if (holder.animations.length === 1) {
  27353. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27354. return refQuaternion;
  27355. }
  27356. var normalizer = 1.0;
  27357. var quaternions;
  27358. var weights;
  27359. if (holder.totalWeight < 1.0) {
  27360. var scale = 1.0 - holder.totalWeight;
  27361. quaternions = [];
  27362. weights = [];
  27363. quaternions.push(originalValue);
  27364. weights.push(scale);
  27365. }
  27366. else {
  27367. if (holder.animations.length === 2) { // Slerp as soon as we can
  27368. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27369. return refQuaternion;
  27370. }
  27371. quaternions = [];
  27372. weights = [];
  27373. normalizer = holder.totalWeight;
  27374. }
  27375. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27376. var runtimeAnimation = holder.animations[animIndex];
  27377. quaternions.push(runtimeAnimation.currentValue);
  27378. weights.push(runtimeAnimation.weight / normalizer);
  27379. }
  27380. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27381. var cumulativeAmount = 0;
  27382. var cumulativeQuaternion = null;
  27383. for (var index = 0; index < quaternions.length;) {
  27384. if (!cumulativeQuaternion) {
  27385. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27386. cumulativeQuaternion = refQuaternion;
  27387. cumulativeAmount = weights[index] + weights[index + 1];
  27388. index += 2;
  27389. continue;
  27390. }
  27391. cumulativeAmount += weights[index];
  27392. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27393. index++;
  27394. }
  27395. return cumulativeQuaternion;
  27396. };
  27397. Scene.prototype._processLateAnimationBindings = function () {
  27398. if (!this._registeredForLateAnimationBindings.length) {
  27399. return;
  27400. }
  27401. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27402. var target = this._registeredForLateAnimationBindings.data[index];
  27403. for (var path in target._lateAnimationHolders) {
  27404. var holder = target._lateAnimationHolders[path];
  27405. var originalAnimation = holder.animations[0];
  27406. var originalValue = holder.originalValue;
  27407. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27408. var finalValue = target[path];
  27409. if (matrixDecomposeMode) {
  27410. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27411. }
  27412. else {
  27413. var quaternionMode = originalValue.w !== undefined;
  27414. if (quaternionMode) {
  27415. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27416. }
  27417. else {
  27418. var startIndex = 0;
  27419. var normalizer = 1.0;
  27420. if (holder.totalWeight < 1.0) {
  27421. // We need to mix the original value in
  27422. if (originalValue.scale) {
  27423. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27424. }
  27425. else {
  27426. finalValue = originalValue * (1.0 - holder.totalWeight);
  27427. }
  27428. }
  27429. else {
  27430. // We need to normalize the weights
  27431. normalizer = holder.totalWeight;
  27432. var scale_1 = originalAnimation.weight / normalizer;
  27433. if (scale_1 !== 1) {
  27434. if (originalAnimation.currentValue.scale) {
  27435. finalValue = originalAnimation.currentValue.scale(scale_1);
  27436. }
  27437. else {
  27438. finalValue = originalAnimation.currentValue * scale_1;
  27439. }
  27440. }
  27441. else {
  27442. finalValue = originalAnimation.currentValue;
  27443. }
  27444. startIndex = 1;
  27445. }
  27446. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27447. var runtimeAnimation = holder.animations[animIndex];
  27448. var scale = runtimeAnimation.weight / normalizer;
  27449. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27450. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27451. }
  27452. else {
  27453. finalValue += runtimeAnimation.currentValue * scale;
  27454. }
  27455. }
  27456. }
  27457. }
  27458. target[path] = finalValue;
  27459. }
  27460. target._lateAnimationHolders = {};
  27461. }
  27462. this._registeredForLateAnimationBindings.reset();
  27463. };
  27464. // Matrix
  27465. /** @hidden */
  27466. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27467. this._useAlternateCameraConfiguration = active;
  27468. };
  27469. /**
  27470. * Gets the current view matrix
  27471. * @returns a Matrix
  27472. */
  27473. Scene.prototype.getViewMatrix = function () {
  27474. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27475. };
  27476. /**
  27477. * Gets the current projection matrix
  27478. * @returns a Matrix
  27479. */
  27480. Scene.prototype.getProjectionMatrix = function () {
  27481. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27482. };
  27483. /**
  27484. * Gets the current transform matrix
  27485. * @returns a Matrix made of View * Projection
  27486. */
  27487. Scene.prototype.getTransformMatrix = function () {
  27488. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27489. };
  27490. /**
  27491. * Sets the current transform matrix
  27492. * @param view defines the View matrix to use
  27493. * @param projection defines the Projection matrix to use
  27494. */
  27495. Scene.prototype.setTransformMatrix = function (view, projection) {
  27496. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27497. return;
  27498. }
  27499. this._viewUpdateFlag = view.updateFlag;
  27500. this._projectionUpdateFlag = projection.updateFlag;
  27501. this._viewMatrix = view;
  27502. this._projectionMatrix = projection;
  27503. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27504. // Update frustum
  27505. if (!this._frustumPlanes) {
  27506. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27507. }
  27508. else {
  27509. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27510. }
  27511. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27512. var otherCamera = this.activeCamera._alternateCamera;
  27513. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27514. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27515. }
  27516. if (this._sceneUbo.useUbo) {
  27517. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27518. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27519. this._sceneUbo.update();
  27520. }
  27521. };
  27522. /** @hidden */
  27523. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27524. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27525. return;
  27526. }
  27527. this._alternateViewUpdateFlag = view.updateFlag;
  27528. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27529. this._alternateViewMatrix = view;
  27530. this._alternateProjectionMatrix = projection;
  27531. if (!this._alternateTransformMatrix) {
  27532. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27533. }
  27534. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27535. if (!this._alternateSceneUbo) {
  27536. this._createAlternateUbo();
  27537. }
  27538. if (this._alternateSceneUbo.useUbo) {
  27539. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27540. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27541. this._alternateSceneUbo.update();
  27542. }
  27543. };
  27544. /**
  27545. * Gets the uniform buffer used to store scene data
  27546. * @returns a UniformBuffer
  27547. */
  27548. Scene.prototype.getSceneUniformBuffer = function () {
  27549. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27550. };
  27551. /**
  27552. * Gets an unique (relatively to the current scene) Id
  27553. * @returns an unique number for the scene
  27554. */
  27555. Scene.prototype.getUniqueId = function () {
  27556. var result = Scene._uniqueIdCounter;
  27557. Scene._uniqueIdCounter++;
  27558. return result;
  27559. };
  27560. /**
  27561. * Add a mesh to the list of scene's meshes
  27562. * @param newMesh defines the mesh to add
  27563. * @param recursive if all child meshes should also be added to the scene
  27564. */
  27565. Scene.prototype.addMesh = function (newMesh, recursive) {
  27566. var _this = this;
  27567. if (recursive === void 0) { recursive = false; }
  27568. this.meshes.push(newMesh);
  27569. //notify the collision coordinator
  27570. if (this.collisionCoordinator) {
  27571. this.collisionCoordinator.onMeshAdded(newMesh);
  27572. }
  27573. newMesh._resyncLightSources();
  27574. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27575. if (recursive) {
  27576. newMesh.getChildMeshes().forEach(function (m) {
  27577. _this.addMesh(m);
  27578. });
  27579. }
  27580. };
  27581. /**
  27582. * Remove a mesh for the list of scene's meshes
  27583. * @param toRemove defines the mesh to remove
  27584. * @param recursive if all child meshes should also be removed from the scene
  27585. * @returns the index where the mesh was in the mesh list
  27586. */
  27587. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27588. var _this = this;
  27589. if (recursive === void 0) { recursive = false; }
  27590. var index = this.meshes.indexOf(toRemove);
  27591. if (index !== -1) {
  27592. // Remove from the scene if mesh found
  27593. this.meshes.splice(index, 1);
  27594. }
  27595. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27596. if (recursive) {
  27597. toRemove.getChildMeshes().forEach(function (m) {
  27598. _this.removeMesh(m);
  27599. });
  27600. }
  27601. return index;
  27602. };
  27603. /**
  27604. * Add a transform node to the list of scene's transform nodes
  27605. * @param newTransformNode defines the transform node to add
  27606. */
  27607. Scene.prototype.addTransformNode = function (newTransformNode) {
  27608. this.transformNodes.push(newTransformNode);
  27609. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27610. };
  27611. /**
  27612. * Remove a transform node for the list of scene's transform nodes
  27613. * @param toRemove defines the transform node to remove
  27614. * @returns the index where the transform node was in the transform node list
  27615. */
  27616. Scene.prototype.removeTransformNode = function (toRemove) {
  27617. var index = this.transformNodes.indexOf(toRemove);
  27618. if (index !== -1) {
  27619. // Remove from the scene if found
  27620. this.transformNodes.splice(index, 1);
  27621. }
  27622. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27623. return index;
  27624. };
  27625. /**
  27626. * Remove a skeleton for the list of scene's skeletons
  27627. * @param toRemove defines the skeleton to remove
  27628. * @returns the index where the skeleton was in the skeleton list
  27629. */
  27630. Scene.prototype.removeSkeleton = function (toRemove) {
  27631. var index = this.skeletons.indexOf(toRemove);
  27632. if (index !== -1) {
  27633. // Remove from the scene if found
  27634. this.skeletons.splice(index, 1);
  27635. }
  27636. return index;
  27637. };
  27638. /**
  27639. * Remove a morph target for the list of scene's morph targets
  27640. * @param toRemove defines the morph target to remove
  27641. * @returns the index where the morph target was in the morph target list
  27642. */
  27643. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27644. var index = this.morphTargetManagers.indexOf(toRemove);
  27645. if (index !== -1) {
  27646. // Remove from the scene if found
  27647. this.morphTargetManagers.splice(index, 1);
  27648. }
  27649. return index;
  27650. };
  27651. /**
  27652. * Remove a light for the list of scene's lights
  27653. * @param toRemove defines the light to remove
  27654. * @returns the index where the light was in the light list
  27655. */
  27656. Scene.prototype.removeLight = function (toRemove) {
  27657. var index = this.lights.indexOf(toRemove);
  27658. if (index !== -1) {
  27659. // Remove from meshes
  27660. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27661. var mesh = _a[_i];
  27662. mesh._removeLightSource(toRemove);
  27663. }
  27664. // Remove from the scene if mesh found
  27665. this.lights.splice(index, 1);
  27666. this.sortLightsByPriority();
  27667. }
  27668. this.onLightRemovedObservable.notifyObservers(toRemove);
  27669. return index;
  27670. };
  27671. /**
  27672. * Remove a camera for the list of scene's cameras
  27673. * @param toRemove defines the camera to remove
  27674. * @returns the index where the camera was in the camera list
  27675. */
  27676. Scene.prototype.removeCamera = function (toRemove) {
  27677. var index = this.cameras.indexOf(toRemove);
  27678. if (index !== -1) {
  27679. // Remove from the scene if mesh found
  27680. this.cameras.splice(index, 1);
  27681. }
  27682. // Remove from activeCameras
  27683. var index2 = this.activeCameras.indexOf(toRemove);
  27684. if (index2 !== -1) {
  27685. // Remove from the scene if mesh found
  27686. this.activeCameras.splice(index2, 1);
  27687. }
  27688. // Reset the activeCamera
  27689. if (this.activeCamera === toRemove) {
  27690. if (this.cameras.length > 0) {
  27691. this.activeCamera = this.cameras[0];
  27692. }
  27693. else {
  27694. this.activeCamera = null;
  27695. }
  27696. }
  27697. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27698. return index;
  27699. };
  27700. /**
  27701. * Remove a particle system for the list of scene's particle systems
  27702. * @param toRemove defines the particle system to remove
  27703. * @returns the index where the particle system was in the particle system list
  27704. */
  27705. Scene.prototype.removeParticleSystem = function (toRemove) {
  27706. var index = this.particleSystems.indexOf(toRemove);
  27707. if (index !== -1) {
  27708. this.particleSystems.splice(index, 1);
  27709. }
  27710. return index;
  27711. };
  27712. /**
  27713. * Remove a animation for the list of scene's animations
  27714. * @param toRemove defines the animation to remove
  27715. * @returns the index where the animation was in the animation list
  27716. */
  27717. Scene.prototype.removeAnimation = function (toRemove) {
  27718. var index = this.animations.indexOf(toRemove);
  27719. if (index !== -1) {
  27720. this.animations.splice(index, 1);
  27721. }
  27722. return index;
  27723. };
  27724. /**
  27725. * Removes the given animation group from this scene.
  27726. * @param toRemove The animation group to remove
  27727. * @returns The index of the removed animation group
  27728. */
  27729. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27730. var index = this.animationGroups.indexOf(toRemove);
  27731. if (index !== -1) {
  27732. this.animationGroups.splice(index, 1);
  27733. }
  27734. return index;
  27735. };
  27736. /**
  27737. * Removes the given multi-material from this scene.
  27738. * @param toRemove The multi-material to remove
  27739. * @returns The index of the removed multi-material
  27740. */
  27741. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27742. var index = this.multiMaterials.indexOf(toRemove);
  27743. if (index !== -1) {
  27744. this.multiMaterials.splice(index, 1);
  27745. }
  27746. return index;
  27747. };
  27748. /**
  27749. * Removes the given material from this scene.
  27750. * @param toRemove The material to remove
  27751. * @returns The index of the removed material
  27752. */
  27753. Scene.prototype.removeMaterial = function (toRemove) {
  27754. var index = this.materials.indexOf(toRemove);
  27755. if (index !== -1) {
  27756. this.materials.splice(index, 1);
  27757. }
  27758. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27759. return index;
  27760. };
  27761. /**
  27762. * Removes the given action manager from this scene.
  27763. * @param toRemove The action manager to remove
  27764. * @returns The index of the removed action manager
  27765. */
  27766. Scene.prototype.removeActionManager = function (toRemove) {
  27767. var index = this.actionManagers.indexOf(toRemove);
  27768. if (index !== -1) {
  27769. this.actionManagers.splice(index, 1);
  27770. }
  27771. return index;
  27772. };
  27773. /**
  27774. * Removes the given texture from this scene.
  27775. * @param toRemove The texture to remove
  27776. * @returns The index of the removed texture
  27777. */
  27778. Scene.prototype.removeTexture = function (toRemove) {
  27779. var index = this.textures.indexOf(toRemove);
  27780. if (index !== -1) {
  27781. this.textures.splice(index, 1);
  27782. }
  27783. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27784. return index;
  27785. };
  27786. /**
  27787. * Adds the given light to this scene
  27788. * @param newLight The light to add
  27789. */
  27790. Scene.prototype.addLight = function (newLight) {
  27791. this.lights.push(newLight);
  27792. this.sortLightsByPriority();
  27793. // Add light to all meshes (To support if the light is removed and then readded)
  27794. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27795. var mesh = _a[_i];
  27796. if (mesh._lightSources.indexOf(newLight) === -1) {
  27797. mesh._lightSources.push(newLight);
  27798. mesh._resyncLightSources();
  27799. }
  27800. }
  27801. this.onNewLightAddedObservable.notifyObservers(newLight);
  27802. };
  27803. /**
  27804. * Sorts the list list based on light priorities
  27805. */
  27806. Scene.prototype.sortLightsByPriority = function () {
  27807. if (this.requireLightSorting) {
  27808. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27809. }
  27810. };
  27811. /**
  27812. * Adds the given camera to this scene
  27813. * @param newCamera The camera to add
  27814. */
  27815. Scene.prototype.addCamera = function (newCamera) {
  27816. this.cameras.push(newCamera);
  27817. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27818. };
  27819. /**
  27820. * Adds the given skeleton to this scene
  27821. * @param newSkeleton The skeleton to add
  27822. */
  27823. Scene.prototype.addSkeleton = function (newSkeleton) {
  27824. this.skeletons.push(newSkeleton);
  27825. };
  27826. /**
  27827. * Adds the given particle system to this scene
  27828. * @param newParticleSystem The particle system to add
  27829. */
  27830. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27831. this.particleSystems.push(newParticleSystem);
  27832. };
  27833. /**
  27834. * Adds the given animation to this scene
  27835. * @param newAnimation The animation to add
  27836. */
  27837. Scene.prototype.addAnimation = function (newAnimation) {
  27838. this.animations.push(newAnimation);
  27839. };
  27840. /**
  27841. * Adds the given animation group to this scene.
  27842. * @param newAnimationGroup The animation group to add
  27843. */
  27844. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27845. this.animationGroups.push(newAnimationGroup);
  27846. };
  27847. /**
  27848. * Adds the given multi-material to this scene
  27849. * @param newMultiMaterial The multi-material to add
  27850. */
  27851. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27852. this.multiMaterials.push(newMultiMaterial);
  27853. };
  27854. /**
  27855. * Adds the given material to this scene
  27856. * @param newMaterial The material to add
  27857. */
  27858. Scene.prototype.addMaterial = function (newMaterial) {
  27859. this.materials.push(newMaterial);
  27860. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27861. };
  27862. /**
  27863. * Adds the given morph target to this scene
  27864. * @param newMorphTargetManager The morph target to add
  27865. */
  27866. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27867. this.morphTargetManagers.push(newMorphTargetManager);
  27868. };
  27869. /**
  27870. * Adds the given geometry to this scene
  27871. * @param newGeometry The geometry to add
  27872. */
  27873. Scene.prototype.addGeometry = function (newGeometry) {
  27874. this.geometries.push(newGeometry);
  27875. };
  27876. /**
  27877. * Adds the given action manager to this scene
  27878. * @param newActionManager The action manager to add
  27879. */
  27880. Scene.prototype.addActionManager = function (newActionManager) {
  27881. this.actionManagers.push(newActionManager);
  27882. };
  27883. /**
  27884. * Adds the given texture to this scene.
  27885. * @param newTexture The texture to add
  27886. */
  27887. Scene.prototype.addTexture = function (newTexture) {
  27888. this.textures.push(newTexture);
  27889. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27890. };
  27891. /**
  27892. * Switch active camera
  27893. * @param newCamera defines the new active camera
  27894. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27895. */
  27896. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27897. if (attachControl === void 0) { attachControl = true; }
  27898. var canvas = this._engine.getRenderingCanvas();
  27899. if (!canvas) {
  27900. return;
  27901. }
  27902. if (this.activeCamera) {
  27903. this.activeCamera.detachControl(canvas);
  27904. }
  27905. this.activeCamera = newCamera;
  27906. if (attachControl) {
  27907. newCamera.attachControl(canvas);
  27908. }
  27909. };
  27910. /**
  27911. * sets the active camera of the scene using its ID
  27912. * @param id defines the camera's ID
  27913. * @return the new active camera or null if none found.
  27914. */
  27915. Scene.prototype.setActiveCameraByID = function (id) {
  27916. var camera = this.getCameraByID(id);
  27917. if (camera) {
  27918. this.activeCamera = camera;
  27919. return camera;
  27920. }
  27921. return null;
  27922. };
  27923. /**
  27924. * sets the active camera of the scene using its name
  27925. * @param name defines the camera's name
  27926. * @returns the new active camera or null if none found.
  27927. */
  27928. Scene.prototype.setActiveCameraByName = function (name) {
  27929. var camera = this.getCameraByName(name);
  27930. if (camera) {
  27931. this.activeCamera = camera;
  27932. return camera;
  27933. }
  27934. return null;
  27935. };
  27936. /**
  27937. * get an animation group using its name
  27938. * @param name defines the material's name
  27939. * @return the animation group or null if none found.
  27940. */
  27941. Scene.prototype.getAnimationGroupByName = function (name) {
  27942. for (var index = 0; index < this.animationGroups.length; index++) {
  27943. if (this.animationGroups[index].name === name) {
  27944. return this.animationGroups[index];
  27945. }
  27946. }
  27947. return null;
  27948. };
  27949. /**
  27950. * get a material using its id
  27951. * @param id defines the material's ID
  27952. * @return the material or null if none found.
  27953. */
  27954. Scene.prototype.getMaterialByID = function (id) {
  27955. for (var index = 0; index < this.materials.length; index++) {
  27956. if (this.materials[index].id === id) {
  27957. return this.materials[index];
  27958. }
  27959. }
  27960. return null;
  27961. };
  27962. /**
  27963. * Gets a material using its name
  27964. * @param name defines the material's name
  27965. * @return the material or null if none found.
  27966. */
  27967. Scene.prototype.getMaterialByName = function (name) {
  27968. for (var index = 0; index < this.materials.length; index++) {
  27969. if (this.materials[index].name === name) {
  27970. return this.materials[index];
  27971. }
  27972. }
  27973. return null;
  27974. };
  27975. /**
  27976. * Gets a camera using its id
  27977. * @param id defines the id to look for
  27978. * @returns the camera or null if not found
  27979. */
  27980. Scene.prototype.getCameraByID = function (id) {
  27981. for (var index = 0; index < this.cameras.length; index++) {
  27982. if (this.cameras[index].id === id) {
  27983. return this.cameras[index];
  27984. }
  27985. }
  27986. return null;
  27987. };
  27988. /**
  27989. * Gets a camera using its unique id
  27990. * @param uniqueId defines the unique id to look for
  27991. * @returns the camera or null if not found
  27992. */
  27993. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27994. for (var index = 0; index < this.cameras.length; index++) {
  27995. if (this.cameras[index].uniqueId === uniqueId) {
  27996. return this.cameras[index];
  27997. }
  27998. }
  27999. return null;
  28000. };
  28001. /**
  28002. * Gets a camera using its name
  28003. * @param name defines the camera's name
  28004. * @return the camera or null if none found.
  28005. */
  28006. Scene.prototype.getCameraByName = function (name) {
  28007. for (var index = 0; index < this.cameras.length; index++) {
  28008. if (this.cameras[index].name === name) {
  28009. return this.cameras[index];
  28010. }
  28011. }
  28012. return null;
  28013. };
  28014. /**
  28015. * Gets a bone using its id
  28016. * @param id defines the bone's id
  28017. * @return the bone or null if not found
  28018. */
  28019. Scene.prototype.getBoneByID = function (id) {
  28020. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28021. var skeleton = this.skeletons[skeletonIndex];
  28022. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28023. if (skeleton.bones[boneIndex].id === id) {
  28024. return skeleton.bones[boneIndex];
  28025. }
  28026. }
  28027. }
  28028. return null;
  28029. };
  28030. /**
  28031. * Gets a bone using its id
  28032. * @param name defines the bone's name
  28033. * @return the bone or null if not found
  28034. */
  28035. Scene.prototype.getBoneByName = function (name) {
  28036. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28037. var skeleton = this.skeletons[skeletonIndex];
  28038. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28039. if (skeleton.bones[boneIndex].name === name) {
  28040. return skeleton.bones[boneIndex];
  28041. }
  28042. }
  28043. }
  28044. return null;
  28045. };
  28046. /**
  28047. * Gets a light node using its name
  28048. * @param name defines the the light's name
  28049. * @return the light or null if none found.
  28050. */
  28051. Scene.prototype.getLightByName = function (name) {
  28052. for (var index = 0; index < this.lights.length; index++) {
  28053. if (this.lights[index].name === name) {
  28054. return this.lights[index];
  28055. }
  28056. }
  28057. return null;
  28058. };
  28059. /**
  28060. * Gets a light node using its id
  28061. * @param id defines the light's id
  28062. * @return the light or null if none found.
  28063. */
  28064. Scene.prototype.getLightByID = function (id) {
  28065. for (var index = 0; index < this.lights.length; index++) {
  28066. if (this.lights[index].id === id) {
  28067. return this.lights[index];
  28068. }
  28069. }
  28070. return null;
  28071. };
  28072. /**
  28073. * Gets a light node using its scene-generated unique ID
  28074. * @param uniqueId defines the light's unique id
  28075. * @return the light or null if none found.
  28076. */
  28077. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28078. for (var index = 0; index < this.lights.length; index++) {
  28079. if (this.lights[index].uniqueId === uniqueId) {
  28080. return this.lights[index];
  28081. }
  28082. }
  28083. return null;
  28084. };
  28085. /**
  28086. * Gets a particle system by id
  28087. * @param id defines the particle system id
  28088. * @return the corresponding system or null if none found
  28089. */
  28090. Scene.prototype.getParticleSystemByID = function (id) {
  28091. for (var index = 0; index < this.particleSystems.length; index++) {
  28092. if (this.particleSystems[index].id === id) {
  28093. return this.particleSystems[index];
  28094. }
  28095. }
  28096. return null;
  28097. };
  28098. /**
  28099. * Gets a geometry using its ID
  28100. * @param id defines the geometry's id
  28101. * @return the geometry or null if none found.
  28102. */
  28103. Scene.prototype.getGeometryByID = function (id) {
  28104. for (var index = 0; index < this.geometries.length; index++) {
  28105. if (this.geometries[index].id === id) {
  28106. return this.geometries[index];
  28107. }
  28108. }
  28109. return null;
  28110. };
  28111. /**
  28112. * Add a new geometry to this scene
  28113. * @param geometry defines the geometry to be added to the scene.
  28114. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28115. * @return a boolean defining if the geometry was added or not
  28116. */
  28117. Scene.prototype.pushGeometry = function (geometry, force) {
  28118. if (!force && this.getGeometryByID(geometry.id)) {
  28119. return false;
  28120. }
  28121. this.geometries.push(geometry);
  28122. //notify the collision coordinator
  28123. if (this.collisionCoordinator) {
  28124. this.collisionCoordinator.onGeometryAdded(geometry);
  28125. }
  28126. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28127. return true;
  28128. };
  28129. /**
  28130. * Removes an existing geometry
  28131. * @param geometry defines the geometry to be removed from the scene
  28132. * @return a boolean defining if the geometry was removed or not
  28133. */
  28134. Scene.prototype.removeGeometry = function (geometry) {
  28135. var index = this.geometries.indexOf(geometry);
  28136. if (index > -1) {
  28137. this.geometries.splice(index, 1);
  28138. //notify the collision coordinator
  28139. if (this.collisionCoordinator) {
  28140. this.collisionCoordinator.onGeometryDeleted(geometry);
  28141. }
  28142. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28143. return true;
  28144. }
  28145. return false;
  28146. };
  28147. /**
  28148. * Gets the list of geometries attached to the scene
  28149. * @returns an array of Geometry
  28150. */
  28151. Scene.prototype.getGeometries = function () {
  28152. return this.geometries;
  28153. };
  28154. /**
  28155. * Gets the first added mesh found of a given ID
  28156. * @param id defines the id to search for
  28157. * @return the mesh found or null if not found at all
  28158. */
  28159. Scene.prototype.getMeshByID = function (id) {
  28160. for (var index = 0; index < this.meshes.length; index++) {
  28161. if (this.meshes[index].id === id) {
  28162. return this.meshes[index];
  28163. }
  28164. }
  28165. return null;
  28166. };
  28167. /**
  28168. * Gets a list of meshes using their id
  28169. * @param id defines the id to search for
  28170. * @returns a list of meshes
  28171. */
  28172. Scene.prototype.getMeshesByID = function (id) {
  28173. return this.meshes.filter(function (m) {
  28174. return m.id === id;
  28175. });
  28176. };
  28177. /**
  28178. * Gets the first added transform node found of a given ID
  28179. * @param id defines the id to search for
  28180. * @return the found transform node or null if not found at all.
  28181. */
  28182. Scene.prototype.getTransformNodeByID = function (id) {
  28183. for (var index = 0; index < this.transformNodes.length; index++) {
  28184. if (this.transformNodes[index].id === id) {
  28185. return this.transformNodes[index];
  28186. }
  28187. }
  28188. return null;
  28189. };
  28190. /**
  28191. * Gets a list of transform nodes using their id
  28192. * @param id defines the id to search for
  28193. * @returns a list of transform nodes
  28194. */
  28195. Scene.prototype.getTransformNodesByID = function (id) {
  28196. return this.transformNodes.filter(function (m) {
  28197. return m.id === id;
  28198. });
  28199. };
  28200. /**
  28201. * Gets a mesh with its auto-generated unique id
  28202. * @param uniqueId defines the unique id to search for
  28203. * @return the found mesh or null if not found at all.
  28204. */
  28205. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28206. for (var index = 0; index < this.meshes.length; index++) {
  28207. if (this.meshes[index].uniqueId === uniqueId) {
  28208. return this.meshes[index];
  28209. }
  28210. }
  28211. return null;
  28212. };
  28213. /**
  28214. * Gets a the last added mesh using a given id
  28215. * @param id defines the id to search for
  28216. * @return the found mesh or null if not found at all.
  28217. */
  28218. Scene.prototype.getLastMeshByID = function (id) {
  28219. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28220. if (this.meshes[index].id === id) {
  28221. return this.meshes[index];
  28222. }
  28223. }
  28224. return null;
  28225. };
  28226. /**
  28227. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28228. * @param id defines the id to search for
  28229. * @return the found node or null if not found at all
  28230. */
  28231. Scene.prototype.getLastEntryByID = function (id) {
  28232. var index;
  28233. for (index = this.meshes.length - 1; index >= 0; index--) {
  28234. if (this.meshes[index].id === id) {
  28235. return this.meshes[index];
  28236. }
  28237. }
  28238. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28239. if (this.transformNodes[index].id === id) {
  28240. return this.transformNodes[index];
  28241. }
  28242. }
  28243. for (index = this.cameras.length - 1; index >= 0; index--) {
  28244. if (this.cameras[index].id === id) {
  28245. return this.cameras[index];
  28246. }
  28247. }
  28248. for (index = this.lights.length - 1; index >= 0; index--) {
  28249. if (this.lights[index].id === id) {
  28250. return this.lights[index];
  28251. }
  28252. }
  28253. return null;
  28254. };
  28255. /**
  28256. * Gets a node (Mesh, Camera, Light) using a given id
  28257. * @param id defines the id to search for
  28258. * @return the found node or null if not found at all
  28259. */
  28260. Scene.prototype.getNodeByID = function (id) {
  28261. var mesh = this.getMeshByID(id);
  28262. if (mesh) {
  28263. return mesh;
  28264. }
  28265. var light = this.getLightByID(id);
  28266. if (light) {
  28267. return light;
  28268. }
  28269. var camera = this.getCameraByID(id);
  28270. if (camera) {
  28271. return camera;
  28272. }
  28273. var bone = this.getBoneByID(id);
  28274. return bone;
  28275. };
  28276. /**
  28277. * Gets a node (Mesh, Camera, Light) using a given name
  28278. * @param name defines the name to search for
  28279. * @return the found node or null if not found at all.
  28280. */
  28281. Scene.prototype.getNodeByName = function (name) {
  28282. var mesh = this.getMeshByName(name);
  28283. if (mesh) {
  28284. return mesh;
  28285. }
  28286. var light = this.getLightByName(name);
  28287. if (light) {
  28288. return light;
  28289. }
  28290. var camera = this.getCameraByName(name);
  28291. if (camera) {
  28292. return camera;
  28293. }
  28294. var bone = this.getBoneByName(name);
  28295. return bone;
  28296. };
  28297. /**
  28298. * Gets a mesh using a given name
  28299. * @param name defines the name to search for
  28300. * @return the found mesh or null if not found at all.
  28301. */
  28302. Scene.prototype.getMeshByName = function (name) {
  28303. for (var index = 0; index < this.meshes.length; index++) {
  28304. if (this.meshes[index].name === name) {
  28305. return this.meshes[index];
  28306. }
  28307. }
  28308. return null;
  28309. };
  28310. /**
  28311. * Gets a transform node using a given name
  28312. * @param name defines the name to search for
  28313. * @return the found transform node or null if not found at all.
  28314. */
  28315. Scene.prototype.getTransformNodeByName = function (name) {
  28316. for (var index = 0; index < this.transformNodes.length; index++) {
  28317. if (this.transformNodes[index].name === name) {
  28318. return this.transformNodes[index];
  28319. }
  28320. }
  28321. return null;
  28322. };
  28323. /**
  28324. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28325. * @param id defines the id to search for
  28326. * @return the found skeleton or null if not found at all.
  28327. */
  28328. Scene.prototype.getLastSkeletonByID = function (id) {
  28329. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28330. if (this.skeletons[index].id === id) {
  28331. return this.skeletons[index];
  28332. }
  28333. }
  28334. return null;
  28335. };
  28336. /**
  28337. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28338. * @param id defines the id to search for
  28339. * @return the found skeleton or null if not found at all.
  28340. */
  28341. Scene.prototype.getSkeletonById = function (id) {
  28342. for (var index = 0; index < this.skeletons.length; index++) {
  28343. if (this.skeletons[index].id === id) {
  28344. return this.skeletons[index];
  28345. }
  28346. }
  28347. return null;
  28348. };
  28349. /**
  28350. * Gets a skeleton using a given name
  28351. * @param name defines the name to search for
  28352. * @return the found skeleton or null if not found at all.
  28353. */
  28354. Scene.prototype.getSkeletonByName = function (name) {
  28355. for (var index = 0; index < this.skeletons.length; index++) {
  28356. if (this.skeletons[index].name === name) {
  28357. return this.skeletons[index];
  28358. }
  28359. }
  28360. return null;
  28361. };
  28362. /**
  28363. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28364. * @param id defines the id to search for
  28365. * @return the found morph target manager or null if not found at all.
  28366. */
  28367. Scene.prototype.getMorphTargetManagerById = function (id) {
  28368. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28369. if (this.morphTargetManagers[index].uniqueId === id) {
  28370. return this.morphTargetManagers[index];
  28371. }
  28372. }
  28373. return null;
  28374. };
  28375. /**
  28376. * Gets a boolean indicating if the given mesh is active
  28377. * @param mesh defines the mesh to look for
  28378. * @returns true if the mesh is in the active list
  28379. */
  28380. Scene.prototype.isActiveMesh = function (mesh) {
  28381. return (this._activeMeshes.indexOf(mesh) !== -1);
  28382. };
  28383. Object.defineProperty(Scene.prototype, "uid", {
  28384. /**
  28385. * Return a unique id as a string which can serve as an identifier for the scene
  28386. */
  28387. get: function () {
  28388. if (!this._uid) {
  28389. this._uid = BABYLON.Tools.RandomId();
  28390. }
  28391. return this._uid;
  28392. },
  28393. enumerable: true,
  28394. configurable: true
  28395. });
  28396. /**
  28397. * Add an externaly attached data from its key.
  28398. * This method call will fail and return false, if such key already exists.
  28399. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28400. * @param key the unique key that identifies the data
  28401. * @param data the data object to associate to the key for this Engine instance
  28402. * @return true if no such key were already present and the data was added successfully, false otherwise
  28403. */
  28404. Scene.prototype.addExternalData = function (key, data) {
  28405. if (!this._externalData) {
  28406. this._externalData = new BABYLON.StringDictionary();
  28407. }
  28408. return this._externalData.add(key, data);
  28409. };
  28410. /**
  28411. * Get an externaly attached data from its key
  28412. * @param key the unique key that identifies the data
  28413. * @return the associated data, if present (can be null), or undefined if not present
  28414. */
  28415. Scene.prototype.getExternalData = function (key) {
  28416. if (!this._externalData) {
  28417. return null;
  28418. }
  28419. return this._externalData.get(key);
  28420. };
  28421. /**
  28422. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28423. * @param key the unique key that identifies the data
  28424. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28425. * @return the associated data, can be null if the factory returned null.
  28426. */
  28427. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28428. if (!this._externalData) {
  28429. this._externalData = new BABYLON.StringDictionary();
  28430. }
  28431. return this._externalData.getOrAddWithFactory(key, factory);
  28432. };
  28433. /**
  28434. * Remove an externaly attached data from the Engine instance
  28435. * @param key the unique key that identifies the data
  28436. * @return true if the data was successfully removed, false if it doesn't exist
  28437. */
  28438. Scene.prototype.removeExternalData = function (key) {
  28439. return this._externalData.remove(key);
  28440. };
  28441. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28442. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28443. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28444. var step = _a[_i];
  28445. step.action(mesh, subMesh);
  28446. }
  28447. var material = subMesh.getMaterial();
  28448. if (material !== null && material !== undefined) {
  28449. // Render targets
  28450. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28451. if (this._processedMaterials.indexOf(material) === -1) {
  28452. this._processedMaterials.push(material);
  28453. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28454. }
  28455. }
  28456. // Dispatch
  28457. this._activeIndices.addCount(subMesh.indexCount, false);
  28458. this._renderingManager.dispatch(subMesh, mesh, material);
  28459. }
  28460. }
  28461. };
  28462. /**
  28463. * Clear the processed materials smart array preventing retention point in material dispose.
  28464. */
  28465. Scene.prototype.freeProcessedMaterials = function () {
  28466. this._processedMaterials.dispose();
  28467. };
  28468. /**
  28469. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28470. */
  28471. Scene.prototype.freeActiveMeshes = function () {
  28472. this._activeMeshes.dispose();
  28473. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28474. this.activeCamera._activeMeshes.dispose();
  28475. }
  28476. if (this.activeCameras) {
  28477. for (var i = 0; i < this.activeCameras.length; i++) {
  28478. var activeCamera = this.activeCameras[i];
  28479. if (activeCamera && activeCamera._activeMeshes) {
  28480. activeCamera._activeMeshes.dispose();
  28481. }
  28482. }
  28483. }
  28484. };
  28485. /**
  28486. * Clear the info related to rendering groups preventing retention points during dispose.
  28487. */
  28488. Scene.prototype.freeRenderingGroups = function () {
  28489. if (this._renderingManager) {
  28490. this._renderingManager.freeRenderingGroups();
  28491. }
  28492. if (this.textures) {
  28493. for (var i = 0; i < this.textures.length; i++) {
  28494. var texture = this.textures[i];
  28495. if (texture && texture.renderList) {
  28496. texture.freeRenderingGroups();
  28497. }
  28498. }
  28499. }
  28500. };
  28501. /** @hidden */
  28502. Scene.prototype._isInIntermediateRendering = function () {
  28503. return this._intermediateRendering;
  28504. };
  28505. /**
  28506. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28507. * @returns the current scene
  28508. */
  28509. Scene.prototype.freezeActiveMeshes = function () {
  28510. if (!this.activeCamera) {
  28511. return this;
  28512. }
  28513. if (!this._frustumPlanes) {
  28514. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28515. }
  28516. this._evaluateActiveMeshes();
  28517. this._activeMeshesFrozen = true;
  28518. return this;
  28519. };
  28520. /**
  28521. * Use this function to restart evaluating active meshes on every frame
  28522. * @returns the current scene
  28523. */
  28524. Scene.prototype.unfreezeActiveMeshes = function () {
  28525. this._activeMeshesFrozen = false;
  28526. return this;
  28527. };
  28528. Scene.prototype._evaluateActiveMeshes = function () {
  28529. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28530. return;
  28531. }
  28532. if (!this.activeCamera) {
  28533. return;
  28534. }
  28535. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28536. this.activeCamera._activeMeshes.reset();
  28537. this._activeMeshes.reset();
  28538. this._renderingManager.reset();
  28539. this._processedMaterials.reset();
  28540. this._activeParticleSystems.reset();
  28541. this._activeSkeletons.reset();
  28542. this._softwareSkinnedMeshes.reset();
  28543. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28544. var step = _a[_i];
  28545. step.action();
  28546. }
  28547. // Determine mesh candidates
  28548. var meshes = this.getActiveMeshCandidates();
  28549. // Check each mesh
  28550. var len = meshes.length;
  28551. for (var i = 0; i < len; i++) {
  28552. var mesh = meshes.data[i];
  28553. if (mesh.isBlocked) {
  28554. continue;
  28555. }
  28556. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28557. if (!mesh.isReady() || !mesh.isEnabled()) {
  28558. continue;
  28559. }
  28560. mesh.computeWorldMatrix();
  28561. // Intersections
  28562. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28563. this._meshesForIntersections.pushNoDuplicate(mesh);
  28564. }
  28565. // Switch to current LOD
  28566. var meshLOD = mesh.getLOD(this.activeCamera);
  28567. if (meshLOD === undefined || meshLOD === null) {
  28568. continue;
  28569. }
  28570. mesh._preActivate();
  28571. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28572. this._activeMeshes.push(mesh);
  28573. this.activeCamera._activeMeshes.push(mesh);
  28574. mesh._activate(this._renderId);
  28575. if (meshLOD !== mesh) {
  28576. meshLOD._activate(this._renderId);
  28577. }
  28578. this._activeMesh(mesh, meshLOD);
  28579. }
  28580. }
  28581. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28582. // Particle systems
  28583. if (this.particlesEnabled) {
  28584. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28585. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28586. var particleSystem = this.particleSystems[particleIndex];
  28587. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28588. continue;
  28589. }
  28590. var emitter = particleSystem.emitter;
  28591. if (!emitter.position || emitter.isEnabled()) {
  28592. this._activeParticleSystems.push(particleSystem);
  28593. particleSystem.animate();
  28594. this._renderingManager.dispatchParticles(particleSystem);
  28595. }
  28596. }
  28597. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28598. }
  28599. };
  28600. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28601. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28602. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28603. mesh.skeleton.prepare();
  28604. }
  28605. if (!mesh.computeBonesUsingShaders) {
  28606. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28607. }
  28608. }
  28609. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28610. var step = _a[_i];
  28611. step.action(sourceMesh, mesh);
  28612. }
  28613. if (mesh !== undefined && mesh !== null
  28614. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28615. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28616. var len = subMeshes.length;
  28617. for (var i = 0; i < len; i++) {
  28618. var subMesh = subMeshes.data[i];
  28619. this._evaluateSubMesh(subMesh, mesh);
  28620. }
  28621. }
  28622. };
  28623. /**
  28624. * Update the transform matrix to update from the current active camera
  28625. * @param force defines a boolean used to force the update even if cache is up to date
  28626. */
  28627. Scene.prototype.updateTransformMatrix = function (force) {
  28628. if (!this.activeCamera) {
  28629. return;
  28630. }
  28631. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28632. };
  28633. /**
  28634. * 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)
  28635. * @param alternateCamera defines the camera to use
  28636. */
  28637. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28638. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28639. };
  28640. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28641. if (camera && camera._skipRendering) {
  28642. return;
  28643. }
  28644. var engine = this._engine;
  28645. this.activeCamera = camera;
  28646. if (!this.activeCamera)
  28647. throw new Error("Active camera not set");
  28648. // Viewport
  28649. engine.setViewport(this.activeCamera.viewport);
  28650. // Camera
  28651. this.resetCachedMaterial();
  28652. this._renderId++;
  28653. this.updateTransformMatrix();
  28654. if (camera._alternateCamera) {
  28655. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28656. this._alternateRendering = true;
  28657. }
  28658. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28659. // Meshes
  28660. this._evaluateActiveMeshes();
  28661. // Software skinning
  28662. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28663. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28664. mesh.applySkeleton(mesh.skeleton);
  28665. }
  28666. // Render targets
  28667. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28668. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28669. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28670. }
  28671. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28672. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28673. }
  28674. // Collects render targets from external components.
  28675. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28676. var step = _a[_i];
  28677. step.action(this._renderTargets);
  28678. }
  28679. if (this.renderTargetsEnabled) {
  28680. this._intermediateRendering = true;
  28681. if (this._renderTargets.length > 0) {
  28682. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28683. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28684. var renderTarget = this._renderTargets.data[renderIndex];
  28685. if (renderTarget._shouldRender()) {
  28686. this._renderId++;
  28687. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28688. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28689. }
  28690. }
  28691. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28692. this._renderId++;
  28693. }
  28694. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28695. var step = _c[_b];
  28696. step.action(this.activeCamera);
  28697. }
  28698. this._intermediateRendering = false;
  28699. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28700. }
  28701. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28702. // Prepare Frame
  28703. if (this.postProcessManager) {
  28704. this.postProcessManager._prepareFrame();
  28705. }
  28706. // Before Camera Draw
  28707. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28708. var step = _e[_d];
  28709. step.action(this.activeCamera);
  28710. }
  28711. // Render
  28712. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28713. this._renderingManager.render(null, null, true, true);
  28714. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28715. // After Camera Draw
  28716. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28717. var step = _g[_f];
  28718. step.action(this.activeCamera);
  28719. }
  28720. // Finalize frame
  28721. if (this.postProcessManager) {
  28722. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28723. }
  28724. // Reset some special arrays
  28725. this._renderTargets.reset();
  28726. this._alternateRendering = false;
  28727. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28728. };
  28729. Scene.prototype._processSubCameras = function (camera) {
  28730. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28731. this._renderForCamera(camera);
  28732. return;
  28733. }
  28734. // rig cameras
  28735. for (var index = 0; index < camera._rigCameras.length; index++) {
  28736. this._renderForCamera(camera._rigCameras[index], camera);
  28737. }
  28738. this.activeCamera = camera;
  28739. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28740. };
  28741. Scene.prototype._checkIntersections = function () {
  28742. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28743. var sourceMesh = this._meshesForIntersections.data[index];
  28744. if (!sourceMesh.actionManager) {
  28745. continue;
  28746. }
  28747. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28748. var action = sourceMesh.actionManager.actions[actionIndex];
  28749. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28750. var parameters = action.getTriggerParameter();
  28751. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28752. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28753. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28754. if (areIntersecting && currentIntersectionInProgress === -1) {
  28755. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28756. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28757. sourceMesh._intersectionsInProgress.push(otherMesh);
  28758. }
  28759. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28760. sourceMesh._intersectionsInProgress.push(otherMesh);
  28761. }
  28762. }
  28763. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28764. //They intersected, and now they don't.
  28765. //is this trigger an exit trigger? execute an event.
  28766. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28767. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28768. }
  28769. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28770. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28771. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28772. return otherMesh === parameterMesh;
  28773. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28774. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28775. }
  28776. }
  28777. }
  28778. }
  28779. }
  28780. };
  28781. /** @hidden */
  28782. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28783. // Do nothing. Code will be replaced if physics engine component is referenced
  28784. };
  28785. /**
  28786. * Render the scene
  28787. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28788. */
  28789. Scene.prototype.render = function (updateCameras) {
  28790. if (updateCameras === void 0) { updateCameras = true; }
  28791. if (this.isDisposed) {
  28792. return;
  28793. }
  28794. this._frameId++;
  28795. // Register components that have been associated lately to the scene.
  28796. this._registerTransientComponents();
  28797. this._activeParticles.fetchNewFrame();
  28798. this._totalVertices.fetchNewFrame();
  28799. this._activeIndices.fetchNewFrame();
  28800. this._activeBones.fetchNewFrame();
  28801. this._meshesForIntersections.reset();
  28802. this.resetCachedMaterial();
  28803. this.onBeforeAnimationsObservable.notifyObservers(this);
  28804. // Actions
  28805. if (this.actionManager) {
  28806. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28807. }
  28808. if (this._engine.isDeterministicLockStep()) {
  28809. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28810. var defaultFPS = (60.0 / 1000.0);
  28811. var defaultFrameTime = this.getDeterministicFrameTime();
  28812. var stepsTaken = 0;
  28813. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28814. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28815. internalSteps = Math.min(internalSteps, maxSubSteps);
  28816. do {
  28817. this.onBeforeStepObservable.notifyObservers(this);
  28818. // Animations
  28819. this._animationRatio = defaultFrameTime * defaultFPS;
  28820. this._animate();
  28821. this.onAfterAnimationsObservable.notifyObservers(this);
  28822. // Physics
  28823. this._advancePhysicsEngineStep(defaultFrameTime);
  28824. this.onAfterStepObservable.notifyObservers(this);
  28825. this._currentStepId++;
  28826. stepsTaken++;
  28827. deltaTime -= defaultFrameTime;
  28828. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28829. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28830. }
  28831. else {
  28832. // Animations
  28833. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28834. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28835. this._animate();
  28836. this.onAfterAnimationsObservable.notifyObservers(this);
  28837. // Physics
  28838. this._advancePhysicsEngineStep(deltaTime);
  28839. }
  28840. // Before camera update steps
  28841. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28842. var step = _a[_i];
  28843. step.action();
  28844. }
  28845. // Update Cameras
  28846. if (updateCameras) {
  28847. if (this.activeCameras.length > 0) {
  28848. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28849. var camera = this.activeCameras[cameraIndex];
  28850. camera.update();
  28851. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28852. // rig cameras
  28853. for (var index = 0; index < camera._rigCameras.length; index++) {
  28854. camera._rigCameras[index].update();
  28855. }
  28856. }
  28857. }
  28858. }
  28859. else if (this.activeCamera) {
  28860. this.activeCamera.update();
  28861. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28862. // rig cameras
  28863. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28864. this.activeCamera._rigCameras[index].update();
  28865. }
  28866. }
  28867. }
  28868. }
  28869. // Before render
  28870. this.onBeforeRenderObservable.notifyObservers(this);
  28871. // Customs render targets
  28872. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28873. var engine = this.getEngine();
  28874. var currentActiveCamera = this.activeCamera;
  28875. if (this.renderTargetsEnabled) {
  28876. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28877. this._intermediateRendering = true;
  28878. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28879. var renderTarget = this.customRenderTargets[customIndex];
  28880. if (renderTarget._shouldRender()) {
  28881. this._renderId++;
  28882. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28883. if (!this.activeCamera)
  28884. throw new Error("Active camera not set");
  28885. // Viewport
  28886. engine.setViewport(this.activeCamera.viewport);
  28887. // Camera
  28888. this.updateTransformMatrix();
  28889. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28890. }
  28891. }
  28892. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28893. this._intermediateRendering = false;
  28894. this._renderId++;
  28895. }
  28896. // Restore back buffer
  28897. if (this.customRenderTargets.length > 0) {
  28898. engine.restoreDefaultFramebuffer();
  28899. }
  28900. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28901. this.activeCamera = currentActiveCamera;
  28902. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28903. var step = _c[_b];
  28904. step.action();
  28905. }
  28906. // Clear
  28907. if (this.autoClearDepthAndStencil || this.autoClear) {
  28908. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28909. }
  28910. // Collects render targets from external components.
  28911. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28912. var step = _e[_d];
  28913. step.action(this._renderTargets);
  28914. }
  28915. // Multi-cameras?
  28916. if (this.activeCameras.length > 0) {
  28917. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28918. if (cameraIndex > 0) {
  28919. this._engine.clear(null, false, true, true);
  28920. }
  28921. this._processSubCameras(this.activeCameras[cameraIndex]);
  28922. }
  28923. }
  28924. else {
  28925. if (!this.activeCamera) {
  28926. throw new Error("No camera defined");
  28927. }
  28928. this._processSubCameras(this.activeCamera);
  28929. }
  28930. // Intersection checks
  28931. this._checkIntersections();
  28932. // Executes the after render stage actions.
  28933. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28934. var step = _g[_f];
  28935. step.action();
  28936. }
  28937. // After render
  28938. if (this.afterRender) {
  28939. this.afterRender();
  28940. }
  28941. this.onAfterRenderObservable.notifyObservers(this);
  28942. // Cleaning
  28943. if (this._toBeDisposed.length) {
  28944. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28945. var data = this._toBeDisposed[index];
  28946. if (data) {
  28947. data.dispose();
  28948. }
  28949. }
  28950. this._toBeDisposed = [];
  28951. }
  28952. if (this.dumpNextRenderTargets) {
  28953. this.dumpNextRenderTargets = false;
  28954. }
  28955. this._activeBones.addCount(0, true);
  28956. this._activeIndices.addCount(0, true);
  28957. this._activeParticles.addCount(0, true);
  28958. };
  28959. /**
  28960. * Freeze all materials
  28961. * A frozen material will not be updatable but should be faster to render
  28962. */
  28963. Scene.prototype.freezeMaterials = function () {
  28964. for (var i = 0; i < this.materials.length; i++) {
  28965. this.materials[i].freeze();
  28966. }
  28967. };
  28968. /**
  28969. * Unfreeze all materials
  28970. * A frozen material will not be updatable but should be faster to render
  28971. */
  28972. Scene.prototype.unfreezeMaterials = function () {
  28973. for (var i = 0; i < this.materials.length; i++) {
  28974. this.materials[i].unfreeze();
  28975. }
  28976. };
  28977. /**
  28978. * Releases all held ressources
  28979. */
  28980. Scene.prototype.dispose = function () {
  28981. this.beforeRender = null;
  28982. this.afterRender = null;
  28983. this.skeletons = [];
  28984. this.morphTargetManagers = [];
  28985. this._transientComponents = [];
  28986. this._isReadyForMeshStage.clear();
  28987. this._beforeEvaluateActiveMeshStage.clear();
  28988. this._evaluateSubMeshStage.clear();
  28989. this._activeMeshStage.clear();
  28990. this._cameraDrawRenderTargetStage.clear();
  28991. this._beforeCameraDrawStage.clear();
  28992. this._beforeRenderingGroupDrawStage.clear();
  28993. this._beforeRenderingMeshStage.clear();
  28994. this._afterRenderingMeshStage.clear();
  28995. this._afterRenderingGroupDrawStage.clear();
  28996. this._afterCameraDrawStage.clear();
  28997. this._afterRenderStage.clear();
  28998. this._beforeCameraUpdateStage.clear();
  28999. this._beforeClearStage.clear();
  29000. this._gatherRenderTargetsStage.clear();
  29001. this._gatherActiveCameraRenderTargetsStage.clear();
  29002. this._pointerMoveStage.clear();
  29003. this._pointerDownStage.clear();
  29004. this._pointerUpStage.clear();
  29005. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29006. var component = _a[_i];
  29007. component.dispose();
  29008. }
  29009. this.importedMeshesFiles = new Array();
  29010. this.stopAllAnimations();
  29011. this.resetCachedMaterial();
  29012. // Smart arrays
  29013. if (this.activeCamera) {
  29014. this.activeCamera._activeMeshes.dispose();
  29015. this.activeCamera = null;
  29016. }
  29017. this._activeMeshes.dispose();
  29018. this._renderingManager.dispose();
  29019. this._processedMaterials.dispose();
  29020. this._activeParticleSystems.dispose();
  29021. this._activeSkeletons.dispose();
  29022. this._softwareSkinnedMeshes.dispose();
  29023. this._renderTargets.dispose();
  29024. this._registeredForLateAnimationBindings.dispose();
  29025. this._meshesForIntersections.dispose();
  29026. this._toBeDisposed = [];
  29027. // Abort active requests
  29028. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29029. var request = _c[_b];
  29030. request.abort();
  29031. }
  29032. // Events
  29033. this.onDisposeObservable.notifyObservers(this);
  29034. this.onDisposeObservable.clear();
  29035. this.onBeforeRenderObservable.clear();
  29036. this.onAfterRenderObservable.clear();
  29037. this.onBeforeRenderTargetsRenderObservable.clear();
  29038. this.onAfterRenderTargetsRenderObservable.clear();
  29039. this.onAfterStepObservable.clear();
  29040. this.onBeforeStepObservable.clear();
  29041. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29042. this.onAfterActiveMeshesEvaluationObservable.clear();
  29043. this.onBeforeParticlesRenderingObservable.clear();
  29044. this.onAfterParticlesRenderingObservable.clear();
  29045. this.onBeforeDrawPhaseObservable.clear();
  29046. this.onAfterDrawPhaseObservable.clear();
  29047. this.onBeforeAnimationsObservable.clear();
  29048. this.onAfterAnimationsObservable.clear();
  29049. this.onDataLoadedObservable.clear();
  29050. this.onBeforeRenderingGroupObservable.clear();
  29051. this.onAfterRenderingGroupObservable.clear();
  29052. this.onMeshImportedObservable.clear();
  29053. this.onBeforeCameraRenderObservable.clear();
  29054. this.onAfterCameraRenderObservable.clear();
  29055. this.onReadyObservable.clear();
  29056. this.onNewCameraAddedObservable.clear();
  29057. this.onCameraRemovedObservable.clear();
  29058. this.onNewLightAddedObservable.clear();
  29059. this.onLightRemovedObservable.clear();
  29060. this.onNewGeometryAddedObservable.clear();
  29061. this.onGeometryRemovedObservable.clear();
  29062. this.onNewTransformNodeAddedObservable.clear();
  29063. this.onTransformNodeRemovedObservable.clear();
  29064. this.onNewMeshAddedObservable.clear();
  29065. this.onMeshRemovedObservable.clear();
  29066. this.onNewMaterialAddedObservable.clear();
  29067. this.onMaterialRemovedObservable.clear();
  29068. this.onNewTextureAddedObservable.clear();
  29069. this.onTextureRemovedObservable.clear();
  29070. this.onPrePointerObservable.clear();
  29071. this.onPointerObservable.clear();
  29072. this.onPreKeyboardObservable.clear();
  29073. this.onKeyboardObservable.clear();
  29074. this.detachControl();
  29075. // Detach cameras
  29076. var canvas = this._engine.getRenderingCanvas();
  29077. if (canvas) {
  29078. var index;
  29079. for (index = 0; index < this.cameras.length; index++) {
  29080. this.cameras[index].detachControl(canvas);
  29081. }
  29082. }
  29083. // Release animation groups
  29084. while (this.animationGroups.length) {
  29085. this.animationGroups[0].dispose();
  29086. }
  29087. // Release lights
  29088. while (this.lights.length) {
  29089. this.lights[0].dispose();
  29090. }
  29091. // Release meshes
  29092. while (this.meshes.length) {
  29093. this.meshes[0].dispose(true);
  29094. }
  29095. while (this.transformNodes.length) {
  29096. this.removeTransformNode(this.transformNodes[0]);
  29097. }
  29098. // Release cameras
  29099. while (this.cameras.length) {
  29100. this.cameras[0].dispose();
  29101. }
  29102. // Release materials
  29103. if (this.defaultMaterial) {
  29104. this.defaultMaterial.dispose();
  29105. }
  29106. while (this.multiMaterials.length) {
  29107. this.multiMaterials[0].dispose();
  29108. }
  29109. while (this.materials.length) {
  29110. this.materials[0].dispose();
  29111. }
  29112. // Release particles
  29113. while (this.particleSystems.length) {
  29114. this.particleSystems[0].dispose();
  29115. }
  29116. // Release postProcesses
  29117. while (this.postProcesses.length) {
  29118. this.postProcesses[0].dispose();
  29119. }
  29120. // Release textures
  29121. while (this.textures.length) {
  29122. this.textures[0].dispose();
  29123. }
  29124. // Release UBO
  29125. this._sceneUbo.dispose();
  29126. if (this._alternateSceneUbo) {
  29127. this._alternateSceneUbo.dispose();
  29128. }
  29129. // Post-processes
  29130. this.postProcessManager.dispose();
  29131. // Remove from engine
  29132. index = this._engine.scenes.indexOf(this);
  29133. if (index > -1) {
  29134. this._engine.scenes.splice(index, 1);
  29135. }
  29136. this._engine.wipeCaches(true);
  29137. this._isDisposed = true;
  29138. };
  29139. Object.defineProperty(Scene.prototype, "isDisposed", {
  29140. /**
  29141. * Gets if the scene is already disposed
  29142. */
  29143. get: function () {
  29144. return this._isDisposed;
  29145. },
  29146. enumerable: true,
  29147. configurable: true
  29148. });
  29149. /**
  29150. * Call this function to reduce memory footprint of the scene.
  29151. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29152. */
  29153. Scene.prototype.clearCachedVertexData = function () {
  29154. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29155. var mesh = this.meshes[meshIndex];
  29156. var geometry = mesh.geometry;
  29157. if (geometry) {
  29158. geometry._indices = [];
  29159. for (var vbName in geometry._vertexBuffers) {
  29160. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29161. continue;
  29162. }
  29163. geometry._vertexBuffers[vbName]._buffer._data = null;
  29164. }
  29165. }
  29166. }
  29167. };
  29168. /**
  29169. * This function will remove the local cached buffer data from texture.
  29170. * It will save memory but will prevent the texture from being rebuilt
  29171. */
  29172. Scene.prototype.cleanCachedTextureBuffer = function () {
  29173. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29174. var baseTexture = _a[_i];
  29175. var buffer = baseTexture._buffer;
  29176. if (buffer) {
  29177. baseTexture._buffer = null;
  29178. }
  29179. }
  29180. };
  29181. /**
  29182. * Get the world extend vectors with an optional filter
  29183. *
  29184. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29185. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29186. */
  29187. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29188. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29189. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29190. filterPredicate = filterPredicate || (function () { return true; });
  29191. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29192. mesh.computeWorldMatrix(true);
  29193. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29194. return;
  29195. }
  29196. var boundingInfo = mesh.getBoundingInfo();
  29197. var minBox = boundingInfo.boundingBox.minimumWorld;
  29198. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29199. BABYLON.Tools.CheckExtends(minBox, min, max);
  29200. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29201. });
  29202. return {
  29203. min: min,
  29204. max: max
  29205. };
  29206. };
  29207. // Picking
  29208. /**
  29209. * Creates a ray that can be used to pick in the scene
  29210. * @param x defines the x coordinate of the origin (on-screen)
  29211. * @param y defines the y coordinate of the origin (on-screen)
  29212. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29213. * @param camera defines the camera to use for the picking
  29214. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29215. * @returns a Ray
  29216. */
  29217. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29218. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29219. var result = BABYLON.Ray.Zero();
  29220. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29221. return result;
  29222. };
  29223. /**
  29224. * Creates a ray that can be used to pick in the scene
  29225. * @param x defines the x coordinate of the origin (on-screen)
  29226. * @param y defines the y coordinate of the origin (on-screen)
  29227. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29228. * @param result defines the ray where to store the picking ray
  29229. * @param camera defines the camera to use for the picking
  29230. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29231. * @returns the current scene
  29232. */
  29233. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29234. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29235. var engine = this._engine;
  29236. if (!camera) {
  29237. if (!this.activeCamera)
  29238. throw new Error("Active camera not set");
  29239. camera = this.activeCamera;
  29240. }
  29241. var cameraViewport = camera.viewport;
  29242. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29243. // Moving coordinates to local viewport world
  29244. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29245. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29246. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29247. return this;
  29248. };
  29249. /**
  29250. * Creates a ray that can be used to pick in the scene
  29251. * @param x defines the x coordinate of the origin (on-screen)
  29252. * @param y defines the y coordinate of the origin (on-screen)
  29253. * @param camera defines the camera to use for the picking
  29254. * @returns a Ray
  29255. */
  29256. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29257. var result = BABYLON.Ray.Zero();
  29258. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29259. return result;
  29260. };
  29261. /**
  29262. * Creates a ray that can be used to pick in the scene
  29263. * @param x defines the x coordinate of the origin (on-screen)
  29264. * @param y defines the y coordinate of the origin (on-screen)
  29265. * @param result defines the ray where to store the picking ray
  29266. * @param camera defines the camera to use for the picking
  29267. * @returns the current scene
  29268. */
  29269. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29270. if (!BABYLON.PickingInfo) {
  29271. return this;
  29272. }
  29273. var engine = this._engine;
  29274. if (!camera) {
  29275. if (!this.activeCamera)
  29276. throw new Error("Active camera not set");
  29277. camera = this.activeCamera;
  29278. }
  29279. var cameraViewport = camera.viewport;
  29280. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29281. var identity = BABYLON.Matrix.Identity();
  29282. // Moving coordinates to local viewport world
  29283. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29284. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29285. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29286. return this;
  29287. };
  29288. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29289. if (!BABYLON.PickingInfo) {
  29290. return null;
  29291. }
  29292. var pickingInfo = null;
  29293. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29294. var mesh = this.meshes[meshIndex];
  29295. if (predicate) {
  29296. if (!predicate(mesh)) {
  29297. continue;
  29298. }
  29299. }
  29300. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29301. continue;
  29302. }
  29303. var world = mesh.getWorldMatrix();
  29304. var ray = rayFunction(world);
  29305. var result = mesh.intersects(ray, fastCheck);
  29306. if (!result || !result.hit)
  29307. continue;
  29308. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29309. continue;
  29310. pickingInfo = result;
  29311. if (fastCheck) {
  29312. break;
  29313. }
  29314. }
  29315. return pickingInfo || new BABYLON.PickingInfo();
  29316. };
  29317. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29318. if (!BABYLON.PickingInfo) {
  29319. return null;
  29320. }
  29321. var pickingInfos = new Array();
  29322. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29323. var mesh = this.meshes[meshIndex];
  29324. if (predicate) {
  29325. if (!predicate(mesh)) {
  29326. continue;
  29327. }
  29328. }
  29329. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29330. continue;
  29331. }
  29332. var world = mesh.getWorldMatrix();
  29333. var ray = rayFunction(world);
  29334. var result = mesh.intersects(ray, false);
  29335. if (!result || !result.hit)
  29336. continue;
  29337. pickingInfos.push(result);
  29338. }
  29339. return pickingInfos;
  29340. };
  29341. /** Launch a ray to try to pick a mesh in the scene
  29342. * @param x position on screen
  29343. * @param y position on screen
  29344. * @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
  29345. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29346. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29347. * @returns a PickingInfo
  29348. */
  29349. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29350. var _this = this;
  29351. if (!BABYLON.PickingInfo) {
  29352. return null;
  29353. }
  29354. var result = this._internalPick(function (world) {
  29355. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29356. return _this._tempPickingRay;
  29357. }, predicate, fastCheck);
  29358. if (result) {
  29359. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29360. }
  29361. return result;
  29362. };
  29363. /** Use the given ray to pick a mesh in the scene
  29364. * @param ray The ray to use to pick meshes
  29365. * @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
  29366. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29367. * @returns a PickingInfo
  29368. */
  29369. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29370. var _this = this;
  29371. var result = this._internalPick(function (world) {
  29372. if (!_this._pickWithRayInverseMatrix) {
  29373. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29374. }
  29375. world.invertToRef(_this._pickWithRayInverseMatrix);
  29376. if (!_this._cachedRayForTransform) {
  29377. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29378. }
  29379. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29380. return _this._cachedRayForTransform;
  29381. }, predicate, fastCheck);
  29382. if (result) {
  29383. result.ray = ray;
  29384. }
  29385. return result;
  29386. };
  29387. /**
  29388. * Launch a ray to try to pick a mesh in the scene
  29389. * @param x X position on screen
  29390. * @param y Y position on screen
  29391. * @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
  29392. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29393. * @returns an array of PickingInfo
  29394. */
  29395. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29396. var _this = this;
  29397. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29398. };
  29399. /**
  29400. * Launch a ray to try to pick a mesh in the scene
  29401. * @param ray Ray to use
  29402. * @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
  29403. * @returns an array of PickingInfo
  29404. */
  29405. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29406. var _this = this;
  29407. return this._internalMultiPick(function (world) {
  29408. if (!_this._pickWithRayInverseMatrix) {
  29409. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29410. }
  29411. world.invertToRef(_this._pickWithRayInverseMatrix);
  29412. if (!_this._cachedRayForTransform) {
  29413. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29414. }
  29415. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29416. return _this._cachedRayForTransform;
  29417. }, predicate);
  29418. };
  29419. /**
  29420. * Force the value of meshUnderPointer
  29421. * @param mesh defines the mesh to use
  29422. */
  29423. Scene.prototype.setPointerOverMesh = function (mesh) {
  29424. if (this._pointerOverMesh === mesh) {
  29425. return;
  29426. }
  29427. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29428. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29429. }
  29430. this._pointerOverMesh = mesh;
  29431. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29432. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29433. }
  29434. };
  29435. /**
  29436. * Gets the mesh under the pointer
  29437. * @returns a Mesh or null if no mesh is under the pointer
  29438. */
  29439. Scene.prototype.getPointerOverMesh = function () {
  29440. return this._pointerOverMesh;
  29441. };
  29442. // Misc.
  29443. /** @hidden */
  29444. Scene.prototype._rebuildGeometries = function () {
  29445. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29446. var geometry = _a[_i];
  29447. geometry._rebuild();
  29448. }
  29449. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29450. var mesh = _c[_b];
  29451. mesh._rebuild();
  29452. }
  29453. if (this.postProcessManager) {
  29454. this.postProcessManager._rebuild();
  29455. }
  29456. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29457. var component = _e[_d];
  29458. component.rebuild();
  29459. }
  29460. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29461. var system = _g[_f];
  29462. system.rebuild();
  29463. }
  29464. };
  29465. /** @hidden */
  29466. Scene.prototype._rebuildTextures = function () {
  29467. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29468. var texture = _a[_i];
  29469. texture._rebuild();
  29470. }
  29471. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29472. };
  29473. // Tags
  29474. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29475. if (tagsQuery === undefined) {
  29476. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29477. return list;
  29478. }
  29479. var listByTags = [];
  29480. forEach = forEach || (function (item) { return; });
  29481. for (var i in list) {
  29482. var item = list[i];
  29483. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29484. listByTags.push(item);
  29485. forEach(item);
  29486. }
  29487. }
  29488. return listByTags;
  29489. };
  29490. /**
  29491. * Get a list of meshes by tags
  29492. * @param tagsQuery defines the tags query to use
  29493. * @param forEach defines a predicate used to filter results
  29494. * @returns an array of Mesh
  29495. */
  29496. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29497. return this._getByTags(this.meshes, tagsQuery, forEach);
  29498. };
  29499. /**
  29500. * Get a list of cameras by tags
  29501. * @param tagsQuery defines the tags query to use
  29502. * @param forEach defines a predicate used to filter results
  29503. * @returns an array of Camera
  29504. */
  29505. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29506. return this._getByTags(this.cameras, tagsQuery, forEach);
  29507. };
  29508. /**
  29509. * Get a list of lights by tags
  29510. * @param tagsQuery defines the tags query to use
  29511. * @param forEach defines a predicate used to filter results
  29512. * @returns an array of Light
  29513. */
  29514. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29515. return this._getByTags(this.lights, tagsQuery, forEach);
  29516. };
  29517. /**
  29518. * Get a list of materials by tags
  29519. * @param tagsQuery defines the tags query to use
  29520. * @param forEach defines a predicate used to filter results
  29521. * @returns an array of Material
  29522. */
  29523. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29524. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29525. };
  29526. /**
  29527. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29528. * This allowed control for front to back rendering or reversly depending of the special needs.
  29529. *
  29530. * @param renderingGroupId The rendering group id corresponding to its index
  29531. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29532. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29533. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29534. */
  29535. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29536. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29537. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29538. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29539. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29540. };
  29541. /**
  29542. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29543. *
  29544. * @param renderingGroupId The rendering group id corresponding to its index
  29545. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29546. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29547. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29548. */
  29549. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29550. if (depth === void 0) { depth = true; }
  29551. if (stencil === void 0) { stencil = true; }
  29552. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29553. };
  29554. /**
  29555. * Gets the current auto clear configuration for one rendering group of the rendering
  29556. * manager.
  29557. * @param index the rendering group index to get the information for
  29558. * @returns The auto clear setup for the requested rendering group
  29559. */
  29560. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29561. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29562. };
  29563. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29564. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29565. get: function () {
  29566. return this._blockMaterialDirtyMechanism;
  29567. },
  29568. set: function (value) {
  29569. if (this._blockMaterialDirtyMechanism === value) {
  29570. return;
  29571. }
  29572. this._blockMaterialDirtyMechanism = value;
  29573. if (!value) { // Do a complete update
  29574. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29575. }
  29576. },
  29577. enumerable: true,
  29578. configurable: true
  29579. });
  29580. /**
  29581. * Will flag all materials as dirty to trigger new shader compilation
  29582. * @param flag defines the flag used to specify which material part must be marked as dirty
  29583. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29584. */
  29585. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29586. if (this._blockMaterialDirtyMechanism) {
  29587. return;
  29588. }
  29589. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29590. var material = _a[_i];
  29591. if (predicate && !predicate(material)) {
  29592. continue;
  29593. }
  29594. material.markAsDirty(flag);
  29595. }
  29596. };
  29597. /** @hidden */
  29598. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29599. var _this = this;
  29600. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29601. this._activeRequests.push(request);
  29602. request.onCompleteObservable.add(function (request) {
  29603. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29604. });
  29605. return request;
  29606. };
  29607. /** @hidden */
  29608. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29609. var _this = this;
  29610. return new Promise(function (resolve, reject) {
  29611. _this._loadFile(url, function (data) {
  29612. resolve(data);
  29613. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29614. reject(exception);
  29615. });
  29616. });
  29617. };
  29618. // Statics
  29619. Scene._uniqueIdCounter = 0;
  29620. /** The fog is deactivated */
  29621. Scene.FOGMODE_NONE = 0;
  29622. /** The fog density is following an exponential function */
  29623. Scene.FOGMODE_EXP = 1;
  29624. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29625. Scene.FOGMODE_EXP2 = 2;
  29626. /** The fog density is following a linear function. */
  29627. Scene.FOGMODE_LINEAR = 3;
  29628. /**
  29629. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29630. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29631. */
  29632. Scene.MinDeltaTime = 1.0;
  29633. /**
  29634. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29635. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29636. */
  29637. Scene.MaxDeltaTime = 1000.0;
  29638. /** The distance in pixel that you have to move to prevent some events */
  29639. Scene.DragMovementThreshold = 10; // in pixels
  29640. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29641. Scene.LongPressDelay = 500; // in milliseconds
  29642. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29643. Scene.DoubleClickDelay = 300; // in milliseconds
  29644. /** If you need to check double click without raising a single click at first click, enable this flag */
  29645. Scene.ExclusiveDoubleClickMode = false;
  29646. return Scene;
  29647. }(BABYLON.AbstractScene));
  29648. BABYLON.Scene = Scene;
  29649. })(BABYLON || (BABYLON = {}));
  29650. //# sourceMappingURL=babylon.scene.js.map
  29651. var BABYLON;
  29652. (function (BABYLON) {
  29653. /**
  29654. * Set of assets to keep when moving a scene into an asset container.
  29655. */
  29656. var KeepAssets = /** @class */ (function (_super) {
  29657. __extends(KeepAssets, _super);
  29658. function KeepAssets() {
  29659. return _super !== null && _super.apply(this, arguments) || this;
  29660. }
  29661. return KeepAssets;
  29662. }(BABYLON.AbstractScene));
  29663. BABYLON.KeepAssets = KeepAssets;
  29664. /**
  29665. * Container with a set of assets that can be added or removed from a scene.
  29666. */
  29667. var AssetContainer = /** @class */ (function (_super) {
  29668. __extends(AssetContainer, _super);
  29669. /**
  29670. * Instantiates an AssetContainer.
  29671. * @param scene The scene the AssetContainer belongs to.
  29672. */
  29673. function AssetContainer(scene) {
  29674. var _this = _super.call(this) || this;
  29675. _this.scene = scene;
  29676. return _this;
  29677. }
  29678. /**
  29679. * Adds all the assets from the container to the scene.
  29680. */
  29681. AssetContainer.prototype.addAllToScene = function () {
  29682. var _this = this;
  29683. this.cameras.forEach(function (o) {
  29684. _this.scene.addCamera(o);
  29685. });
  29686. this.lights.forEach(function (o) {
  29687. _this.scene.addLight(o);
  29688. });
  29689. this.meshes.forEach(function (o) {
  29690. _this.scene.addMesh(o);
  29691. });
  29692. this.skeletons.forEach(function (o) {
  29693. _this.scene.addSkeleton(o);
  29694. });
  29695. this.animations.forEach(function (o) {
  29696. _this.scene.addAnimation(o);
  29697. });
  29698. this.animationGroups.forEach(function (o) {
  29699. _this.scene.addAnimationGroup(o);
  29700. });
  29701. this.multiMaterials.forEach(function (o) {
  29702. _this.scene.addMultiMaterial(o);
  29703. });
  29704. this.materials.forEach(function (o) {
  29705. _this.scene.addMaterial(o);
  29706. });
  29707. this.morphTargetManagers.forEach(function (o) {
  29708. _this.scene.addMorphTargetManager(o);
  29709. });
  29710. this.geometries.forEach(function (o) {
  29711. _this.scene.addGeometry(o);
  29712. });
  29713. this.transformNodes.forEach(function (o) {
  29714. _this.scene.addTransformNode(o);
  29715. });
  29716. this.actionManagers.forEach(function (o) {
  29717. _this.scene.addActionManager(o);
  29718. });
  29719. this.textures.forEach(function (o) {
  29720. _this.scene.addTexture(o);
  29721. });
  29722. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29723. var component = _a[_i];
  29724. component.addFromContainer(this.scene);
  29725. }
  29726. };
  29727. /**
  29728. * Removes all the assets in the container from the scene
  29729. */
  29730. AssetContainer.prototype.removeAllFromScene = function () {
  29731. var _this = this;
  29732. this.cameras.forEach(function (o) {
  29733. _this.scene.removeCamera(o);
  29734. });
  29735. this.lights.forEach(function (o) {
  29736. _this.scene.removeLight(o);
  29737. });
  29738. this.meshes.forEach(function (o) {
  29739. _this.scene.removeMesh(o);
  29740. });
  29741. this.skeletons.forEach(function (o) {
  29742. _this.scene.removeSkeleton(o);
  29743. });
  29744. this.animations.forEach(function (o) {
  29745. _this.scene.removeAnimation(o);
  29746. });
  29747. this.animationGroups.forEach(function (o) {
  29748. _this.scene.removeAnimationGroup(o);
  29749. });
  29750. this.multiMaterials.forEach(function (o) {
  29751. _this.scene.removeMultiMaterial(o);
  29752. });
  29753. this.materials.forEach(function (o) {
  29754. _this.scene.removeMaterial(o);
  29755. });
  29756. this.morphTargetManagers.forEach(function (o) {
  29757. _this.scene.removeMorphTargetManager(o);
  29758. });
  29759. this.geometries.forEach(function (o) {
  29760. _this.scene.removeGeometry(o);
  29761. });
  29762. this.transformNodes.forEach(function (o) {
  29763. _this.scene.removeTransformNode(o);
  29764. });
  29765. this.actionManagers.forEach(function (o) {
  29766. _this.scene.removeActionManager(o);
  29767. });
  29768. this.textures.forEach(function (o) {
  29769. _this.scene.removeTexture(o);
  29770. });
  29771. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29772. var component = _a[_i];
  29773. component.removeFromContainer(this.scene);
  29774. }
  29775. };
  29776. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29777. if (!sourceAssets) {
  29778. return;
  29779. }
  29780. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29781. var asset = sourceAssets_1[_i];
  29782. var move = true;
  29783. if (keepAssets) {
  29784. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29785. var keepAsset = keepAssets_1[_a];
  29786. if (asset === keepAsset) {
  29787. move = false;
  29788. break;
  29789. }
  29790. }
  29791. }
  29792. if (move) {
  29793. targetAssets.push(asset);
  29794. }
  29795. }
  29796. };
  29797. /**
  29798. * Removes all the assets contained in the scene and adds them to the container.
  29799. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29800. */
  29801. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29802. if (keepAssets === undefined) {
  29803. keepAssets = new KeepAssets();
  29804. }
  29805. for (var key in this) {
  29806. if (this.hasOwnProperty(key)) {
  29807. this[key] = this[key] || [];
  29808. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29809. }
  29810. }
  29811. this.removeAllFromScene();
  29812. };
  29813. /**
  29814. * 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.
  29815. * @returns the root mesh
  29816. */
  29817. AssetContainer.prototype.createRootMesh = function () {
  29818. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29819. this.meshes.forEach(function (m) {
  29820. if (!m.parent) {
  29821. rootMesh.addChild(m);
  29822. }
  29823. });
  29824. this.meshes.unshift(rootMesh);
  29825. return rootMesh;
  29826. };
  29827. return AssetContainer;
  29828. }(BABYLON.AbstractScene));
  29829. BABYLON.AssetContainer = AssetContainer;
  29830. })(BABYLON || (BABYLON = {}));
  29831. //# sourceMappingURL=babylon.assetContainer.js.map
  29832. var BABYLON;
  29833. (function (BABYLON) {
  29834. /**
  29835. * Class used to store data that will be store in GPU memory
  29836. */
  29837. var Buffer = /** @class */ (function () {
  29838. /**
  29839. * Constructor
  29840. * @param engine the engine
  29841. * @param data the data to use for this buffer
  29842. * @param updatable whether the data is updatable
  29843. * @param stride the stride (optional)
  29844. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29845. * @param instanced whether the buffer is instanced (optional)
  29846. * @param useBytes set to true if the stride in in bytes (optional)
  29847. */
  29848. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29849. if (stride === void 0) { stride = 0; }
  29850. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29851. if (instanced === void 0) { instanced = false; }
  29852. if (useBytes === void 0) { useBytes = false; }
  29853. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29854. this._engine = engine.getScene().getEngine();
  29855. }
  29856. else {
  29857. this._engine = engine;
  29858. }
  29859. this._updatable = updatable;
  29860. this._instanced = instanced;
  29861. this._data = data;
  29862. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29863. if (!postponeInternalCreation) { // by default
  29864. this.create();
  29865. }
  29866. }
  29867. /**
  29868. * Create a new VertexBuffer based on the current buffer
  29869. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29870. * @param offset defines offset in the buffer (0 by default)
  29871. * @param size defines the size in floats of attributes (position is 3 for instance)
  29872. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29873. * @param instanced defines if the vertex buffer contains indexed data
  29874. * @param useBytes defines if the offset and stride are in bytes
  29875. * @returns the new vertex buffer
  29876. */
  29877. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29878. if (useBytes === void 0) { useBytes = false; }
  29879. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29880. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29881. // a lot of these parameters are ignored as they are overriden by the buffer
  29882. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29883. };
  29884. // Properties
  29885. /**
  29886. * Gets a boolean indicating if the Buffer is updatable?
  29887. * @returns true if the buffer is updatable
  29888. */
  29889. Buffer.prototype.isUpdatable = function () {
  29890. return this._updatable;
  29891. };
  29892. /**
  29893. * Gets current buffer's data
  29894. * @returns a DataArray or null
  29895. */
  29896. Buffer.prototype.getData = function () {
  29897. return this._data;
  29898. };
  29899. /**
  29900. * Gets underlying native buffer
  29901. * @returns underlying native buffer
  29902. */
  29903. Buffer.prototype.getBuffer = function () {
  29904. return this._buffer;
  29905. };
  29906. /**
  29907. * Gets the stride in float32 units (i.e. byte stride / 4).
  29908. * May not be an integer if the byte stride is not divisible by 4.
  29909. * DEPRECATED. Use byteStride instead.
  29910. * @returns the stride in float32 units
  29911. */
  29912. Buffer.prototype.getStrideSize = function () {
  29913. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29914. };
  29915. // Methods
  29916. /**
  29917. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29918. * @param data defines the data to store
  29919. */
  29920. Buffer.prototype.create = function (data) {
  29921. if (data === void 0) { data = null; }
  29922. if (!data && this._buffer) {
  29923. return; // nothing to do
  29924. }
  29925. data = data || this._data;
  29926. if (!data) {
  29927. return;
  29928. }
  29929. if (!this._buffer) { // create buffer
  29930. if (this._updatable) {
  29931. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29932. this._data = data;
  29933. }
  29934. else {
  29935. this._buffer = this._engine.createVertexBuffer(data);
  29936. }
  29937. }
  29938. else if (this._updatable) { // update buffer
  29939. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29940. this._data = data;
  29941. }
  29942. };
  29943. /** @hidden */
  29944. Buffer.prototype._rebuild = function () {
  29945. this._buffer = null;
  29946. this.create(this._data);
  29947. };
  29948. /**
  29949. * Update current buffer data
  29950. * @param data defines the data to store
  29951. */
  29952. Buffer.prototype.update = function (data) {
  29953. this.create(data);
  29954. };
  29955. /**
  29956. * Updates the data directly.
  29957. * @param data the new data
  29958. * @param offset the new offset
  29959. * @param vertexCount the vertex count (optional)
  29960. * @param useBytes set to true if the offset is in bytes
  29961. */
  29962. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29963. if (useBytes === void 0) { useBytes = false; }
  29964. if (!this._buffer) {
  29965. return;
  29966. }
  29967. if (this._updatable) { // update buffer
  29968. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29969. this._data = null;
  29970. }
  29971. };
  29972. /**
  29973. * Release all resources
  29974. */
  29975. Buffer.prototype.dispose = function () {
  29976. if (!this._buffer) {
  29977. return;
  29978. }
  29979. if (this._engine._releaseBuffer(this._buffer)) {
  29980. this._buffer = null;
  29981. }
  29982. };
  29983. return Buffer;
  29984. }());
  29985. BABYLON.Buffer = Buffer;
  29986. })(BABYLON || (BABYLON = {}));
  29987. //# sourceMappingURL=babylon.buffer.js.map
  29988. var BABYLON;
  29989. (function (BABYLON) {
  29990. /**
  29991. * Specialized buffer used to store vertex data
  29992. */
  29993. var VertexBuffer = /** @class */ (function () {
  29994. /**
  29995. * Constructor
  29996. * @param engine the engine
  29997. * @param data the data to use for this vertex buffer
  29998. * @param kind the vertex buffer kind
  29999. * @param updatable whether the data is updatable
  30000. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30001. * @param stride the stride (optional)
  30002. * @param instanced whether the buffer is instanced (optional)
  30003. * @param offset the offset of the data (optional)
  30004. * @param size the number of components (optional)
  30005. * @param type the type of the component (optional)
  30006. * @param normalized whether the data contains normalized data (optional)
  30007. * @param useBytes set to true if stride and offset are in bytes (optional)
  30008. */
  30009. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30010. if (normalized === void 0) { normalized = false; }
  30011. if (useBytes === void 0) { useBytes = false; }
  30012. if (data instanceof BABYLON.Buffer) {
  30013. this._buffer = data;
  30014. this._ownsBuffer = false;
  30015. }
  30016. else {
  30017. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30018. this._ownsBuffer = true;
  30019. }
  30020. this._kind = kind;
  30021. if (type == undefined) {
  30022. var data_1 = this.getData();
  30023. this.type = VertexBuffer.FLOAT;
  30024. if (data_1 instanceof Int8Array)
  30025. this.type = VertexBuffer.BYTE;
  30026. else if (data_1 instanceof Uint8Array)
  30027. this.type = VertexBuffer.UNSIGNED_BYTE;
  30028. else if (data_1 instanceof Int16Array)
  30029. this.type = VertexBuffer.SHORT;
  30030. else if (data_1 instanceof Uint16Array)
  30031. this.type = VertexBuffer.UNSIGNED_SHORT;
  30032. else if (data_1 instanceof Int32Array)
  30033. this.type = VertexBuffer.INT;
  30034. else if (data_1 instanceof Uint32Array)
  30035. this.type = VertexBuffer.UNSIGNED_INT;
  30036. }
  30037. else {
  30038. this.type = type;
  30039. }
  30040. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30041. if (useBytes) {
  30042. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30043. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30044. this.byteOffset = offset || 0;
  30045. }
  30046. else {
  30047. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30048. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30049. this.byteOffset = (offset || 0) * typeByteLength;
  30050. }
  30051. this.normalized = normalized;
  30052. this._instanced = instanced !== undefined ? instanced : false;
  30053. this._instanceDivisor = instanced ? 1 : 0;
  30054. }
  30055. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30056. /**
  30057. * Gets or sets the instance divisor when in instanced mode
  30058. */
  30059. get: function () {
  30060. return this._instanceDivisor;
  30061. },
  30062. set: function (value) {
  30063. this._instanceDivisor = value;
  30064. if (value == 0) {
  30065. this._instanced = false;
  30066. }
  30067. else {
  30068. this._instanced = true;
  30069. }
  30070. },
  30071. enumerable: true,
  30072. configurable: true
  30073. });
  30074. /** @hidden */
  30075. VertexBuffer.prototype._rebuild = function () {
  30076. if (!this._buffer) {
  30077. return;
  30078. }
  30079. this._buffer._rebuild();
  30080. };
  30081. /**
  30082. * Returns the kind of the VertexBuffer (string)
  30083. * @returns a string
  30084. */
  30085. VertexBuffer.prototype.getKind = function () {
  30086. return this._kind;
  30087. };
  30088. // Properties
  30089. /**
  30090. * Gets a boolean indicating if the VertexBuffer is updatable?
  30091. * @returns true if the buffer is updatable
  30092. */
  30093. VertexBuffer.prototype.isUpdatable = function () {
  30094. return this._buffer.isUpdatable();
  30095. };
  30096. /**
  30097. * Gets current buffer's data
  30098. * @returns a DataArray or null
  30099. */
  30100. VertexBuffer.prototype.getData = function () {
  30101. return this._buffer.getData();
  30102. };
  30103. /**
  30104. * Gets underlying native buffer
  30105. * @returns underlying native buffer
  30106. */
  30107. VertexBuffer.prototype.getBuffer = function () {
  30108. return this._buffer.getBuffer();
  30109. };
  30110. /**
  30111. * Gets the stride in float32 units (i.e. byte stride / 4).
  30112. * May not be an integer if the byte stride is not divisible by 4.
  30113. * DEPRECATED. Use byteStride instead.
  30114. * @returns the stride in float32 units
  30115. */
  30116. VertexBuffer.prototype.getStrideSize = function () {
  30117. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30118. };
  30119. /**
  30120. * Returns the offset as a multiple of the type byte length.
  30121. * DEPRECATED. Use byteOffset instead.
  30122. * @returns the offset in bytes
  30123. */
  30124. VertexBuffer.prototype.getOffset = function () {
  30125. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30126. };
  30127. /**
  30128. * Returns the number of components per vertex attribute (integer)
  30129. * @returns the size in float
  30130. */
  30131. VertexBuffer.prototype.getSize = function () {
  30132. return this._size;
  30133. };
  30134. /**
  30135. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30136. * @returns true if this buffer is instanced
  30137. */
  30138. VertexBuffer.prototype.getIsInstanced = function () {
  30139. return this._instanced;
  30140. };
  30141. /**
  30142. * Returns the instancing divisor, zero for non-instanced (integer).
  30143. * @returns a number
  30144. */
  30145. VertexBuffer.prototype.getInstanceDivisor = function () {
  30146. return this._instanceDivisor;
  30147. };
  30148. // Methods
  30149. /**
  30150. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30151. * @param data defines the data to store
  30152. */
  30153. VertexBuffer.prototype.create = function (data) {
  30154. this._buffer.create(data);
  30155. };
  30156. /**
  30157. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30158. * This function will create a new buffer if the current one is not updatable
  30159. * @param data defines the data to store
  30160. */
  30161. VertexBuffer.prototype.update = function (data) {
  30162. this._buffer.update(data);
  30163. };
  30164. /**
  30165. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30166. * Returns the directly updated WebGLBuffer.
  30167. * @param data the new data
  30168. * @param offset the new offset
  30169. * @param useBytes set to true if the offset is in bytes
  30170. */
  30171. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30172. if (useBytes === void 0) { useBytes = false; }
  30173. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30174. };
  30175. /**
  30176. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30177. */
  30178. VertexBuffer.prototype.dispose = function () {
  30179. if (this._ownsBuffer) {
  30180. this._buffer.dispose();
  30181. }
  30182. };
  30183. /**
  30184. * Enumerates each value of this vertex buffer as numbers.
  30185. * @param count the number of values to enumerate
  30186. * @param callback the callback function called for each value
  30187. */
  30188. VertexBuffer.prototype.forEach = function (count, callback) {
  30189. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30190. };
  30191. /**
  30192. * Deduces the stride given a kind.
  30193. * @param kind The kind string to deduce
  30194. * @returns The deduced stride
  30195. */
  30196. VertexBuffer.DeduceStride = function (kind) {
  30197. switch (kind) {
  30198. case VertexBuffer.UVKind:
  30199. case VertexBuffer.UV2Kind:
  30200. case VertexBuffer.UV3Kind:
  30201. case VertexBuffer.UV4Kind:
  30202. case VertexBuffer.UV5Kind:
  30203. case VertexBuffer.UV6Kind:
  30204. return 2;
  30205. case VertexBuffer.NormalKind:
  30206. case VertexBuffer.PositionKind:
  30207. return 3;
  30208. case VertexBuffer.ColorKind:
  30209. case VertexBuffer.MatricesIndicesKind:
  30210. case VertexBuffer.MatricesIndicesExtraKind:
  30211. case VertexBuffer.MatricesWeightsKind:
  30212. case VertexBuffer.MatricesWeightsExtraKind:
  30213. case VertexBuffer.TangentKind:
  30214. return 4;
  30215. default:
  30216. throw new Error("Invalid kind '" + kind + "'");
  30217. }
  30218. };
  30219. /**
  30220. * Gets the byte length of the given type.
  30221. * @param type the type
  30222. * @returns the number of bytes
  30223. */
  30224. VertexBuffer.GetTypeByteLength = function (type) {
  30225. switch (type) {
  30226. case VertexBuffer.BYTE:
  30227. case VertexBuffer.UNSIGNED_BYTE:
  30228. return 1;
  30229. case VertexBuffer.SHORT:
  30230. case VertexBuffer.UNSIGNED_SHORT:
  30231. return 2;
  30232. case VertexBuffer.INT:
  30233. case VertexBuffer.FLOAT:
  30234. return 4;
  30235. default:
  30236. throw new Error("Invalid type '" + type + "'");
  30237. }
  30238. };
  30239. /**
  30240. * Enumerates each value of the given parameters as numbers.
  30241. * @param data the data to enumerate
  30242. * @param byteOffset the byte offset of the data
  30243. * @param byteStride the byte stride of the data
  30244. * @param componentCount the number of components per element
  30245. * @param componentType the type of the component
  30246. * @param count the total number of components
  30247. * @param normalized whether the data is normalized
  30248. * @param callback the callback function called for each value
  30249. */
  30250. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30251. if (data instanceof Array) {
  30252. var offset = byteOffset / 4;
  30253. var stride = byteStride / 4;
  30254. for (var index = 0; index < count; index += componentCount) {
  30255. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30256. callback(data[offset + componentIndex], index + componentIndex);
  30257. }
  30258. offset += stride;
  30259. }
  30260. }
  30261. else {
  30262. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30263. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30264. for (var index = 0; index < count; index += componentCount) {
  30265. var componentByteOffset = byteOffset;
  30266. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30267. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30268. callback(value, index + componentIndex);
  30269. componentByteOffset += componentByteLength;
  30270. }
  30271. byteOffset += byteStride;
  30272. }
  30273. }
  30274. };
  30275. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30276. switch (type) {
  30277. case VertexBuffer.BYTE: {
  30278. var value = dataView.getInt8(byteOffset);
  30279. if (normalized) {
  30280. value = Math.max(value / 127, -1);
  30281. }
  30282. return value;
  30283. }
  30284. case VertexBuffer.UNSIGNED_BYTE: {
  30285. var value = dataView.getUint8(byteOffset);
  30286. if (normalized) {
  30287. value = value / 255;
  30288. }
  30289. return value;
  30290. }
  30291. case VertexBuffer.SHORT: {
  30292. var value = dataView.getInt16(byteOffset, true);
  30293. if (normalized) {
  30294. value = Math.max(value / 16383, -1);
  30295. }
  30296. return value;
  30297. }
  30298. case VertexBuffer.UNSIGNED_SHORT: {
  30299. var value = dataView.getUint16(byteOffset, true);
  30300. if (normalized) {
  30301. value = value / 65535;
  30302. }
  30303. return value;
  30304. }
  30305. case VertexBuffer.FLOAT: {
  30306. return dataView.getFloat32(byteOffset, true);
  30307. }
  30308. default: {
  30309. throw new Error("Invalid component type " + type);
  30310. }
  30311. }
  30312. };
  30313. /**
  30314. * The byte type.
  30315. */
  30316. VertexBuffer.BYTE = 5120;
  30317. /**
  30318. * The unsigned byte type.
  30319. */
  30320. VertexBuffer.UNSIGNED_BYTE = 5121;
  30321. /**
  30322. * The short type.
  30323. */
  30324. VertexBuffer.SHORT = 5122;
  30325. /**
  30326. * The unsigned short type.
  30327. */
  30328. VertexBuffer.UNSIGNED_SHORT = 5123;
  30329. /**
  30330. * The integer type.
  30331. */
  30332. VertexBuffer.INT = 5124;
  30333. /**
  30334. * The unsigned integer type.
  30335. */
  30336. VertexBuffer.UNSIGNED_INT = 5125;
  30337. /**
  30338. * The float type.
  30339. */
  30340. VertexBuffer.FLOAT = 5126;
  30341. // Enums
  30342. /**
  30343. * Positions
  30344. */
  30345. VertexBuffer.PositionKind = "position";
  30346. /**
  30347. * Normals
  30348. */
  30349. VertexBuffer.NormalKind = "normal";
  30350. /**
  30351. * Tangents
  30352. */
  30353. VertexBuffer.TangentKind = "tangent";
  30354. /**
  30355. * Texture coordinates
  30356. */
  30357. VertexBuffer.UVKind = "uv";
  30358. /**
  30359. * Texture coordinates 2
  30360. */
  30361. VertexBuffer.UV2Kind = "uv2";
  30362. /**
  30363. * Texture coordinates 3
  30364. */
  30365. VertexBuffer.UV3Kind = "uv3";
  30366. /**
  30367. * Texture coordinates 4
  30368. */
  30369. VertexBuffer.UV4Kind = "uv4";
  30370. /**
  30371. * Texture coordinates 5
  30372. */
  30373. VertexBuffer.UV5Kind = "uv5";
  30374. /**
  30375. * Texture coordinates 6
  30376. */
  30377. VertexBuffer.UV6Kind = "uv6";
  30378. /**
  30379. * Colors
  30380. */
  30381. VertexBuffer.ColorKind = "color";
  30382. /**
  30383. * Matrix indices (for bones)
  30384. */
  30385. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30386. /**
  30387. * Matrix weights (for bones)
  30388. */
  30389. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30390. /**
  30391. * Additional matrix indices (for bones)
  30392. */
  30393. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30394. /**
  30395. * Additional matrix weights (for bones)
  30396. */
  30397. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30398. return VertexBuffer;
  30399. }());
  30400. BABYLON.VertexBuffer = VertexBuffer;
  30401. })(BABYLON || (BABYLON = {}));
  30402. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30403. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30404. var BABYLON;
  30405. (function (BABYLON) {
  30406. /**
  30407. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30408. */
  30409. var DummyInternalTextureTracker = /** @class */ (function () {
  30410. function DummyInternalTextureTracker() {
  30411. /**
  30412. * Gets or set the previous tracker in the list
  30413. */
  30414. this.previous = null;
  30415. /**
  30416. * Gets or set the next tracker in the list
  30417. */
  30418. this.next = null;
  30419. }
  30420. return DummyInternalTextureTracker;
  30421. }());
  30422. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30423. })(BABYLON || (BABYLON = {}));
  30424. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30425. var BABYLON;
  30426. (function (BABYLON) {
  30427. /**
  30428. * Class used to store data associated with WebGL texture data for the engine
  30429. * This class should not be used directly
  30430. */
  30431. var InternalTexture = /** @class */ (function () {
  30432. /**
  30433. * Creates a new InternalTexture
  30434. * @param engine defines the engine to use
  30435. * @param dataSource defines the type of data that will be used
  30436. */
  30437. function InternalTexture(engine, dataSource) {
  30438. /**
  30439. * Observable called when the texture is loaded
  30440. */
  30441. this.onLoadedObservable = new BABYLON.Observable();
  30442. /**
  30443. * Gets or set the previous tracker in the list
  30444. */
  30445. this.previous = null;
  30446. /**
  30447. * Gets or set the next tracker in the list
  30448. */
  30449. this.next = null;
  30450. // Private
  30451. /** @hidden */
  30452. this._initialSlot = -1;
  30453. /** @hidden */
  30454. this._designatedSlot = -1;
  30455. /** @hidden */
  30456. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30457. /** @hidden */
  30458. this._comparisonFunction = 0;
  30459. /** @hidden */
  30460. this._sphericalPolynomial = null;
  30461. /** @hidden */
  30462. this._lodGenerationScale = 0;
  30463. /** @hidden */
  30464. this._lodGenerationOffset = 0;
  30465. /** @hidden */
  30466. this._isRGBD = false;
  30467. /** @hidden */
  30468. this._references = 1;
  30469. this._engine = engine;
  30470. this._dataSource = dataSource;
  30471. this._webGLTexture = engine._createTexture();
  30472. }
  30473. /**
  30474. * Gets the Engine the texture belongs to.
  30475. * @returns The babylon engine
  30476. */
  30477. InternalTexture.prototype.getEngine = function () {
  30478. return this._engine;
  30479. };
  30480. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30481. /**
  30482. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30483. */
  30484. get: function () {
  30485. return this._dataSource;
  30486. },
  30487. enumerable: true,
  30488. configurable: true
  30489. });
  30490. /**
  30491. * Increments the number of references (ie. the number of Texture that point to it)
  30492. */
  30493. InternalTexture.prototype.incrementReferences = function () {
  30494. this._references++;
  30495. };
  30496. /**
  30497. * Change the size of the texture (not the size of the content)
  30498. * @param width defines the new width
  30499. * @param height defines the new height
  30500. * @param depth defines the new depth (1 by default)
  30501. */
  30502. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30503. if (depth === void 0) { depth = 1; }
  30504. this.width = width;
  30505. this.height = height;
  30506. this.depth = depth;
  30507. this.baseWidth = width;
  30508. this.baseHeight = height;
  30509. this.baseDepth = depth;
  30510. this._size = width * height * depth;
  30511. };
  30512. /** @hidden */
  30513. InternalTexture.prototype._rebuild = function () {
  30514. var _this = this;
  30515. var proxy;
  30516. this.isReady = false;
  30517. this._cachedCoordinatesMode = null;
  30518. this._cachedWrapU = null;
  30519. this._cachedWrapV = null;
  30520. this._cachedAnisotropicFilteringLevel = null;
  30521. switch (this._dataSource) {
  30522. case InternalTexture.DATASOURCE_TEMP:
  30523. return;
  30524. case InternalTexture.DATASOURCE_URL:
  30525. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30526. _this.isReady = true;
  30527. }, null, this._buffer, undefined, this.format);
  30528. proxy._swapAndDie(this);
  30529. return;
  30530. case InternalTexture.DATASOURCE_RAW:
  30531. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30532. proxy._swapAndDie(this);
  30533. this.isReady = true;
  30534. return;
  30535. case InternalTexture.DATASOURCE_RAW3D:
  30536. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30537. proxy._swapAndDie(this);
  30538. this.isReady = true;
  30539. return;
  30540. case InternalTexture.DATASOURCE_DYNAMIC:
  30541. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30542. proxy._swapAndDie(this);
  30543. // The engine will make sure to update content so no need to flag it as isReady = true
  30544. return;
  30545. case InternalTexture.DATASOURCE_RENDERTARGET:
  30546. var options = new BABYLON.RenderTargetCreationOptions();
  30547. options.generateDepthBuffer = this._generateDepthBuffer;
  30548. options.generateMipMaps = this.generateMipMaps;
  30549. options.generateStencilBuffer = this._generateStencilBuffer;
  30550. options.samplingMode = this.samplingMode;
  30551. options.type = this.type;
  30552. if (this.isCube) {
  30553. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30554. }
  30555. else {
  30556. var size = {
  30557. width: this.width,
  30558. height: this.height
  30559. };
  30560. proxy = this._engine.createRenderTargetTexture(size, options);
  30561. }
  30562. proxy._swapAndDie(this);
  30563. this.isReady = true;
  30564. return;
  30565. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30566. var depthTextureOptions = {
  30567. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30568. comparisonFunction: this._comparisonFunction,
  30569. generateStencil: this._generateStencilBuffer,
  30570. isCube: this.isCube
  30571. };
  30572. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30573. proxy._swapAndDie(this);
  30574. this.isReady = true;
  30575. return;
  30576. case InternalTexture.DATASOURCE_CUBE:
  30577. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30578. _this.isReady = true;
  30579. }, null, this.format, this._extension);
  30580. proxy._swapAndDie(this);
  30581. return;
  30582. case InternalTexture.DATASOURCE_CUBERAW:
  30583. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30584. proxy._swapAndDie(this);
  30585. this.isReady = true;
  30586. return;
  30587. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30588. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30589. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30590. _this.isReady = true;
  30591. });
  30592. proxy._swapAndDie(this);
  30593. return;
  30594. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30595. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30596. if (proxy) {
  30597. proxy._swapAndDie(_this);
  30598. }
  30599. _this.isReady = true;
  30600. }, null, this.format, this._extension);
  30601. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30602. return;
  30603. }
  30604. };
  30605. /** @hidden */
  30606. InternalTexture.prototype._swapAndDie = function (target) {
  30607. target._webGLTexture = this._webGLTexture;
  30608. if (this._framebuffer) {
  30609. target._framebuffer = this._framebuffer;
  30610. }
  30611. if (this._depthStencilBuffer) {
  30612. target._depthStencilBuffer = this._depthStencilBuffer;
  30613. }
  30614. if (this._lodTextureHigh) {
  30615. if (target._lodTextureHigh) {
  30616. target._lodTextureHigh.dispose();
  30617. }
  30618. target._lodTextureHigh = this._lodTextureHigh;
  30619. }
  30620. if (this._lodTextureMid) {
  30621. if (target._lodTextureMid) {
  30622. target._lodTextureMid.dispose();
  30623. }
  30624. target._lodTextureMid = this._lodTextureMid;
  30625. }
  30626. if (this._lodTextureLow) {
  30627. if (target._lodTextureLow) {
  30628. target._lodTextureLow.dispose();
  30629. }
  30630. target._lodTextureLow = this._lodTextureLow;
  30631. }
  30632. var cache = this._engine.getLoadedTexturesCache();
  30633. var index = cache.indexOf(this);
  30634. if (index !== -1) {
  30635. cache.splice(index, 1);
  30636. }
  30637. };
  30638. /**
  30639. * Dispose the current allocated resources
  30640. */
  30641. InternalTexture.prototype.dispose = function () {
  30642. if (!this._webGLTexture) {
  30643. return;
  30644. }
  30645. this._references--;
  30646. if (this._references === 0) {
  30647. this._engine._releaseTexture(this);
  30648. this._webGLTexture = null;
  30649. this.previous = null;
  30650. this.next = null;
  30651. }
  30652. };
  30653. /**
  30654. * The source of the texture data is unknown
  30655. */
  30656. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30657. /**
  30658. * Texture data comes from an URL
  30659. */
  30660. InternalTexture.DATASOURCE_URL = 1;
  30661. /**
  30662. * Texture data is only used for temporary storage
  30663. */
  30664. InternalTexture.DATASOURCE_TEMP = 2;
  30665. /**
  30666. * Texture data comes from raw data (ArrayBuffer)
  30667. */
  30668. InternalTexture.DATASOURCE_RAW = 3;
  30669. /**
  30670. * Texture content is dynamic (video or dynamic texture)
  30671. */
  30672. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30673. /**
  30674. * Texture content is generated by rendering to it
  30675. */
  30676. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30677. /**
  30678. * Texture content is part of a multi render target process
  30679. */
  30680. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30681. /**
  30682. * Texture data comes from a cube data file
  30683. */
  30684. InternalTexture.DATASOURCE_CUBE = 7;
  30685. /**
  30686. * Texture data comes from a raw cube data
  30687. */
  30688. InternalTexture.DATASOURCE_CUBERAW = 8;
  30689. /**
  30690. * Texture data come from a prefiltered cube data file
  30691. */
  30692. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30693. /**
  30694. * Texture content is raw 3D data
  30695. */
  30696. InternalTexture.DATASOURCE_RAW3D = 10;
  30697. /**
  30698. * Texture content is a depth texture
  30699. */
  30700. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30701. /**
  30702. * Texture data comes from a raw cube data encoded with RGBD
  30703. */
  30704. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30705. return InternalTexture;
  30706. }());
  30707. BABYLON.InternalTexture = InternalTexture;
  30708. })(BABYLON || (BABYLON = {}));
  30709. //# sourceMappingURL=babylon.internalTexture.js.map
  30710. var BABYLON;
  30711. (function (BABYLON) {
  30712. /**
  30713. * Base class of all the textures in babylon.
  30714. * It groups all the common properties the materials, post process, lights... might need
  30715. * in order to make a correct use of the texture.
  30716. */
  30717. var BaseTexture = /** @class */ (function () {
  30718. /**
  30719. * Instantiates a new BaseTexture.
  30720. * Base class of all the textures in babylon.
  30721. * It groups all the common properties the materials, post process, lights... might need
  30722. * in order to make a correct use of the texture.
  30723. * @param scene Define the scene the texture blongs to
  30724. */
  30725. function BaseTexture(scene) {
  30726. this._hasAlpha = false;
  30727. /**
  30728. * Defines if the alpha value should be determined via the rgb values.
  30729. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30730. */
  30731. this.getAlphaFromRGB = false;
  30732. /**
  30733. * Intensity or strength of the texture.
  30734. * It is commonly used by materials to fine tune the intensity of the texture
  30735. */
  30736. this.level = 1;
  30737. /**
  30738. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30739. * This is part of the texture as textures usually maps to one uv set.
  30740. */
  30741. this.coordinatesIndex = 0;
  30742. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30743. /**
  30744. * | Value | Type | Description |
  30745. * | ----- | ------------------ | ----------- |
  30746. * | 0 | CLAMP_ADDRESSMODE | |
  30747. * | 1 | WRAP_ADDRESSMODE | |
  30748. * | 2 | MIRROR_ADDRESSMODE | |
  30749. */
  30750. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30751. /**
  30752. * | Value | Type | Description |
  30753. * | ----- | ------------------ | ----------- |
  30754. * | 0 | CLAMP_ADDRESSMODE | |
  30755. * | 1 | WRAP_ADDRESSMODE | |
  30756. * | 2 | MIRROR_ADDRESSMODE | |
  30757. */
  30758. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30759. /**
  30760. * | Value | Type | Description |
  30761. * | ----- | ------------------ | ----------- |
  30762. * | 0 | CLAMP_ADDRESSMODE | |
  30763. * | 1 | WRAP_ADDRESSMODE | |
  30764. * | 2 | MIRROR_ADDRESSMODE | |
  30765. */
  30766. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30767. /**
  30768. * With compliant hardware and browser (supporting anisotropic filtering)
  30769. * this defines the level of anisotropic filtering in the texture.
  30770. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30771. */
  30772. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30773. /**
  30774. * Define if the texture is a cube texture or if false a 2d texture.
  30775. */
  30776. this.isCube = false;
  30777. /**
  30778. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30779. */
  30780. this.is3D = false;
  30781. /**
  30782. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30783. * HDR texture are usually stored in linear space.
  30784. * This only impacts the PBR and Background materials
  30785. */
  30786. this.gammaSpace = true;
  30787. /**
  30788. * Is Z inverted in the texture (useful in a cube texture).
  30789. */
  30790. this.invertZ = false;
  30791. /**
  30792. * @hidden
  30793. */
  30794. this.lodLevelInAlpha = false;
  30795. /**
  30796. * Define if the texture is a render target.
  30797. */
  30798. this.isRenderTarget = false;
  30799. /**
  30800. * Define the list of animation attached to the texture.
  30801. */
  30802. this.animations = new Array();
  30803. /**
  30804. * An event triggered when the texture is disposed.
  30805. */
  30806. this.onDisposeObservable = new BABYLON.Observable();
  30807. /**
  30808. * Define the current state of the loading sequence when in delayed load mode.
  30809. */
  30810. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30811. this._cachedSize = BABYLON.Size.Zero();
  30812. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30813. if (this._scene) {
  30814. this._scene.textures.push(this);
  30815. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30816. }
  30817. this._uid = null;
  30818. }
  30819. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30820. get: function () {
  30821. return this._hasAlpha;
  30822. },
  30823. /**
  30824. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30825. */
  30826. set: function (value) {
  30827. if (this._hasAlpha === value) {
  30828. return;
  30829. }
  30830. this._hasAlpha = value;
  30831. if (this._scene) {
  30832. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30833. }
  30834. },
  30835. enumerable: true,
  30836. configurable: true
  30837. });
  30838. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30839. get: function () {
  30840. return this._coordinatesMode;
  30841. },
  30842. /**
  30843. * How a texture is mapped.
  30844. *
  30845. * | Value | Type | Description |
  30846. * | ----- | ----------------------------------- | ----------- |
  30847. * | 0 | EXPLICIT_MODE | |
  30848. * | 1 | SPHERICAL_MODE | |
  30849. * | 2 | PLANAR_MODE | |
  30850. * | 3 | CUBIC_MODE | |
  30851. * | 4 | PROJECTION_MODE | |
  30852. * | 5 | SKYBOX_MODE | |
  30853. * | 6 | INVCUBIC_MODE | |
  30854. * | 7 | EQUIRECTANGULAR_MODE | |
  30855. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30856. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30857. */
  30858. set: function (value) {
  30859. if (this._coordinatesMode === value) {
  30860. return;
  30861. }
  30862. this._coordinatesMode = value;
  30863. if (this._scene) {
  30864. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30865. }
  30866. },
  30867. enumerable: true,
  30868. configurable: true
  30869. });
  30870. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30871. /**
  30872. * Gets whether or not the texture contains RGBD data.
  30873. */
  30874. get: function () {
  30875. return this._texture != null && this._texture._isRGBD;
  30876. },
  30877. enumerable: true,
  30878. configurable: true
  30879. });
  30880. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30881. /**
  30882. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30883. */
  30884. get: function () {
  30885. if (this._texture)
  30886. return this._texture._lodGenerationOffset;
  30887. return 0.0;
  30888. },
  30889. set: function (value) {
  30890. if (this._texture)
  30891. this._texture._lodGenerationOffset = value;
  30892. },
  30893. enumerable: true,
  30894. configurable: true
  30895. });
  30896. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30897. /**
  30898. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30899. */
  30900. get: function () {
  30901. if (this._texture)
  30902. return this._texture._lodGenerationScale;
  30903. return 0.0;
  30904. },
  30905. set: function (value) {
  30906. if (this._texture)
  30907. this._texture._lodGenerationScale = value;
  30908. },
  30909. enumerable: true,
  30910. configurable: true
  30911. });
  30912. Object.defineProperty(BaseTexture.prototype, "uid", {
  30913. /**
  30914. * Define the unique id of the texture in the scene.
  30915. */
  30916. get: function () {
  30917. if (!this._uid) {
  30918. this._uid = BABYLON.Tools.RandomId();
  30919. }
  30920. return this._uid;
  30921. },
  30922. enumerable: true,
  30923. configurable: true
  30924. });
  30925. /**
  30926. * Return a string representation of the texture.
  30927. * @returns the texture as a string
  30928. */
  30929. BaseTexture.prototype.toString = function () {
  30930. return this.name;
  30931. };
  30932. /**
  30933. * Get the class name of the texture.
  30934. * @returns "BaseTexture"
  30935. */
  30936. BaseTexture.prototype.getClassName = function () {
  30937. return "BaseTexture";
  30938. };
  30939. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30940. /**
  30941. * Callback triggered when the texture has been disposed.
  30942. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30943. */
  30944. set: function (callback) {
  30945. if (this._onDisposeObserver) {
  30946. this.onDisposeObservable.remove(this._onDisposeObserver);
  30947. }
  30948. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30954. /**
  30955. * Define if the texture is preventinga material to render or not.
  30956. * If not and the texture is not ready, the engine will use a default black texture instead.
  30957. */
  30958. get: function () {
  30959. return true;
  30960. },
  30961. enumerable: true,
  30962. configurable: true
  30963. });
  30964. /**
  30965. * Get the scene the texture belongs to.
  30966. * @returns the scene or null if undefined
  30967. */
  30968. BaseTexture.prototype.getScene = function () {
  30969. return this._scene;
  30970. };
  30971. /**
  30972. * Get the texture transform matrix used to offset tile the texture for istance.
  30973. * @returns the transformation matrix
  30974. */
  30975. BaseTexture.prototype.getTextureMatrix = function () {
  30976. return BABYLON.Matrix.IdentityReadOnly;
  30977. };
  30978. /**
  30979. * Get the texture reflection matrix used to rotate/transform the reflection.
  30980. * @returns the reflection matrix
  30981. */
  30982. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30983. return BABYLON.Matrix.IdentityReadOnly;
  30984. };
  30985. /**
  30986. * Get the underlying lower level texture from Babylon.
  30987. * @returns the insternal texture
  30988. */
  30989. BaseTexture.prototype.getInternalTexture = function () {
  30990. return this._texture;
  30991. };
  30992. /**
  30993. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  30994. * @returns true if ready or not blocking
  30995. */
  30996. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30997. return !this.isBlocking || this.isReady();
  30998. };
  30999. /**
  31000. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31001. * @returns true if fully ready
  31002. */
  31003. BaseTexture.prototype.isReady = function () {
  31004. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31005. this.delayLoad();
  31006. return false;
  31007. }
  31008. if (this._texture) {
  31009. return this._texture.isReady;
  31010. }
  31011. return false;
  31012. };
  31013. /**
  31014. * Get the size of the texture.
  31015. * @returns the texture size.
  31016. */
  31017. BaseTexture.prototype.getSize = function () {
  31018. if (this._texture) {
  31019. if (this._texture.width) {
  31020. this._cachedSize.width = this._texture.width;
  31021. this._cachedSize.height = this._texture.height;
  31022. return this._cachedSize;
  31023. }
  31024. if (this._texture._size) {
  31025. this._cachedSize.width = this._texture._size;
  31026. this._cachedSize.height = this._texture._size;
  31027. return this._cachedSize;
  31028. }
  31029. }
  31030. return this._cachedSize;
  31031. };
  31032. /**
  31033. * Get the base size of the texture.
  31034. * It can be different from the size if the texture has been resized for POT for instance
  31035. * @returns the base size
  31036. */
  31037. BaseTexture.prototype.getBaseSize = function () {
  31038. if (!this.isReady() || !this._texture)
  31039. return BABYLON.Size.Zero();
  31040. if (this._texture._size) {
  31041. return new BABYLON.Size(this._texture._size, this._texture._size);
  31042. }
  31043. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31044. };
  31045. /**
  31046. * Scales the texture if is `canRescale()`
  31047. * @param ratio the resize factor we want to use to rescale
  31048. */
  31049. BaseTexture.prototype.scale = function (ratio) {
  31050. };
  31051. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31052. /**
  31053. * Get if the texture can rescale.
  31054. */
  31055. get: function () {
  31056. return false;
  31057. },
  31058. enumerable: true,
  31059. configurable: true
  31060. });
  31061. /** @hidden */
  31062. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31063. if (!this._scene) {
  31064. return null;
  31065. }
  31066. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31067. for (var index = 0; index < texturesCache.length; index++) {
  31068. var texturesCacheEntry = texturesCache[index];
  31069. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31070. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31071. texturesCacheEntry.incrementReferences();
  31072. return texturesCacheEntry;
  31073. }
  31074. }
  31075. }
  31076. return null;
  31077. };
  31078. /** @hidden */
  31079. BaseTexture.prototype._rebuild = function () {
  31080. };
  31081. /**
  31082. * Triggers the load sequence in delayed load mode.
  31083. */
  31084. BaseTexture.prototype.delayLoad = function () {
  31085. };
  31086. /**
  31087. * Clones the texture.
  31088. * @returns the cloned texture
  31089. */
  31090. BaseTexture.prototype.clone = function () {
  31091. return null;
  31092. };
  31093. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31094. /**
  31095. * Get the texture underlying type (INT, FLOAT...)
  31096. */
  31097. get: function () {
  31098. if (!this._texture) {
  31099. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31100. }
  31101. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31102. },
  31103. enumerable: true,
  31104. configurable: true
  31105. });
  31106. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31107. /**
  31108. * Get the texture underlying format (RGB, RGBA...)
  31109. */
  31110. get: function () {
  31111. if (!this._texture) {
  31112. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31113. }
  31114. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31115. },
  31116. enumerable: true,
  31117. configurable: true
  31118. });
  31119. /**
  31120. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31121. * This will returns an RGBA array buffer containing either in values (0-255) or
  31122. * float values (0-1) depending of the underlying buffer type.
  31123. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31124. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31125. * @param buffer defines a user defined buffer to fill with data (can be null)
  31126. * @returns The Array buffer containing the pixels data.
  31127. */
  31128. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31129. if (faceIndex === void 0) { faceIndex = 0; }
  31130. if (level === void 0) { level = 0; }
  31131. if (buffer === void 0) { buffer = null; }
  31132. if (!this._texture) {
  31133. return null;
  31134. }
  31135. var size = this.getSize();
  31136. var width = size.width;
  31137. var height = size.height;
  31138. var scene = this.getScene();
  31139. if (!scene) {
  31140. return null;
  31141. }
  31142. var engine = scene.getEngine();
  31143. if (level != 0) {
  31144. width = width / Math.pow(2, level);
  31145. height = height / Math.pow(2, level);
  31146. width = Math.round(width);
  31147. height = Math.round(height);
  31148. }
  31149. if (this._texture.isCube) {
  31150. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31151. }
  31152. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31153. };
  31154. /**
  31155. * Release and destroy the underlying lower level texture aka internalTexture.
  31156. */
  31157. BaseTexture.prototype.releaseInternalTexture = function () {
  31158. if (this._texture) {
  31159. this._texture.dispose();
  31160. this._texture = null;
  31161. }
  31162. };
  31163. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31164. /**
  31165. * Get the polynomial representation of the texture data.
  31166. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31167. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31168. */
  31169. get: function () {
  31170. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31171. return null;
  31172. }
  31173. if (!this._texture._sphericalPolynomial) {
  31174. this._texture._sphericalPolynomial =
  31175. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31176. }
  31177. return this._texture._sphericalPolynomial;
  31178. },
  31179. set: function (value) {
  31180. if (this._texture) {
  31181. this._texture._sphericalPolynomial = value;
  31182. }
  31183. },
  31184. enumerable: true,
  31185. configurable: true
  31186. });
  31187. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31188. /** @hidden */
  31189. get: function () {
  31190. if (this._texture) {
  31191. return this._texture._lodTextureHigh;
  31192. }
  31193. return null;
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31199. /** @hidden */
  31200. get: function () {
  31201. if (this._texture) {
  31202. return this._texture._lodTextureMid;
  31203. }
  31204. return null;
  31205. },
  31206. enumerable: true,
  31207. configurable: true
  31208. });
  31209. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31210. /** @hidden */
  31211. get: function () {
  31212. if (this._texture) {
  31213. return this._texture._lodTextureLow;
  31214. }
  31215. return null;
  31216. },
  31217. enumerable: true,
  31218. configurable: true
  31219. });
  31220. /**
  31221. * Dispose the texture and release its associated resources.
  31222. */
  31223. BaseTexture.prototype.dispose = function () {
  31224. if (!this._scene) {
  31225. return;
  31226. }
  31227. // Animations
  31228. this._scene.stopAnimation(this);
  31229. // Remove from scene
  31230. this._scene._removePendingData(this);
  31231. var index = this._scene.textures.indexOf(this);
  31232. if (index >= 0) {
  31233. this._scene.textures.splice(index, 1);
  31234. }
  31235. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31236. if (this._texture === undefined) {
  31237. return;
  31238. }
  31239. // Release
  31240. this.releaseInternalTexture();
  31241. // Callback
  31242. this.onDisposeObservable.notifyObservers(this);
  31243. this.onDisposeObservable.clear();
  31244. };
  31245. /**
  31246. * Serialize the texture into a JSON representation that can be parsed later on.
  31247. * @returns the JSON representation of the texture
  31248. */
  31249. BaseTexture.prototype.serialize = function () {
  31250. if (!this.name) {
  31251. return null;
  31252. }
  31253. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31254. // Animations
  31255. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31256. return serializationObject;
  31257. };
  31258. /**
  31259. * Helper function to be called back once a list of texture contains only ready textures.
  31260. * @param textures Define the list of textures to wait for
  31261. * @param callback Define the callback triggered once the entire list will be ready
  31262. */
  31263. BaseTexture.WhenAllReady = function (textures, callback) {
  31264. var numRemaining = textures.length;
  31265. if (numRemaining === 0) {
  31266. callback();
  31267. return;
  31268. }
  31269. var _loop_1 = function () {
  31270. texture = textures[i];
  31271. if (texture.isReady()) {
  31272. if (--numRemaining === 0) {
  31273. callback();
  31274. }
  31275. }
  31276. else {
  31277. onLoadObservable = texture.onLoadObservable;
  31278. var onLoadCallback_1 = function () {
  31279. onLoadObservable.removeCallback(onLoadCallback_1);
  31280. if (--numRemaining === 0) {
  31281. callback();
  31282. }
  31283. };
  31284. onLoadObservable.add(onLoadCallback_1);
  31285. }
  31286. };
  31287. var texture, onLoadObservable;
  31288. for (var i = 0; i < textures.length; i++) {
  31289. _loop_1();
  31290. }
  31291. };
  31292. /**
  31293. * Default anisotropic filtering level for the application.
  31294. * It is set to 4 as a good tradeoff between perf and quality.
  31295. */
  31296. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31297. __decorate([
  31298. BABYLON.serialize()
  31299. ], BaseTexture.prototype, "name", void 0);
  31300. __decorate([
  31301. BABYLON.serialize("hasAlpha")
  31302. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31303. __decorate([
  31304. BABYLON.serialize()
  31305. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31306. __decorate([
  31307. BABYLON.serialize()
  31308. ], BaseTexture.prototype, "level", void 0);
  31309. __decorate([
  31310. BABYLON.serialize()
  31311. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31312. __decorate([
  31313. BABYLON.serialize("coordinatesMode")
  31314. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31315. __decorate([
  31316. BABYLON.serialize()
  31317. ], BaseTexture.prototype, "wrapU", void 0);
  31318. __decorate([
  31319. BABYLON.serialize()
  31320. ], BaseTexture.prototype, "wrapV", void 0);
  31321. __decorate([
  31322. BABYLON.serialize()
  31323. ], BaseTexture.prototype, "wrapR", void 0);
  31324. __decorate([
  31325. BABYLON.serialize()
  31326. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31327. __decorate([
  31328. BABYLON.serialize()
  31329. ], BaseTexture.prototype, "isCube", void 0);
  31330. __decorate([
  31331. BABYLON.serialize()
  31332. ], BaseTexture.prototype, "is3D", void 0);
  31333. __decorate([
  31334. BABYLON.serialize()
  31335. ], BaseTexture.prototype, "gammaSpace", void 0);
  31336. __decorate([
  31337. BABYLON.serialize()
  31338. ], BaseTexture.prototype, "invertZ", void 0);
  31339. __decorate([
  31340. BABYLON.serialize()
  31341. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31342. __decorate([
  31343. BABYLON.serialize()
  31344. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31345. __decorate([
  31346. BABYLON.serialize()
  31347. ], BaseTexture.prototype, "lodGenerationScale", null);
  31348. __decorate([
  31349. BABYLON.serialize()
  31350. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31351. return BaseTexture;
  31352. }());
  31353. BABYLON.BaseTexture = BaseTexture;
  31354. })(BABYLON || (BABYLON = {}));
  31355. //# sourceMappingURL=babylon.baseTexture.js.map
  31356. var BABYLON;
  31357. (function (BABYLON) {
  31358. /**
  31359. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31360. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31361. */
  31362. var Texture = /** @class */ (function (_super) {
  31363. __extends(Texture, _super);
  31364. /**
  31365. * Instantiates a new texture.
  31366. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31367. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31368. * @param url define the url of the picture to load as a texture
  31369. * @param scene define the scene the texture will belong to
  31370. * @param noMipmap define if the texture will require mip maps or not
  31371. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31372. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31373. * @param onLoad define a callback triggered when the texture has been loaded
  31374. * @param onError define a callback triggered when an error occurred during the loading session
  31375. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31376. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31377. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31378. */
  31379. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31380. if (noMipmap === void 0) { noMipmap = false; }
  31381. if (invertY === void 0) { invertY = true; }
  31382. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31383. if (onLoad === void 0) { onLoad = null; }
  31384. if (onError === void 0) { onError = null; }
  31385. if (buffer === void 0) { buffer = null; }
  31386. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31387. var _this = _super.call(this, scene) || this;
  31388. /**
  31389. * Define an offset on the texture to offset the u coordinates of the UVs
  31390. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31391. */
  31392. _this.uOffset = 0;
  31393. /**
  31394. * Define an offset on the texture to offset the v coordinates of the UVs
  31395. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31396. */
  31397. _this.vOffset = 0;
  31398. /**
  31399. * Define an offset on the texture to scale the u coordinates of the UVs
  31400. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31401. */
  31402. _this.uScale = 1.0;
  31403. /**
  31404. * Define an offset on the texture to scale the v coordinates of the UVs
  31405. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31406. */
  31407. _this.vScale = 1.0;
  31408. /**
  31409. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31410. * @see http://doc.babylonjs.com/how_to/more_materials
  31411. */
  31412. _this.uAng = 0;
  31413. /**
  31414. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31415. * @see http://doc.babylonjs.com/how_to/more_materials
  31416. */
  31417. _this.vAng = 0;
  31418. /**
  31419. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31420. * @see http://doc.babylonjs.com/how_to/more_materials
  31421. */
  31422. _this.wAng = 0;
  31423. /**
  31424. * Defines the center of rotation (U)
  31425. */
  31426. _this.uRotationCenter = 0.5;
  31427. /**
  31428. * Defines the center of rotation (V)
  31429. */
  31430. _this.vRotationCenter = 0.5;
  31431. /**
  31432. * Defines the center of rotation (W)
  31433. */
  31434. _this.wRotationCenter = 0.5;
  31435. /**
  31436. * Observable triggered once the texture has been loaded.
  31437. */
  31438. _this.onLoadObservable = new BABYLON.Observable();
  31439. _this._isBlocking = true;
  31440. _this.name = url || "";
  31441. _this.url = url;
  31442. _this._noMipmap = noMipmap;
  31443. _this._invertY = invertY;
  31444. _this._samplingMode = samplingMode;
  31445. _this._buffer = buffer;
  31446. _this._deleteBuffer = deleteBuffer;
  31447. if (format) {
  31448. _this._format = format;
  31449. }
  31450. scene = _this.getScene();
  31451. if (!scene) {
  31452. return _this;
  31453. }
  31454. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31455. var load = function () {
  31456. if (_this.onLoadObservable.hasObservers()) {
  31457. _this.onLoadObservable.notifyObservers(_this);
  31458. }
  31459. if (onLoad) {
  31460. onLoad();
  31461. }
  31462. if (!_this.isBlocking && scene) {
  31463. scene.resetCachedMaterial();
  31464. }
  31465. };
  31466. if (!_this.url) {
  31467. _this._delayedOnLoad = load;
  31468. _this._delayedOnError = onError;
  31469. return _this;
  31470. }
  31471. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31472. if (!_this._texture) {
  31473. if (!scene.useDelayedTextureLoading) {
  31474. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31475. if (deleteBuffer) {
  31476. delete _this._buffer;
  31477. }
  31478. }
  31479. else {
  31480. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31481. _this._delayedOnLoad = load;
  31482. _this._delayedOnError = onError;
  31483. }
  31484. }
  31485. else {
  31486. if (_this._texture.isReady) {
  31487. BABYLON.Tools.SetImmediate(function () { return load(); });
  31488. }
  31489. else {
  31490. _this._texture.onLoadedObservable.add(load);
  31491. }
  31492. }
  31493. return _this;
  31494. }
  31495. Object.defineProperty(Texture.prototype, "noMipmap", {
  31496. /**
  31497. * Are mip maps generated for this texture or not.
  31498. */
  31499. get: function () {
  31500. return this._noMipmap;
  31501. },
  31502. enumerable: true,
  31503. configurable: true
  31504. });
  31505. Object.defineProperty(Texture.prototype, "isBlocking", {
  31506. get: function () {
  31507. return this._isBlocking;
  31508. },
  31509. /**
  31510. * Is the texture preventing material to render while loading.
  31511. * If false, a default texture will be used instead of the loading one during the preparation step.
  31512. */
  31513. set: function (value) {
  31514. this._isBlocking = value;
  31515. },
  31516. enumerable: true,
  31517. configurable: true
  31518. });
  31519. Object.defineProperty(Texture.prototype, "samplingMode", {
  31520. /**
  31521. * Get the current sampling mode associated with the texture.
  31522. */
  31523. get: function () {
  31524. return this._samplingMode;
  31525. },
  31526. enumerable: true,
  31527. configurable: true
  31528. });
  31529. /**
  31530. * Update the url (and optional buffer) of this texture if url was null during construction.
  31531. * @param url the url of the texture
  31532. * @param buffer the buffer of the texture (defaults to null)
  31533. */
  31534. Texture.prototype.updateURL = function (url, buffer) {
  31535. if (buffer === void 0) { buffer = null; }
  31536. if (this.url) {
  31537. throw new Error("URL is already set");
  31538. }
  31539. this.url = url;
  31540. this._buffer = buffer;
  31541. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31542. this.delayLoad();
  31543. };
  31544. /**
  31545. * Finish the loading sequence of a texture flagged as delayed load.
  31546. * @hidden
  31547. */
  31548. Texture.prototype.delayLoad = function () {
  31549. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31550. return;
  31551. }
  31552. var scene = this.getScene();
  31553. if (!scene) {
  31554. return;
  31555. }
  31556. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31557. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31558. if (!this._texture) {
  31559. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31560. if (this._deleteBuffer) {
  31561. delete this._buffer;
  31562. }
  31563. }
  31564. else {
  31565. if (this._delayedOnLoad) {
  31566. if (this._texture.isReady) {
  31567. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31568. }
  31569. else {
  31570. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31571. }
  31572. }
  31573. }
  31574. this._delayedOnLoad = null;
  31575. this._delayedOnError = null;
  31576. };
  31577. /**
  31578. * Update the sampling mode of the texture.
  31579. * Default is Trilinear mode.
  31580. *
  31581. * | Value | Type | Description |
  31582. * | ----- | ------------------ | ----------- |
  31583. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31584. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31585. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31586. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31587. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31588. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31589. * | 7 | NEAREST_LINEAR | |
  31590. * | 8 | NEAREST_NEAREST | |
  31591. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31592. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31593. * | 11 | LINEAR_LINEAR | |
  31594. * | 12 | LINEAR_NEAREST | |
  31595. *
  31596. * > _mag_: magnification filter (close to the viewer)
  31597. * > _min_: minification filter (far from the viewer)
  31598. * > _mip_: filter used between mip map levels
  31599. *@param samplingMode Define the new sampling mode of the texture
  31600. */
  31601. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31602. if (!this._texture) {
  31603. return;
  31604. }
  31605. var scene = this.getScene();
  31606. if (!scene) {
  31607. return;
  31608. }
  31609. this._samplingMode = samplingMode;
  31610. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31611. };
  31612. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31613. x *= this.uScale;
  31614. y *= this.vScale;
  31615. x -= this.uRotationCenter * this.uScale;
  31616. y -= this.vRotationCenter * this.vScale;
  31617. z -= this.wRotationCenter;
  31618. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31619. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31620. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31621. t.z += this.wRotationCenter;
  31622. };
  31623. /**
  31624. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31625. * @returns the transform matrix of the texture.
  31626. */
  31627. Texture.prototype.getTextureMatrix = function () {
  31628. var _this = this;
  31629. if (this.uOffset === this._cachedUOffset &&
  31630. this.vOffset === this._cachedVOffset &&
  31631. this.uScale === this._cachedUScale &&
  31632. this.vScale === this._cachedVScale &&
  31633. this.uAng === this._cachedUAng &&
  31634. this.vAng === this._cachedVAng &&
  31635. this.wAng === this._cachedWAng) {
  31636. return this._cachedTextureMatrix;
  31637. }
  31638. this._cachedUOffset = this.uOffset;
  31639. this._cachedVOffset = this.vOffset;
  31640. this._cachedUScale = this.uScale;
  31641. this._cachedVScale = this.vScale;
  31642. this._cachedUAng = this.uAng;
  31643. this._cachedVAng = this.vAng;
  31644. this._cachedWAng = this.wAng;
  31645. if (!this._cachedTextureMatrix) {
  31646. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31647. this._rowGenerationMatrix = new BABYLON.Matrix();
  31648. this._t0 = BABYLON.Vector3.Zero();
  31649. this._t1 = BABYLON.Vector3.Zero();
  31650. this._t2 = BABYLON.Vector3.Zero();
  31651. }
  31652. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31653. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31654. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31655. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31656. this._t1.subtractInPlace(this._t0);
  31657. this._t2.subtractInPlace(this._t0);
  31658. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31659. this._cachedTextureMatrix.m[0] = this._t1.x;
  31660. this._cachedTextureMatrix.m[1] = this._t1.y;
  31661. this._cachedTextureMatrix.m[2] = this._t1.z;
  31662. this._cachedTextureMatrix.m[4] = this._t2.x;
  31663. this._cachedTextureMatrix.m[5] = this._t2.y;
  31664. this._cachedTextureMatrix.m[6] = this._t2.z;
  31665. this._cachedTextureMatrix.m[8] = this._t0.x;
  31666. this._cachedTextureMatrix.m[9] = this._t0.y;
  31667. this._cachedTextureMatrix.m[10] = this._t0.z;
  31668. var scene = this.getScene();
  31669. if (!scene) {
  31670. return this._cachedTextureMatrix;
  31671. }
  31672. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31673. return mat.hasTexture(_this);
  31674. });
  31675. return this._cachedTextureMatrix;
  31676. };
  31677. /**
  31678. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31679. * @returns The reflection texture transform
  31680. */
  31681. Texture.prototype.getReflectionTextureMatrix = function () {
  31682. var _this = this;
  31683. var scene = this.getScene();
  31684. if (!scene) {
  31685. return this._cachedTextureMatrix;
  31686. }
  31687. if (this.uOffset === this._cachedUOffset &&
  31688. this.vOffset === this._cachedVOffset &&
  31689. this.uScale === this._cachedUScale &&
  31690. this.vScale === this._cachedVScale &&
  31691. this.coordinatesMode === this._cachedCoordinatesMode) {
  31692. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31693. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31694. return this._cachedTextureMatrix;
  31695. }
  31696. }
  31697. else {
  31698. return this._cachedTextureMatrix;
  31699. }
  31700. }
  31701. if (!this._cachedTextureMatrix) {
  31702. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31703. }
  31704. if (!this._projectionModeMatrix) {
  31705. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31706. }
  31707. this._cachedUOffset = this.uOffset;
  31708. this._cachedVOffset = this.vOffset;
  31709. this._cachedUScale = this.uScale;
  31710. this._cachedVScale = this.vScale;
  31711. this._cachedCoordinatesMode = this.coordinatesMode;
  31712. switch (this.coordinatesMode) {
  31713. case Texture.PLANAR_MODE:
  31714. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31715. this._cachedTextureMatrix[0] = this.uScale;
  31716. this._cachedTextureMatrix[5] = this.vScale;
  31717. this._cachedTextureMatrix[12] = this.uOffset;
  31718. this._cachedTextureMatrix[13] = this.vOffset;
  31719. break;
  31720. case Texture.PROJECTION_MODE:
  31721. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31722. this._projectionModeMatrix.m[0] = 0.5;
  31723. this._projectionModeMatrix.m[5] = -0.5;
  31724. this._projectionModeMatrix.m[10] = 0.0;
  31725. this._projectionModeMatrix.m[12] = 0.5;
  31726. this._projectionModeMatrix.m[13] = 0.5;
  31727. this._projectionModeMatrix.m[14] = 1.0;
  31728. this._projectionModeMatrix.m[15] = 1.0;
  31729. var projectionMatrix = scene.getProjectionMatrix();
  31730. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31731. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31732. break;
  31733. default:
  31734. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31735. break;
  31736. }
  31737. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31738. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31739. });
  31740. return this._cachedTextureMatrix;
  31741. };
  31742. /**
  31743. * Clones the texture.
  31744. * @returns the cloned texture
  31745. */
  31746. Texture.prototype.clone = function () {
  31747. var _this = this;
  31748. return BABYLON.SerializationHelper.Clone(function () {
  31749. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31750. }, this);
  31751. };
  31752. /**
  31753. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31754. * @returns The JSON representation of the texture
  31755. */
  31756. Texture.prototype.serialize = function () {
  31757. var serializationObject = _super.prototype.serialize.call(this);
  31758. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31759. serializationObject.base64String = this._buffer;
  31760. serializationObject.name = serializationObject.name.replace("data:", "");
  31761. }
  31762. serializationObject.invertY = this._invertY;
  31763. serializationObject.samplingMode = this.samplingMode;
  31764. return serializationObject;
  31765. };
  31766. /**
  31767. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31768. * @returns "Texture"
  31769. */
  31770. Texture.prototype.getClassName = function () {
  31771. return "Texture";
  31772. };
  31773. /**
  31774. * Dispose the texture and release its associated resources.
  31775. */
  31776. Texture.prototype.dispose = function () {
  31777. _super.prototype.dispose.call(this);
  31778. this.onLoadObservable.clear();
  31779. this._delayedOnLoad = null;
  31780. this._delayedOnError = null;
  31781. };
  31782. /**
  31783. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31784. * @param parsedTexture Define the JSON representation of the texture
  31785. * @param scene Define the scene the parsed texture should be instantiated in
  31786. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31787. * @returns The parsed texture if successful
  31788. */
  31789. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31790. if (parsedTexture.customType) {
  31791. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31792. // Update Sampling Mode
  31793. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31794. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31795. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31796. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31797. }
  31798. }
  31799. return parsedCustomTexture;
  31800. }
  31801. if (parsedTexture.isCube) {
  31802. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31803. }
  31804. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31805. return null;
  31806. }
  31807. var texture = BABYLON.SerializationHelper.Parse(function () {
  31808. var generateMipMaps = true;
  31809. if (parsedTexture.noMipmap) {
  31810. generateMipMaps = false;
  31811. }
  31812. if (parsedTexture.mirrorPlane) {
  31813. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31814. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31815. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31816. return mirrorTexture;
  31817. }
  31818. else if (parsedTexture.isRenderTarget) {
  31819. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31820. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31821. return renderTargetTexture;
  31822. }
  31823. else {
  31824. var texture;
  31825. if (parsedTexture.base64String) {
  31826. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31827. }
  31828. else {
  31829. var url = rootUrl + parsedTexture.name;
  31830. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31831. url = parsedTexture.url;
  31832. }
  31833. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31834. }
  31835. return texture;
  31836. }
  31837. }, parsedTexture, scene);
  31838. // Update Sampling Mode
  31839. if (parsedTexture.samplingMode) {
  31840. var sampling = parsedTexture.samplingMode;
  31841. if (texture._samplingMode !== sampling) {
  31842. texture.updateSamplingMode(sampling);
  31843. }
  31844. }
  31845. // Animations
  31846. if (parsedTexture.animations) {
  31847. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31848. var parsedAnimation = parsedTexture.animations[animationIndex];
  31849. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31850. }
  31851. }
  31852. return texture;
  31853. };
  31854. /**
  31855. * Creates a texture from its base 64 representation.
  31856. * @param data Define the base64 payload without the data: prefix
  31857. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31858. * @param scene Define the scene the texture should belong to
  31859. * @param noMipmap Forces the texture to not create mip map information if true
  31860. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31861. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31862. * @param onLoad define a callback triggered when the texture has been loaded
  31863. * @param onError define a callback triggered when an error occurred during the loading session
  31864. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31865. * @returns the created texture
  31866. */
  31867. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31868. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31869. if (onLoad === void 0) { onLoad = null; }
  31870. if (onError === void 0) { onError = null; }
  31871. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31872. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31873. };
  31874. /**
  31875. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  31876. * @param data Define the base64 payload without the data: prefix
  31877. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31878. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31879. * @param scene Define the scene the texture should belong to
  31880. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31881. * @param noMipmap Forces the texture to not create mip map information if true
  31882. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31883. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31884. * @param onLoad define a callback triggered when the texture has been loaded
  31885. * @param onError define a callback triggered when an error occurred during the loading session
  31886. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31887. * @returns the created texture
  31888. */
  31889. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31890. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31891. if (noMipmap === void 0) { noMipmap = false; }
  31892. if (invertY === void 0) { invertY = true; }
  31893. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31894. if (onLoad === void 0) { onLoad = null; }
  31895. if (onError === void 0) { onError = null; }
  31896. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31897. if (name.substr(0, 5) !== "data:") {
  31898. name = "data:" + name;
  31899. }
  31900. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31901. };
  31902. /** nearest is mag = nearest and min = nearest and mip = linear */
  31903. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31904. /** nearest is mag = nearest and min = nearest and mip = linear */
  31905. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31906. /** Bilinear is mag = linear and min = linear and mip = nearest */
  31907. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31908. /** Bilinear is mag = linear and min = linear and mip = nearest */
  31909. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31910. /** Trilinear is mag = linear and min = linear and mip = linear */
  31911. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31912. /** Trilinear is mag = linear and min = linear and mip = linear */
  31913. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31914. /** mag = nearest and min = nearest and mip = nearest */
  31915. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31916. /** mag = nearest and min = linear and mip = nearest */
  31917. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31918. /** mag = nearest and min = linear and mip = linear */
  31919. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31920. /** mag = nearest and min = linear and mip = none */
  31921. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31922. /** mag = nearest and min = nearest and mip = none */
  31923. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31924. /** mag = linear and min = nearest and mip = nearest */
  31925. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31926. /** mag = linear and min = nearest and mip = linear */
  31927. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31928. /** mag = linear and min = linear and mip = none */
  31929. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31930. /** mag = linear and min = nearest and mip = none */
  31931. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31932. /** Explicit coordinates mode */
  31933. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31934. /** Spherical coordinates mode */
  31935. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31936. /** Planar coordinates mode */
  31937. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31938. /** Cubic coordinates mode */
  31939. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31940. /** Projection coordinates mode */
  31941. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31942. /** Inverse Cubic coordinates mode */
  31943. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31944. /** Inverse Cubic coordinates mode */
  31945. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31946. /** Equirectangular coordinates mode */
  31947. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31948. /** Equirectangular Fixed coordinates mode */
  31949. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31950. /** Equirectangular Fixed Mirrored coordinates mode */
  31951. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31952. /** Texture is not repeating outside of 0..1 UVs */
  31953. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31954. /** Texture is repeating outside of 0..1 UVs */
  31955. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31956. /** Texture is repeating and mirrored */
  31957. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31958. /**
  31959. * 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
  31960. */
  31961. Texture.UseSerializedUrlIfAny = false;
  31962. __decorate([
  31963. BABYLON.serialize()
  31964. ], Texture.prototype, "url", void 0);
  31965. __decorate([
  31966. BABYLON.serialize()
  31967. ], Texture.prototype, "uOffset", void 0);
  31968. __decorate([
  31969. BABYLON.serialize()
  31970. ], Texture.prototype, "vOffset", void 0);
  31971. __decorate([
  31972. BABYLON.serialize()
  31973. ], Texture.prototype, "uScale", void 0);
  31974. __decorate([
  31975. BABYLON.serialize()
  31976. ], Texture.prototype, "vScale", void 0);
  31977. __decorate([
  31978. BABYLON.serialize()
  31979. ], Texture.prototype, "uAng", void 0);
  31980. __decorate([
  31981. BABYLON.serialize()
  31982. ], Texture.prototype, "vAng", void 0);
  31983. __decorate([
  31984. BABYLON.serialize()
  31985. ], Texture.prototype, "wAng", void 0);
  31986. __decorate([
  31987. BABYLON.serialize()
  31988. ], Texture.prototype, "uRotationCenter", void 0);
  31989. __decorate([
  31990. BABYLON.serialize()
  31991. ], Texture.prototype, "vRotationCenter", void 0);
  31992. __decorate([
  31993. BABYLON.serialize()
  31994. ], Texture.prototype, "wRotationCenter", void 0);
  31995. __decorate([
  31996. BABYLON.serialize()
  31997. ], Texture.prototype, "isBlocking", null);
  31998. return Texture;
  31999. }(BABYLON.BaseTexture));
  32000. BABYLON.Texture = Texture;
  32001. })(BABYLON || (BABYLON = {}));
  32002. //# sourceMappingURL=babylon.texture.js.map
  32003. var BABYLON;
  32004. (function (BABYLON) {
  32005. /**
  32006. * @hidden
  32007. **/
  32008. var _CreationDataStorage = /** @class */ (function () {
  32009. function _CreationDataStorage() {
  32010. }
  32011. return _CreationDataStorage;
  32012. }());
  32013. BABYLON._CreationDataStorage = _CreationDataStorage;
  32014. /**
  32015. * @hidden
  32016. **/
  32017. var _InstanceDataStorage = /** @class */ (function () {
  32018. function _InstanceDataStorage() {
  32019. this.visibleInstances = {};
  32020. this.renderIdForInstances = new Array();
  32021. this.batchCache = new _InstancesBatch();
  32022. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32023. }
  32024. return _InstanceDataStorage;
  32025. }());
  32026. /**
  32027. * @hidden
  32028. **/
  32029. var _InstancesBatch = /** @class */ (function () {
  32030. function _InstancesBatch() {
  32031. this.mustReturn = false;
  32032. this.visibleInstances = new Array();
  32033. this.renderSelf = new Array();
  32034. }
  32035. return _InstancesBatch;
  32036. }());
  32037. BABYLON._InstancesBatch = _InstancesBatch;
  32038. /**
  32039. * Class used to represent renderable models
  32040. */
  32041. var Mesh = /** @class */ (function (_super) {
  32042. __extends(Mesh, _super);
  32043. /**
  32044. * @constructor
  32045. * @param name The value used by scene.getMeshByName() to do a lookup.
  32046. * @param scene The scene to add this mesh to.
  32047. * @param parent The parent of this mesh, if it has one
  32048. * @param source An optional Mesh from which geometry is shared, cloned.
  32049. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32050. * When false, achieved by calling a clone(), also passing False.
  32051. * This will make creation of children, recursive.
  32052. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32053. */
  32054. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32055. if (scene === void 0) { scene = null; }
  32056. if (parent === void 0) { parent = null; }
  32057. if (source === void 0) { source = null; }
  32058. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32059. var _this = _super.call(this, name, scene) || this;
  32060. // Members
  32061. /**
  32062. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32063. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32064. */
  32065. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32066. /**
  32067. * Gets the list of instances created from this mesh
  32068. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32069. */
  32070. _this.instances = new Array();
  32071. _this._LODLevels = new Array();
  32072. /** @hidden */
  32073. _this._instanceDataStorage = new _InstanceDataStorage();
  32074. // Use by builder only to know what orientation were the mesh build in.
  32075. /** @hidden */
  32076. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32077. /**
  32078. * Use this property to change the original side orientation defined at construction time
  32079. */
  32080. _this.overrideMaterialSideOrientation = null;
  32081. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32082. // Will be used to save a source mesh reference, If any
  32083. _this._source = null;
  32084. scene = _this.getScene();
  32085. if (source) {
  32086. // Geometry
  32087. if (source._geometry) {
  32088. source._geometry.applyToMesh(_this);
  32089. }
  32090. // Deep copy
  32091. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32092. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32093. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32094. ], ["_poseMatrix"]);
  32095. // Source mesh
  32096. _this._source = source;
  32097. // Construction Params
  32098. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32099. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32100. _this._creationDataStorage = source._creationDataStorage;
  32101. // Animation ranges
  32102. if (_this._source._ranges) {
  32103. var ranges = _this._source._ranges;
  32104. for (var name in ranges) {
  32105. if (!ranges.hasOwnProperty(name)) {
  32106. continue;
  32107. }
  32108. if (!ranges[name]) {
  32109. continue;
  32110. }
  32111. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32112. }
  32113. }
  32114. // Metadata
  32115. if (source.metadata && source.metadata.clone) {
  32116. _this.metadata = source.metadata.clone();
  32117. }
  32118. else {
  32119. _this.metadata = source.metadata;
  32120. }
  32121. // Tags
  32122. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32123. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32124. }
  32125. // Parent
  32126. _this.parent = source.parent;
  32127. // Pivot
  32128. _this.setPivotMatrix(source.getPivotMatrix());
  32129. _this.id = name + "." + source.id;
  32130. // Material
  32131. _this.material = source.material;
  32132. var index;
  32133. if (!doNotCloneChildren) {
  32134. // Children
  32135. var directDescendants = source.getDescendants(true);
  32136. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32137. var child = directDescendants[index_1];
  32138. if (child.clone) {
  32139. child.clone(name + "." + child.name, _this);
  32140. }
  32141. }
  32142. }
  32143. // Physics clone
  32144. var physicsEngine = _this.getScene().getPhysicsEngine();
  32145. if (clonePhysicsImpostor && physicsEngine) {
  32146. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32147. if (impostor) {
  32148. _this.physicsImpostor = impostor.clone(_this);
  32149. }
  32150. }
  32151. // Particles
  32152. for (index = 0; index < scene.particleSystems.length; index++) {
  32153. var system = scene.particleSystems[index];
  32154. if (system.emitter === source) {
  32155. system.clone(system.name, _this);
  32156. }
  32157. }
  32158. _this.refreshBoundingInfo();
  32159. _this.computeWorldMatrix(true);
  32160. }
  32161. // Parent
  32162. if (parent !== null) {
  32163. _this.parent = parent;
  32164. }
  32165. return _this;
  32166. }
  32167. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32168. /**
  32169. * An event triggered before rendering the mesh
  32170. */
  32171. get: function () {
  32172. if (!this._onBeforeRenderObservable) {
  32173. this._onBeforeRenderObservable = new BABYLON.Observable();
  32174. }
  32175. return this._onBeforeRenderObservable;
  32176. },
  32177. enumerable: true,
  32178. configurable: true
  32179. });
  32180. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32181. /**
  32182. * An event triggered after rendering the mesh
  32183. */
  32184. get: function () {
  32185. if (!this._onAfterRenderObservable) {
  32186. this._onAfterRenderObservable = new BABYLON.Observable();
  32187. }
  32188. return this._onAfterRenderObservable;
  32189. },
  32190. enumerable: true,
  32191. configurable: true
  32192. });
  32193. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32194. /**
  32195. * An event triggered before drawing the mesh
  32196. */
  32197. get: function () {
  32198. if (!this._onBeforeDrawObservable) {
  32199. this._onBeforeDrawObservable = new BABYLON.Observable();
  32200. }
  32201. return this._onBeforeDrawObservable;
  32202. },
  32203. enumerable: true,
  32204. configurable: true
  32205. });
  32206. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32207. /**
  32208. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32209. */
  32210. set: function (callback) {
  32211. if (this._onBeforeDrawObserver) {
  32212. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32213. }
  32214. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32215. },
  32216. enumerable: true,
  32217. configurable: true
  32218. });
  32219. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32220. /**
  32221. * Gets or sets the morph target manager
  32222. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32223. */
  32224. get: function () {
  32225. return this._morphTargetManager;
  32226. },
  32227. set: function (value) {
  32228. if (this._morphTargetManager === value) {
  32229. return;
  32230. }
  32231. this._morphTargetManager = value;
  32232. this._syncGeometryWithMorphTargetManager();
  32233. },
  32234. enumerable: true,
  32235. configurable: true
  32236. });
  32237. Object.defineProperty(Mesh.prototype, "source", {
  32238. /**
  32239. * Gets the source mesh (the one used to clone this one from)
  32240. */
  32241. get: function () {
  32242. return this._source;
  32243. },
  32244. enumerable: true,
  32245. configurable: true
  32246. });
  32247. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32248. /**
  32249. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32250. */
  32251. get: function () {
  32252. return this._unIndexed;
  32253. },
  32254. set: function (value) {
  32255. if (this._unIndexed !== value) {
  32256. this._unIndexed = value;
  32257. this._markSubMeshesAsAttributesDirty();
  32258. }
  32259. },
  32260. enumerable: true,
  32261. configurable: true
  32262. });
  32263. // Methods
  32264. /**
  32265. * Gets the class name
  32266. * @returns the string "Mesh".
  32267. */
  32268. Mesh.prototype.getClassName = function () {
  32269. return "Mesh";
  32270. };
  32271. /**
  32272. * Returns a description of this mesh
  32273. * @param fullDetails define if full details about this mesh must be used
  32274. * @returns a descriptive string representing this mesh
  32275. */
  32276. Mesh.prototype.toString = function (fullDetails) {
  32277. var ret = _super.prototype.toString.call(this, fullDetails);
  32278. ret += ", n vertices: " + this.getTotalVertices();
  32279. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32280. if (this.animations) {
  32281. for (var i = 0; i < this.animations.length; i++) {
  32282. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32283. }
  32284. }
  32285. if (fullDetails) {
  32286. if (this._geometry) {
  32287. var ib = this.getIndices();
  32288. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32289. if (vb && ib) {
  32290. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32291. }
  32292. }
  32293. else {
  32294. ret += ", flat shading: UNKNOWN";
  32295. }
  32296. }
  32297. return ret;
  32298. };
  32299. /** @hidden */
  32300. Mesh.prototype._unBindEffect = function () {
  32301. _super.prototype._unBindEffect.call(this);
  32302. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32303. var instance = _a[_i];
  32304. instance._unBindEffect();
  32305. }
  32306. };
  32307. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32308. /**
  32309. * Gets a boolean indicating if this mesh has LOD
  32310. */
  32311. get: function () {
  32312. return this._LODLevels.length > 0;
  32313. },
  32314. enumerable: true,
  32315. configurable: true
  32316. });
  32317. /**
  32318. * Gets the list of MeshLODLevel associated with the current mesh
  32319. * @returns an array of MeshLODLevel
  32320. */
  32321. Mesh.prototype.getLODLevels = function () {
  32322. return this._LODLevels;
  32323. };
  32324. Mesh.prototype._sortLODLevels = function () {
  32325. this._LODLevels.sort(function (a, b) {
  32326. if (a.distance < b.distance) {
  32327. return 1;
  32328. }
  32329. if (a.distance > b.distance) {
  32330. return -1;
  32331. }
  32332. return 0;
  32333. });
  32334. };
  32335. /**
  32336. * Add a mesh as LOD level triggered at the given distance.
  32337. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32338. * @param distance The distance from the center of the object to show this level
  32339. * @param mesh The mesh to be added as LOD level (can be null)
  32340. * @return This mesh (for chaining)
  32341. */
  32342. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32343. if (mesh && mesh._masterMesh) {
  32344. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32345. return this;
  32346. }
  32347. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32348. this._LODLevels.push(level);
  32349. if (mesh) {
  32350. mesh._masterMesh = this;
  32351. }
  32352. this._sortLODLevels();
  32353. return this;
  32354. };
  32355. /**
  32356. * Returns the LOD level mesh at the passed distance or null if not found.
  32357. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32358. * @param distance The distance from the center of the object to show this level
  32359. * @returns a Mesh or `null`
  32360. */
  32361. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32362. for (var index = 0; index < this._LODLevels.length; index++) {
  32363. var level = this._LODLevels[index];
  32364. if (level.distance === distance) {
  32365. return level.mesh;
  32366. }
  32367. }
  32368. return null;
  32369. };
  32370. /**
  32371. * Remove a mesh from the LOD array
  32372. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32373. * @param mesh defines the mesh to be removed
  32374. * @return This mesh (for chaining)
  32375. */
  32376. Mesh.prototype.removeLODLevel = function (mesh) {
  32377. for (var index = 0; index < this._LODLevels.length; index++) {
  32378. if (this._LODLevels[index].mesh === mesh) {
  32379. this._LODLevels.splice(index, 1);
  32380. if (mesh) {
  32381. mesh._masterMesh = null;
  32382. }
  32383. }
  32384. }
  32385. this._sortLODLevels();
  32386. return this;
  32387. };
  32388. /**
  32389. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32390. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32391. * @param camera defines the camera to use to compute distance
  32392. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32393. * @return This mesh (for chaining)
  32394. */
  32395. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32396. if (!this._LODLevels || this._LODLevels.length === 0) {
  32397. return this;
  32398. }
  32399. var bSphere;
  32400. if (boundingSphere) {
  32401. bSphere = boundingSphere;
  32402. }
  32403. else {
  32404. var boundingInfo = this.getBoundingInfo();
  32405. bSphere = boundingInfo.boundingSphere;
  32406. }
  32407. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32408. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32409. if (this.onLODLevelSelection) {
  32410. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32411. }
  32412. return this;
  32413. }
  32414. for (var index = 0; index < this._LODLevels.length; index++) {
  32415. var level = this._LODLevels[index];
  32416. if (level.distance < distanceToCamera) {
  32417. if (level.mesh) {
  32418. level.mesh._preActivate();
  32419. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32420. }
  32421. if (this.onLODLevelSelection) {
  32422. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32423. }
  32424. return level.mesh;
  32425. }
  32426. }
  32427. if (this.onLODLevelSelection) {
  32428. this.onLODLevelSelection(distanceToCamera, this, this);
  32429. }
  32430. return this;
  32431. };
  32432. Object.defineProperty(Mesh.prototype, "geometry", {
  32433. /**
  32434. * Gets the mesh internal Geometry object
  32435. */
  32436. get: function () {
  32437. return this._geometry;
  32438. },
  32439. enumerable: true,
  32440. configurable: true
  32441. });
  32442. /**
  32443. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32444. * @returns the total number of vertices
  32445. */
  32446. Mesh.prototype.getTotalVertices = function () {
  32447. if (this._geometry === null || this._geometry === undefined) {
  32448. return 0;
  32449. }
  32450. return this._geometry.getTotalVertices();
  32451. };
  32452. /**
  32453. * Returns the content of an associated vertex buffer
  32454. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32455. * - BABYLON.VertexBuffer.PositionKind
  32456. * - BABYLON.VertexBuffer.UVKind
  32457. * - BABYLON.VertexBuffer.UV2Kind
  32458. * - BABYLON.VertexBuffer.UV3Kind
  32459. * - BABYLON.VertexBuffer.UV4Kind
  32460. * - BABYLON.VertexBuffer.UV5Kind
  32461. * - BABYLON.VertexBuffer.UV6Kind
  32462. * - BABYLON.VertexBuffer.ColorKind
  32463. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32464. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32465. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32466. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32467. * @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
  32468. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32469. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32470. */
  32471. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32472. if (!this._geometry) {
  32473. return null;
  32474. }
  32475. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32476. };
  32477. /**
  32478. * Returns the mesh VertexBuffer object from the requested `kind`
  32479. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32480. * - BABYLON.VertexBuffer.PositionKind
  32481. * - BABYLON.VertexBuffer.UVKind
  32482. * - BABYLON.VertexBuffer.UV2Kind
  32483. * - BABYLON.VertexBuffer.UV3Kind
  32484. * - BABYLON.VertexBuffer.UV4Kind
  32485. * - BABYLON.VertexBuffer.UV5Kind
  32486. * - BABYLON.VertexBuffer.UV6Kind
  32487. * - BABYLON.VertexBuffer.ColorKind
  32488. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32489. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32490. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32491. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32492. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32493. */
  32494. Mesh.prototype.getVertexBuffer = function (kind) {
  32495. if (!this._geometry) {
  32496. return null;
  32497. }
  32498. return this._geometry.getVertexBuffer(kind);
  32499. };
  32500. /**
  32501. * Tests if a specific vertex buffer is associated with this mesh
  32502. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32503. * - BABYLON.VertexBuffer.PositionKind
  32504. * - BABYLON.VertexBuffer.UVKind
  32505. * - BABYLON.VertexBuffer.UV2Kind
  32506. * - BABYLON.VertexBuffer.UV3Kind
  32507. * - BABYLON.VertexBuffer.UV4Kind
  32508. * - BABYLON.VertexBuffer.UV5Kind
  32509. * - BABYLON.VertexBuffer.UV6Kind
  32510. * - BABYLON.VertexBuffer.ColorKind
  32511. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32512. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32513. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32514. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32515. * @returns a boolean
  32516. */
  32517. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32518. if (!this._geometry) {
  32519. if (this._delayInfo) {
  32520. return this._delayInfo.indexOf(kind) !== -1;
  32521. }
  32522. return false;
  32523. }
  32524. return this._geometry.isVerticesDataPresent(kind);
  32525. };
  32526. /**
  32527. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32528. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32529. * - BABYLON.VertexBuffer.PositionKind
  32530. * - BABYLON.VertexBuffer.UVKind
  32531. * - BABYLON.VertexBuffer.UV2Kind
  32532. * - BABYLON.VertexBuffer.UV3Kind
  32533. * - BABYLON.VertexBuffer.UV4Kind
  32534. * - BABYLON.VertexBuffer.UV5Kind
  32535. * - BABYLON.VertexBuffer.UV6Kind
  32536. * - BABYLON.VertexBuffer.ColorKind
  32537. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32538. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32539. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32540. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32541. * @returns a boolean
  32542. */
  32543. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32544. if (!this._geometry) {
  32545. if (this._delayInfo) {
  32546. return this._delayInfo.indexOf(kind) !== -1;
  32547. }
  32548. return false;
  32549. }
  32550. return this._geometry.isVertexBufferUpdatable(kind);
  32551. };
  32552. /**
  32553. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32554. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32555. * - BABYLON.VertexBuffer.PositionKind
  32556. * - BABYLON.VertexBuffer.UVKind
  32557. * - BABYLON.VertexBuffer.UV2Kind
  32558. * - BABYLON.VertexBuffer.UV3Kind
  32559. * - BABYLON.VertexBuffer.UV4Kind
  32560. * - BABYLON.VertexBuffer.UV5Kind
  32561. * - BABYLON.VertexBuffer.UV6Kind
  32562. * - BABYLON.VertexBuffer.ColorKind
  32563. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32564. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32565. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32566. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32567. * @returns an array of strings
  32568. */
  32569. Mesh.prototype.getVerticesDataKinds = function () {
  32570. if (!this._geometry) {
  32571. var result = new Array();
  32572. if (this._delayInfo) {
  32573. this._delayInfo.forEach(function (kind, index, array) {
  32574. result.push(kind);
  32575. });
  32576. }
  32577. return result;
  32578. }
  32579. return this._geometry.getVerticesDataKinds();
  32580. };
  32581. /**
  32582. * Returns a positive integer : the total number of indices in this mesh geometry.
  32583. * @returns the numner of indices or zero if the mesh has no geometry.
  32584. */
  32585. Mesh.prototype.getTotalIndices = function () {
  32586. if (!this._geometry) {
  32587. return 0;
  32588. }
  32589. return this._geometry.getTotalIndices();
  32590. };
  32591. /**
  32592. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32593. * @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.
  32594. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32595. * @returns the indices array or an empty array if the mesh has no geometry
  32596. */
  32597. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32598. if (!this._geometry) {
  32599. return [];
  32600. }
  32601. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32602. };
  32603. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32604. get: function () {
  32605. return this._masterMesh !== null && this._masterMesh !== undefined;
  32606. },
  32607. enumerable: true,
  32608. configurable: true
  32609. });
  32610. /**
  32611. * Determine if the current mesh is ready to be rendered
  32612. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32613. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32614. * @returns true if all associated assets are ready (material, textures, shaders)
  32615. */
  32616. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32617. if (completeCheck === void 0) { completeCheck = false; }
  32618. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32619. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32620. return false;
  32621. }
  32622. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32623. return false;
  32624. }
  32625. if (!this.subMeshes || this.subMeshes.length === 0) {
  32626. return true;
  32627. }
  32628. if (!completeCheck) {
  32629. return true;
  32630. }
  32631. var engine = this.getEngine();
  32632. var scene = this.getScene();
  32633. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32634. this.computeWorldMatrix();
  32635. var mat = this.material || scene.defaultMaterial;
  32636. if (mat) {
  32637. if (mat.storeEffectOnSubMeshes) {
  32638. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32639. var subMesh = _a[_i];
  32640. var effectiveMaterial = subMesh.getMaterial();
  32641. if (effectiveMaterial) {
  32642. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32643. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32644. return false;
  32645. }
  32646. }
  32647. else {
  32648. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32649. return false;
  32650. }
  32651. }
  32652. }
  32653. }
  32654. }
  32655. else {
  32656. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32657. return false;
  32658. }
  32659. }
  32660. }
  32661. // Shadows
  32662. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32663. var light = _c[_b];
  32664. var generator = light.getShadowGenerator();
  32665. if (generator) {
  32666. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32667. var subMesh = _e[_d];
  32668. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32669. return false;
  32670. }
  32671. }
  32672. }
  32673. }
  32674. // LOD
  32675. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32676. var lod = _g[_f];
  32677. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32678. return false;
  32679. }
  32680. }
  32681. return true;
  32682. };
  32683. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32684. /**
  32685. * 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.
  32686. */
  32687. get: function () {
  32688. return this._areNormalsFrozen;
  32689. },
  32690. enumerable: true,
  32691. configurable: true
  32692. });
  32693. /**
  32694. * 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.
  32695. * @returns the current mesh
  32696. */
  32697. Mesh.prototype.freezeNormals = function () {
  32698. this._areNormalsFrozen = true;
  32699. return this;
  32700. };
  32701. /**
  32702. * 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
  32703. * @returns the current mesh
  32704. */
  32705. Mesh.prototype.unfreezeNormals = function () {
  32706. this._areNormalsFrozen = false;
  32707. return this;
  32708. };
  32709. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32710. /**
  32711. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32712. */
  32713. set: function (count) {
  32714. this._instanceDataStorage.overridenInstanceCount = count;
  32715. },
  32716. enumerable: true,
  32717. configurable: true
  32718. });
  32719. // Methods
  32720. /** @hidden */
  32721. Mesh.prototype._preActivate = function () {
  32722. var sceneRenderId = this.getScene().getRenderId();
  32723. if (this._preActivateId === sceneRenderId) {
  32724. return this;
  32725. }
  32726. this._preActivateId = sceneRenderId;
  32727. this._instanceDataStorage.visibleInstances = null;
  32728. return this;
  32729. };
  32730. /** @hidden */
  32731. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32732. if (this._instanceDataStorage.visibleInstances) {
  32733. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32734. }
  32735. return this;
  32736. };
  32737. /** @hidden */
  32738. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32739. if (!this._instanceDataStorage.visibleInstances) {
  32740. this._instanceDataStorage.visibleInstances = {};
  32741. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32742. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32743. }
  32744. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32745. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32746. }
  32747. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32748. return this;
  32749. };
  32750. /**
  32751. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32752. * This means the mesh underlying bounding box and sphere are recomputed.
  32753. * @returns the current mesh
  32754. */
  32755. Mesh.prototype.refreshBoundingInfo = function () {
  32756. return this._refreshBoundingInfo(false);
  32757. };
  32758. /** @hidden */
  32759. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32760. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32761. return this;
  32762. }
  32763. var data = this._getPositionData(applySkeleton);
  32764. if (data) {
  32765. var bias = this.geometry ? this.geometry.boundingBias : null;
  32766. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32767. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32768. }
  32769. if (this.subMeshes) {
  32770. for (var index = 0; index < this.subMeshes.length; index++) {
  32771. this.subMeshes[index].refreshBoundingInfo();
  32772. }
  32773. }
  32774. this._updateBoundingInfo();
  32775. return this;
  32776. };
  32777. Mesh.prototype._getPositionData = function (applySkeleton) {
  32778. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32779. if (data && applySkeleton && this.skeleton) {
  32780. data = BABYLON.Tools.Slice(data);
  32781. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32782. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32783. if (matricesWeightsData && matricesIndicesData) {
  32784. var needExtras = this.numBoneInfluencers > 4;
  32785. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32786. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32787. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32788. var tempVector = BABYLON.Tmp.Vector3[0];
  32789. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32790. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32791. var matWeightIdx = 0;
  32792. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32793. finalMatrix.reset();
  32794. var inf;
  32795. var weight;
  32796. for (inf = 0; inf < 4; inf++) {
  32797. weight = matricesWeightsData[matWeightIdx + inf];
  32798. if (weight > 0) {
  32799. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32800. finalMatrix.addToSelf(tempMatrix);
  32801. }
  32802. }
  32803. if (needExtras) {
  32804. for (inf = 0; inf < 4; inf++) {
  32805. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32806. if (weight > 0) {
  32807. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32808. finalMatrix.addToSelf(tempMatrix);
  32809. }
  32810. }
  32811. }
  32812. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32813. tempVector.toArray(data, index);
  32814. }
  32815. }
  32816. }
  32817. return data;
  32818. };
  32819. /** @hidden */
  32820. Mesh.prototype._createGlobalSubMesh = function (force) {
  32821. var totalVertices = this.getTotalVertices();
  32822. if (!totalVertices || !this.getIndices()) {
  32823. return null;
  32824. }
  32825. // Check if we need to recreate the submeshes
  32826. if (this.subMeshes && this.subMeshes.length > 0) {
  32827. var ib = this.getIndices();
  32828. if (!ib) {
  32829. return null;
  32830. }
  32831. var totalIndices = ib.length;
  32832. var needToRecreate = false;
  32833. if (force) {
  32834. needToRecreate = true;
  32835. }
  32836. else {
  32837. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32838. var submesh = _a[_i];
  32839. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32840. needToRecreate = true;
  32841. break;
  32842. }
  32843. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32844. needToRecreate = true;
  32845. break;
  32846. }
  32847. }
  32848. }
  32849. if (!needToRecreate) {
  32850. return this.subMeshes[0];
  32851. }
  32852. }
  32853. this.releaseSubMeshes();
  32854. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32855. };
  32856. /**
  32857. * This function will subdivide the mesh into multiple submeshes
  32858. * @param count defines the expected number of submeshes
  32859. */
  32860. Mesh.prototype.subdivide = function (count) {
  32861. if (count < 1) {
  32862. return;
  32863. }
  32864. var totalIndices = this.getTotalIndices();
  32865. var subdivisionSize = (totalIndices / count) | 0;
  32866. var offset = 0;
  32867. // Ensure that subdivisionSize is a multiple of 3
  32868. while (subdivisionSize % 3 !== 0) {
  32869. subdivisionSize++;
  32870. }
  32871. this.releaseSubMeshes();
  32872. for (var index = 0; index < count; index++) {
  32873. if (offset >= totalIndices) {
  32874. break;
  32875. }
  32876. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32877. offset += subdivisionSize;
  32878. }
  32879. this.synchronizeInstances();
  32880. };
  32881. /**
  32882. * Copy a FloatArray into a specific associated vertex buffer
  32883. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32884. * - BABYLON.VertexBuffer.PositionKind
  32885. * - BABYLON.VertexBuffer.UVKind
  32886. * - BABYLON.VertexBuffer.UV2Kind
  32887. * - BABYLON.VertexBuffer.UV3Kind
  32888. * - BABYLON.VertexBuffer.UV4Kind
  32889. * - BABYLON.VertexBuffer.UV5Kind
  32890. * - BABYLON.VertexBuffer.UV6Kind
  32891. * - BABYLON.VertexBuffer.ColorKind
  32892. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32893. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32894. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32895. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32896. * @param data defines the data source
  32897. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32898. * @param stride defines the data stride size (can be null)
  32899. * @returns the current mesh
  32900. */
  32901. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32902. if (updatable === void 0) { updatable = false; }
  32903. if (!this._geometry) {
  32904. var vertexData = new BABYLON.VertexData();
  32905. vertexData.set(data, kind);
  32906. var scene = this.getScene();
  32907. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32908. }
  32909. else {
  32910. this._geometry.setVerticesData(kind, data, updatable, stride);
  32911. }
  32912. return this;
  32913. };
  32914. /**
  32915. * Flags an associated vertex buffer as updatable
  32916. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32917. * - BABYLON.VertexBuffer.PositionKind
  32918. * - BABYLON.VertexBuffer.UVKind
  32919. * - BABYLON.VertexBuffer.UV2Kind
  32920. * - BABYLON.VertexBuffer.UV3Kind
  32921. * - BABYLON.VertexBuffer.UV4Kind
  32922. * - BABYLON.VertexBuffer.UV5Kind
  32923. * - BABYLON.VertexBuffer.UV6Kind
  32924. * - BABYLON.VertexBuffer.ColorKind
  32925. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32926. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32927. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32928. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32929. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32930. */
  32931. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32932. if (updatable === void 0) { updatable = true; }
  32933. var vb = this.getVertexBuffer(kind);
  32934. if (!vb || vb.isUpdatable() === updatable) {
  32935. return;
  32936. }
  32937. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32938. };
  32939. /**
  32940. * Sets the mesh global Vertex Buffer
  32941. * @param buffer defines the buffer to use
  32942. * @returns the current mesh
  32943. */
  32944. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32945. if (!this._geometry) {
  32946. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32947. }
  32948. this._geometry.setVerticesBuffer(buffer);
  32949. return this;
  32950. };
  32951. /**
  32952. * Update a specific associated vertex buffer
  32953. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32954. * - BABYLON.VertexBuffer.PositionKind
  32955. * - BABYLON.VertexBuffer.UVKind
  32956. * - BABYLON.VertexBuffer.UV2Kind
  32957. * - BABYLON.VertexBuffer.UV3Kind
  32958. * - BABYLON.VertexBuffer.UV4Kind
  32959. * - BABYLON.VertexBuffer.UV5Kind
  32960. * - BABYLON.VertexBuffer.UV6Kind
  32961. * - BABYLON.VertexBuffer.ColorKind
  32962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32966. * @param data defines the data source
  32967. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32968. * @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)
  32969. * @returns the current mesh
  32970. */
  32971. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32972. if (!this._geometry) {
  32973. return this;
  32974. }
  32975. if (!makeItUnique) {
  32976. this._geometry.updateVerticesData(kind, data, updateExtends);
  32977. }
  32978. else {
  32979. this.makeGeometryUnique();
  32980. this.updateVerticesData(kind, data, updateExtends, false);
  32981. }
  32982. return this;
  32983. };
  32984. /**
  32985. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32986. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32987. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  32988. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  32989. * @returns the current mesh
  32990. */
  32991. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32992. if (computeNormals === void 0) { computeNormals = true; }
  32993. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32994. if (!positions) {
  32995. return this;
  32996. }
  32997. positionFunction(positions);
  32998. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32999. if (computeNormals) {
  33000. var indices = this.getIndices();
  33001. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33002. if (!normals) {
  33003. return this;
  33004. }
  33005. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33006. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33007. }
  33008. return this;
  33009. };
  33010. /**
  33011. * Creates a un-shared specific occurence of the geometry for the mesh.
  33012. * @returns the current mesh
  33013. */
  33014. Mesh.prototype.makeGeometryUnique = function () {
  33015. if (!this._geometry) {
  33016. return this;
  33017. }
  33018. var oldGeometry = this._geometry;
  33019. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33020. oldGeometry.releaseForMesh(this, true);
  33021. geometry.applyToMesh(this);
  33022. return this;
  33023. };
  33024. /**
  33025. * Set the index buffer of this mesh
  33026. * @param indices defines the source data
  33027. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33028. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33029. * @returns the current mesh
  33030. */
  33031. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33032. if (totalVertices === void 0) { totalVertices = null; }
  33033. if (updatable === void 0) { updatable = false; }
  33034. if (!this._geometry) {
  33035. var vertexData = new BABYLON.VertexData();
  33036. vertexData.indices = indices;
  33037. var scene = this.getScene();
  33038. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33039. }
  33040. else {
  33041. this._geometry.setIndices(indices, totalVertices, updatable);
  33042. }
  33043. return this;
  33044. };
  33045. /**
  33046. * Update the current index buffer
  33047. * @param indices defines the source data
  33048. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33049. * @returns the current mesh
  33050. */
  33051. Mesh.prototype.updateIndices = function (indices, offset) {
  33052. if (!this._geometry) {
  33053. return this;
  33054. }
  33055. this._geometry.updateIndices(indices, offset);
  33056. return this;
  33057. };
  33058. /**
  33059. * Invert the geometry to move from a right handed system to a left handed one.
  33060. * @returns the current mesh
  33061. */
  33062. Mesh.prototype.toLeftHanded = function () {
  33063. if (!this._geometry) {
  33064. return this;
  33065. }
  33066. this._geometry.toLeftHanded();
  33067. return this;
  33068. };
  33069. /** @hidden */
  33070. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33071. if (!this._geometry) {
  33072. return this;
  33073. }
  33074. var engine = this.getScene().getEngine();
  33075. // Wireframe
  33076. var indexToBind;
  33077. if (this._unIndexed) {
  33078. indexToBind = null;
  33079. }
  33080. else {
  33081. switch (fillMode) {
  33082. case BABYLON.Material.PointFillMode:
  33083. indexToBind = null;
  33084. break;
  33085. case BABYLON.Material.WireFrameFillMode:
  33086. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33087. break;
  33088. default:
  33089. case BABYLON.Material.TriangleFillMode:
  33090. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33091. break;
  33092. }
  33093. }
  33094. // VBOs
  33095. this._geometry._bind(effect, indexToBind);
  33096. return this;
  33097. };
  33098. /** @hidden */
  33099. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33100. if (alternate === void 0) { alternate = false; }
  33101. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33102. return this;
  33103. }
  33104. if (this._onBeforeDrawObservable) {
  33105. this._onBeforeDrawObservable.notifyObservers(this);
  33106. }
  33107. var scene = this.getScene();
  33108. var engine = scene.getEngine();
  33109. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33110. // or triangles as points
  33111. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33112. }
  33113. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33114. // Triangles as wireframe
  33115. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33116. }
  33117. else {
  33118. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33119. }
  33120. if (scene._isAlternateRenderingEnabled && !alternate) {
  33121. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33122. if (!effect || !scene.activeCamera) {
  33123. return this;
  33124. }
  33125. scene._switchToAlternateCameraConfiguration(true);
  33126. this._effectiveMaterial.bindView(effect);
  33127. this._effectiveMaterial.bindViewProjection(effect);
  33128. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33129. this._draw(subMesh, fillMode, instancesCount, true);
  33130. engine.setViewport(scene.activeCamera.viewport);
  33131. scene._switchToAlternateCameraConfiguration(false);
  33132. this._effectiveMaterial.bindView(effect);
  33133. this._effectiveMaterial.bindViewProjection(effect);
  33134. }
  33135. return this;
  33136. };
  33137. /**
  33138. * Registers for this mesh a javascript function called just before the rendering process
  33139. * @param func defines the function to call before rendering this mesh
  33140. * @returns the current mesh
  33141. */
  33142. Mesh.prototype.registerBeforeRender = function (func) {
  33143. this.onBeforeRenderObservable.add(func);
  33144. return this;
  33145. };
  33146. /**
  33147. * Disposes a previously registered javascript function called before the rendering
  33148. * @param func defines the function to remove
  33149. * @returns the current mesh
  33150. */
  33151. Mesh.prototype.unregisterBeforeRender = function (func) {
  33152. this.onBeforeRenderObservable.removeCallback(func);
  33153. return this;
  33154. };
  33155. /**
  33156. * Registers for this mesh a javascript function called just after the rendering is complete
  33157. * @param func defines the function to call after rendering this mesh
  33158. * @returns the current mesh
  33159. */
  33160. Mesh.prototype.registerAfterRender = function (func) {
  33161. this.onAfterRenderObservable.add(func);
  33162. return this;
  33163. };
  33164. /**
  33165. * Disposes a previously registered javascript function called after the rendering.
  33166. * @param func defines the function to remove
  33167. * @returns the current mesh
  33168. */
  33169. Mesh.prototype.unregisterAfterRender = function (func) {
  33170. this.onAfterRenderObservable.removeCallback(func);
  33171. return this;
  33172. };
  33173. /** @hidden */
  33174. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33175. var scene = this.getScene();
  33176. var batchCache = this._instanceDataStorage.batchCache;
  33177. batchCache.mustReturn = false;
  33178. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33179. batchCache.visibleInstances[subMeshId] = null;
  33180. if (this._instanceDataStorage.visibleInstances) {
  33181. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33182. var currentRenderId = scene.getRenderId();
  33183. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33184. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33185. var selfRenderId = this._renderId;
  33186. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33187. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33188. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33189. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33190. }
  33191. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33192. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33193. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33194. batchCache.mustReturn = true;
  33195. return batchCache;
  33196. }
  33197. if (currentRenderId !== selfRenderId) {
  33198. batchCache.renderSelf[subMeshId] = false;
  33199. }
  33200. }
  33201. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33202. }
  33203. return batchCache;
  33204. };
  33205. /** @hidden */
  33206. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33207. var visibleInstances = batch.visibleInstances[subMesh._id];
  33208. if (!visibleInstances) {
  33209. return this;
  33210. }
  33211. var matricesCount = visibleInstances.length + 1;
  33212. var bufferSize = matricesCount * 16 * 4;
  33213. var instanceStorage = this._instanceDataStorage;
  33214. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33215. var instancesBuffer = instanceStorage.instancesBuffer;
  33216. while (instanceStorage.instancesBufferSize < bufferSize) {
  33217. instanceStorage.instancesBufferSize *= 2;
  33218. }
  33219. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33220. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33221. }
  33222. var offset = 0;
  33223. var instancesCount = 0;
  33224. var world = this.getWorldMatrix();
  33225. if (batch.renderSelf[subMesh._id]) {
  33226. world.copyToArray(instanceStorage.instancesData, offset);
  33227. offset += 16;
  33228. instancesCount++;
  33229. }
  33230. if (visibleInstances) {
  33231. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33232. var instance = visibleInstances[instanceIndex];
  33233. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33234. offset += 16;
  33235. instancesCount++;
  33236. }
  33237. }
  33238. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33239. if (instancesBuffer) {
  33240. instancesBuffer.dispose();
  33241. }
  33242. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33243. instanceStorage.instancesBuffer = instancesBuffer;
  33244. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33245. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33246. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33247. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33248. }
  33249. else {
  33250. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33251. }
  33252. this._bind(subMesh, effect, fillMode);
  33253. this._draw(subMesh, fillMode, instancesCount);
  33254. engine.unbindInstanceAttributes();
  33255. return this;
  33256. };
  33257. /** @hidden */
  33258. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33259. var scene = this.getScene();
  33260. var engine = scene.getEngine();
  33261. if (hardwareInstancedRendering) {
  33262. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33263. }
  33264. else {
  33265. if (batch.renderSelf[subMesh._id]) {
  33266. // Draw
  33267. if (onBeforeDraw) {
  33268. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33269. }
  33270. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33271. }
  33272. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33273. if (visibleInstancesForSubMesh) {
  33274. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33275. var instance = visibleInstancesForSubMesh[instanceIndex];
  33276. // World
  33277. var world = instance.getWorldMatrix();
  33278. if (onBeforeDraw) {
  33279. onBeforeDraw(true, world, effectiveMaterial);
  33280. }
  33281. // Draw
  33282. this._draw(subMesh, fillMode);
  33283. }
  33284. }
  33285. }
  33286. return this;
  33287. };
  33288. /**
  33289. * 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
  33290. * @param subMesh defines the subMesh to render
  33291. * @param enableAlphaMode defines if alpha mode can be changed
  33292. * @returns the current mesh
  33293. */
  33294. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33295. if (this._checkOcclusionQuery()) {
  33296. return this;
  33297. }
  33298. var scene = this.getScene();
  33299. // Managing instances
  33300. var batch = this._getInstancesRenderList(subMesh._id);
  33301. if (batch.mustReturn) {
  33302. return this;
  33303. }
  33304. // Checking geometry state
  33305. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33306. return this;
  33307. }
  33308. if (this._onBeforeRenderObservable) {
  33309. this._onBeforeRenderObservable.notifyObservers(this);
  33310. }
  33311. var engine = scene.getEngine();
  33312. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33313. // Material
  33314. var material = subMesh.getMaterial();
  33315. if (!material) {
  33316. return this;
  33317. }
  33318. this._effectiveMaterial = material;
  33319. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33320. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33321. return this;
  33322. }
  33323. }
  33324. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33325. return this;
  33326. }
  33327. // Alpha mode
  33328. if (enableAlphaMode) {
  33329. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33330. }
  33331. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33332. var step = _a[_i];
  33333. step.action(this, subMesh, batch);
  33334. }
  33335. var effect;
  33336. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33337. effect = subMesh.effect;
  33338. }
  33339. else {
  33340. effect = this._effectiveMaterial.getEffect();
  33341. }
  33342. if (!effect) {
  33343. return this;
  33344. }
  33345. var sideOrientation = this.overrideMaterialSideOrientation;
  33346. if (sideOrientation == null) {
  33347. sideOrientation = this._effectiveMaterial.sideOrientation;
  33348. if (this._getWorldMatrixDeterminant() < 0) {
  33349. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33350. }
  33351. }
  33352. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33353. if (this._effectiveMaterial.forceDepthWrite) {
  33354. engine.setDepthWrite(true);
  33355. }
  33356. // Bind
  33357. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33358. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33359. this._bind(subMesh, effect, fillMode);
  33360. }
  33361. var world = this.getWorldMatrix();
  33362. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33363. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33364. }
  33365. else {
  33366. this._effectiveMaterial.bind(world, this);
  33367. }
  33368. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33369. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33370. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33371. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33372. }
  33373. // Draw
  33374. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33375. // Unbind
  33376. this._effectiveMaterial.unbind();
  33377. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33378. var step = _c[_b];
  33379. step.action(this, subMesh, batch);
  33380. }
  33381. if (this._onAfterRenderObservable) {
  33382. this._onAfterRenderObservable.notifyObservers(this);
  33383. }
  33384. return this;
  33385. };
  33386. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33387. if (isInstance && effectiveMaterial) {
  33388. effectiveMaterial.bindOnlyWorldMatrix(world);
  33389. }
  33390. };
  33391. /**
  33392. * Renormalize the mesh and patch it up if there are no weights
  33393. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33394. * However in the case of zero weights then we set just a single influence to 1.
  33395. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33396. */
  33397. Mesh.prototype.cleanMatrixWeights = function () {
  33398. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33400. this.normalizeSkinWeightsAndExtra();
  33401. }
  33402. else {
  33403. this.normalizeSkinFourWeights();
  33404. }
  33405. }
  33406. };
  33407. // faster 4 weight version.
  33408. Mesh.prototype.normalizeSkinFourWeights = function () {
  33409. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33410. var numWeights = matricesWeights.length;
  33411. for (var a = 0; a < numWeights; a += 4) {
  33412. // accumulate weights
  33413. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33414. // check for invalid weight and just set it to 1.
  33415. if (t === 0)
  33416. matricesWeights[a] = 1;
  33417. else {
  33418. // renormalize so everything adds to 1 use reciprical
  33419. var recip = 1 / t;
  33420. matricesWeights[a] *= recip;
  33421. matricesWeights[a + 1] *= recip;
  33422. matricesWeights[a + 2] *= recip;
  33423. matricesWeights[a + 3] *= recip;
  33424. }
  33425. }
  33426. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33427. };
  33428. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33429. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33430. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33431. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33432. var numWeights = matricesWeights.length;
  33433. for (var a = 0; a < numWeights; a += 4) {
  33434. // accumulate weights
  33435. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33436. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33437. // check for invalid weight and just set it to 1.
  33438. if (t === 0)
  33439. matricesWeights[a] = 1;
  33440. else {
  33441. // renormalize so everything adds to 1 use reciprical
  33442. var recip = 1 / t;
  33443. matricesWeights[a] *= recip;
  33444. matricesWeights[a + 1] *= recip;
  33445. matricesWeights[a + 2] *= recip;
  33446. matricesWeights[a + 3] *= recip;
  33447. // same goes for extras
  33448. matricesWeightsExtra[a] *= recip;
  33449. matricesWeightsExtra[a + 1] *= recip;
  33450. matricesWeightsExtra[a + 2] *= recip;
  33451. matricesWeightsExtra[a + 3] *= recip;
  33452. }
  33453. }
  33454. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33455. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33456. };
  33457. /**
  33458. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33459. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33460. * the user know there was an issue with importing the mesh
  33461. * @returns a validation object with skinned, valid and report string
  33462. */
  33463. Mesh.prototype.validateSkinning = function () {
  33464. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33465. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33466. if (matricesWeights === null || this.skeleton == null) {
  33467. return { skinned: false, valid: true, report: "not skinned" };
  33468. }
  33469. var numWeights = matricesWeights.length;
  33470. var numberNotSorted = 0;
  33471. var missingWeights = 0;
  33472. var maxUsedWeights = 0;
  33473. var numberNotNormalized = 0;
  33474. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33475. var usedWeightCounts = new Array();
  33476. for (var a = 0; a <= numInfluences; a++) {
  33477. usedWeightCounts[a] = 0;
  33478. }
  33479. var toleranceEpsilon = 0.001;
  33480. for (var a = 0; a < numWeights; a += 4) {
  33481. var lastWeight = matricesWeights[a];
  33482. var t = lastWeight;
  33483. var usedWeights = t === 0 ? 0 : 1;
  33484. for (var b = 1; b < numInfluences; b++) {
  33485. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33486. if (d > lastWeight)
  33487. numberNotSorted++;
  33488. if (d !== 0)
  33489. usedWeights++;
  33490. t += d;
  33491. lastWeight = d;
  33492. }
  33493. // count the buffer weights usage
  33494. usedWeightCounts[usedWeights]++;
  33495. // max influences
  33496. if (usedWeights > maxUsedWeights)
  33497. maxUsedWeights = usedWeights;
  33498. // check for invalid weight and just set it to 1.
  33499. if (t === 0) {
  33500. missingWeights++;
  33501. }
  33502. else {
  33503. // renormalize so everything adds to 1 use reciprical
  33504. var recip = 1 / t;
  33505. var tolerance = 0;
  33506. for (b = 0; b < numInfluences; b++) {
  33507. if (b < 4)
  33508. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33509. else
  33510. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33511. }
  33512. // arbitary epsilon value for dicdating not normalized
  33513. if (tolerance > toleranceEpsilon)
  33514. numberNotNormalized++;
  33515. }
  33516. }
  33517. // validate bone indices are in range of the skeleton
  33518. var numBones = this.skeleton.bones.length;
  33519. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33520. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33521. var numBadBoneIndices = 0;
  33522. for (var a = 0; a < numWeights; a++) {
  33523. for (var b = 0; b < numInfluences; b++) {
  33524. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33525. if (index >= numBones || index < 0)
  33526. numBadBoneIndices++;
  33527. }
  33528. }
  33529. // log mesh stats
  33530. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33531. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33532. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33533. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33534. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33535. };
  33536. /** @hidden */
  33537. Mesh.prototype._checkDelayState = function () {
  33538. var scene = this.getScene();
  33539. if (this._geometry) {
  33540. this._geometry.load(scene);
  33541. }
  33542. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33543. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33544. this._queueLoad(scene);
  33545. }
  33546. return this;
  33547. };
  33548. Mesh.prototype._queueLoad = function (scene) {
  33549. var _this = this;
  33550. scene._addPendingData(this);
  33551. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33552. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33553. if (data instanceof ArrayBuffer) {
  33554. _this._delayLoadingFunction(data, _this);
  33555. }
  33556. else {
  33557. _this._delayLoadingFunction(JSON.parse(data), _this);
  33558. }
  33559. _this.instances.forEach(function (instance) {
  33560. instance._syncSubMeshes();
  33561. });
  33562. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33563. scene._removePendingData(_this);
  33564. }, function () { }, scene.database, getBinaryData);
  33565. return this;
  33566. };
  33567. /**
  33568. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33569. * A mesh is in the frustum if its bounding box intersects the frustum
  33570. * @param frustumPlanes defines the frustum to test
  33571. * @returns true if the mesh is in the frustum planes
  33572. */
  33573. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33574. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33575. return false;
  33576. }
  33577. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33578. return false;
  33579. }
  33580. this._checkDelayState();
  33581. return true;
  33582. };
  33583. /**
  33584. * Sets the mesh material by the material or multiMaterial `id` property
  33585. * @param id is a string identifying the material or the multiMaterial
  33586. * @returns the current mesh
  33587. */
  33588. Mesh.prototype.setMaterialByID = function (id) {
  33589. var materials = this.getScene().materials;
  33590. var index;
  33591. for (index = materials.length - 1; index > -1; index--) {
  33592. if (materials[index].id === id) {
  33593. this.material = materials[index];
  33594. return this;
  33595. }
  33596. }
  33597. // Multi
  33598. var multiMaterials = this.getScene().multiMaterials;
  33599. for (index = multiMaterials.length - 1; index > -1; index--) {
  33600. if (multiMaterials[index].id === id) {
  33601. this.material = multiMaterials[index];
  33602. return this;
  33603. }
  33604. }
  33605. return this;
  33606. };
  33607. /**
  33608. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33609. * @returns an array of IAnimatable
  33610. */
  33611. Mesh.prototype.getAnimatables = function () {
  33612. var results = new Array();
  33613. if (this.material) {
  33614. results.push(this.material);
  33615. }
  33616. if (this.skeleton) {
  33617. results.push(this.skeleton);
  33618. }
  33619. return results;
  33620. };
  33621. /**
  33622. * Modifies the mesh geometry according to the passed transformation matrix.
  33623. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33624. * The mesh normals are modified using the same transformation.
  33625. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33626. * @param transform defines the transform matrix to use
  33627. * @see http://doc.babylonjs.com/resources/baking_transformations
  33628. * @returns the current mesh
  33629. */
  33630. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33631. // Position
  33632. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33633. return this;
  33634. }
  33635. var submeshes = this.subMeshes.splice(0);
  33636. this._resetPointsArrayCache();
  33637. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33638. var temp = new Array();
  33639. var index;
  33640. for (index = 0; index < data.length; index += 3) {
  33641. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33642. }
  33643. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33644. // Normals
  33645. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33646. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33647. temp = [];
  33648. for (index = 0; index < data.length; index += 3) {
  33649. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33650. }
  33651. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33652. }
  33653. // flip faces?
  33654. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33655. this.flipFaces();
  33656. }
  33657. // Restore submeshes
  33658. this.releaseSubMeshes();
  33659. this.subMeshes = submeshes;
  33660. return this;
  33661. };
  33662. /**
  33663. * Modifies the mesh geometry according to its own current World Matrix.
  33664. * The mesh World Matrix is then reset.
  33665. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33666. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33667. * @see http://doc.babylonjs.com/resources/baking_transformations
  33668. * @returns the current mesh
  33669. */
  33670. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33671. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33672. this.scaling.copyFromFloats(1, 1, 1);
  33673. this.position.copyFromFloats(0, 0, 0);
  33674. this.rotation.copyFromFloats(0, 0, 0);
  33675. //only if quaternion is already set
  33676. if (this.rotationQuaternion) {
  33677. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33678. }
  33679. this._worldMatrix = BABYLON.Matrix.Identity();
  33680. return this;
  33681. };
  33682. Object.defineProperty(Mesh.prototype, "_positions", {
  33683. // Cache
  33684. /** @hidden */
  33685. get: function () {
  33686. if (this._geometry) {
  33687. return this._geometry._positions;
  33688. }
  33689. return null;
  33690. },
  33691. enumerable: true,
  33692. configurable: true
  33693. });
  33694. /** @hidden */
  33695. Mesh.prototype._resetPointsArrayCache = function () {
  33696. if (this._geometry) {
  33697. this._geometry._resetPointsArrayCache();
  33698. }
  33699. return this;
  33700. };
  33701. /** @hidden */
  33702. Mesh.prototype._generatePointsArray = function () {
  33703. if (this._geometry) {
  33704. return this._geometry._generatePointsArray();
  33705. }
  33706. return false;
  33707. };
  33708. /**
  33709. * Returns a new Mesh object generated from the current mesh properties.
  33710. * This method must not get confused with createInstance()
  33711. * @param name is a string, the name given to the new mesh
  33712. * @param newParent can be any Node object (default `null`)
  33713. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33714. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33715. * @returns a new mesh
  33716. */
  33717. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33718. if (name === void 0) { name = ""; }
  33719. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33720. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33721. };
  33722. /**
  33723. * Releases resources associated with this mesh.
  33724. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33725. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33726. */
  33727. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33728. var _this = this;
  33729. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33730. this.morphTargetManager = null;
  33731. if (this._geometry) {
  33732. this._geometry.releaseForMesh(this, true);
  33733. }
  33734. if (this._onBeforeDrawObservable) {
  33735. this._onBeforeDrawObservable.clear();
  33736. }
  33737. if (this._onBeforeRenderObservable) {
  33738. this._onBeforeRenderObservable.clear();
  33739. }
  33740. if (this._onAfterRenderObservable) {
  33741. this._onAfterRenderObservable.clear();
  33742. }
  33743. // Sources
  33744. var meshes = this.getScene().meshes;
  33745. meshes.forEach(function (abstractMesh) {
  33746. var mesh = abstractMesh;
  33747. if (mesh._source && mesh._source === _this) {
  33748. mesh._source = null;
  33749. }
  33750. });
  33751. this._source = null;
  33752. // Instances
  33753. if (this._instanceDataStorage.instancesBuffer) {
  33754. this._instanceDataStorage.instancesBuffer.dispose();
  33755. this._instanceDataStorage.instancesBuffer = null;
  33756. }
  33757. while (this.instances.length) {
  33758. this.instances[0].dispose();
  33759. }
  33760. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33761. };
  33762. /**
  33763. * Modifies the mesh geometry according to a displacement map.
  33764. * 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.
  33765. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33766. * @param url is a string, the URL from the image file is to be downloaded.
  33767. * @param minHeight is the lower limit of the displacement.
  33768. * @param maxHeight is the upper limit of the displacement.
  33769. * @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.
  33770. * @param uvOffset is an optional vector2 used to offset UV.
  33771. * @param uvScale is an optional vector2 used to scale UV.
  33772. * @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.
  33773. * @returns the Mesh.
  33774. */
  33775. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33776. var _this = this;
  33777. if (forceUpdate === void 0) { forceUpdate = false; }
  33778. var scene = this.getScene();
  33779. var onload = function (img) {
  33780. // Getting height map data
  33781. var canvas = document.createElement("canvas");
  33782. var context = canvas.getContext("2d");
  33783. var heightMapWidth = img.width;
  33784. var heightMapHeight = img.height;
  33785. canvas.width = heightMapWidth;
  33786. canvas.height = heightMapHeight;
  33787. context.drawImage(img, 0, 0);
  33788. // Create VertexData from map data
  33789. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33790. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33791. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33792. //execute success callback, if set
  33793. if (onSuccess) {
  33794. onSuccess(_this);
  33795. }
  33796. };
  33797. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33798. return this;
  33799. };
  33800. /**
  33801. * Modifies the mesh geometry according to a displacementMap buffer.
  33802. * 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.
  33803. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33804. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33805. * @param heightMapWidth is the width of the buffer image.
  33806. * @param heightMapHeight is the height of the buffer image.
  33807. * @param minHeight is the lower limit of the displacement.
  33808. * @param maxHeight is the upper limit of the displacement.
  33809. * @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.
  33810. * @param uvOffset is an optional vector2 used to offset UV.
  33811. * @param uvScale is an optional vector2 used to scale UV.
  33812. * @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.
  33813. * @returns the Mesh.
  33814. */
  33815. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33816. if (forceUpdate === void 0) { forceUpdate = false; }
  33817. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33818. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33819. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33820. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33821. return this;
  33822. }
  33823. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33824. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33825. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33826. var position = BABYLON.Vector3.Zero();
  33827. var normal = BABYLON.Vector3.Zero();
  33828. var uv = BABYLON.Vector2.Zero();
  33829. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33830. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33831. for (var index = 0; index < positions.length; index += 3) {
  33832. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33833. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33834. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33835. // Compute height
  33836. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33837. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33838. var pos = (u + v * heightMapWidth) * 4;
  33839. var r = buffer[pos] / 255.0;
  33840. var g = buffer[pos + 1] / 255.0;
  33841. var b = buffer[pos + 2] / 255.0;
  33842. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33843. normal.normalize();
  33844. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33845. position = position.add(normal);
  33846. position.toArray(positions, index);
  33847. }
  33848. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33849. if (forceUpdate) {
  33850. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33851. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33852. }
  33853. else {
  33854. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33855. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33856. }
  33857. return this;
  33858. };
  33859. /**
  33860. * Modify the mesh to get a flat shading rendering.
  33861. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33862. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33863. * @returns current mesh
  33864. */
  33865. Mesh.prototype.convertToFlatShadedMesh = function () {
  33866. var kinds = this.getVerticesDataKinds();
  33867. var vbs = {};
  33868. var data = {};
  33869. var newdata = {};
  33870. var updatableNormals = false;
  33871. var kindIndex;
  33872. var kind;
  33873. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33874. kind = kinds[kindIndex];
  33875. var vertexBuffer = this.getVertexBuffer(kind);
  33876. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33877. updatableNormals = vertexBuffer.isUpdatable();
  33878. kinds.splice(kindIndex, 1);
  33879. kindIndex--;
  33880. continue;
  33881. }
  33882. vbs[kind] = vertexBuffer;
  33883. data[kind] = vbs[kind].getData();
  33884. newdata[kind] = [];
  33885. }
  33886. // Save previous submeshes
  33887. var previousSubmeshes = this.subMeshes.slice(0);
  33888. var indices = this.getIndices();
  33889. var totalIndices = this.getTotalIndices();
  33890. // Generating unique vertices per face
  33891. var index;
  33892. for (index = 0; index < totalIndices; index++) {
  33893. var vertexIndex = indices[index];
  33894. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33895. kind = kinds[kindIndex];
  33896. var stride = vbs[kind].getStrideSize();
  33897. for (var offset = 0; offset < stride; offset++) {
  33898. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33899. }
  33900. }
  33901. }
  33902. // Updating faces & normal
  33903. var normals = [];
  33904. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33905. for (index = 0; index < totalIndices; index += 3) {
  33906. indices[index] = index;
  33907. indices[index + 1] = index + 1;
  33908. indices[index + 2] = index + 2;
  33909. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33910. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33911. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33912. var p1p2 = p1.subtract(p2);
  33913. var p3p2 = p3.subtract(p2);
  33914. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33915. // Store same normals for every vertex
  33916. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33917. normals.push(normal.x);
  33918. normals.push(normal.y);
  33919. normals.push(normal.z);
  33920. }
  33921. }
  33922. this.setIndices(indices);
  33923. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33924. // Updating vertex buffers
  33925. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33926. kind = kinds[kindIndex];
  33927. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33928. }
  33929. // Updating submeshes
  33930. this.releaseSubMeshes();
  33931. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33932. var previousOne = previousSubmeshes[submeshIndex];
  33933. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33934. }
  33935. this.synchronizeInstances();
  33936. return this;
  33937. };
  33938. /**
  33939. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33940. * In other words, more vertices, no more indices and a single bigger VBO.
  33941. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33942. * @returns current mesh
  33943. */
  33944. Mesh.prototype.convertToUnIndexedMesh = function () {
  33945. var kinds = this.getVerticesDataKinds();
  33946. var vbs = {};
  33947. var data = {};
  33948. var newdata = {};
  33949. var kindIndex;
  33950. var kind;
  33951. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33952. kind = kinds[kindIndex];
  33953. var vertexBuffer = this.getVertexBuffer(kind);
  33954. vbs[kind] = vertexBuffer;
  33955. data[kind] = vbs[kind].getData();
  33956. newdata[kind] = [];
  33957. }
  33958. // Save previous submeshes
  33959. var previousSubmeshes = this.subMeshes.slice(0);
  33960. var indices = this.getIndices();
  33961. var totalIndices = this.getTotalIndices();
  33962. // Generating unique vertices per face
  33963. var index;
  33964. for (index = 0; index < totalIndices; index++) {
  33965. var vertexIndex = indices[index];
  33966. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33967. kind = kinds[kindIndex];
  33968. var stride = vbs[kind].getStrideSize();
  33969. for (var offset = 0; offset < stride; offset++) {
  33970. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33971. }
  33972. }
  33973. }
  33974. // Updating indices
  33975. for (index = 0; index < totalIndices; index += 3) {
  33976. indices[index] = index;
  33977. indices[index + 1] = index + 1;
  33978. indices[index + 2] = index + 2;
  33979. }
  33980. this.setIndices(indices);
  33981. // Updating vertex buffers
  33982. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33983. kind = kinds[kindIndex];
  33984. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33985. }
  33986. // Updating submeshes
  33987. this.releaseSubMeshes();
  33988. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33989. var previousOne = previousSubmeshes[submeshIndex];
  33990. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33991. }
  33992. this._unIndexed = true;
  33993. this.synchronizeInstances();
  33994. return this;
  33995. };
  33996. /**
  33997. * Inverses facet orientations.
  33998. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33999. * @param flipNormals will also inverts the normals
  34000. * @returns current mesh
  34001. */
  34002. Mesh.prototype.flipFaces = function (flipNormals) {
  34003. if (flipNormals === void 0) { flipNormals = false; }
  34004. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34005. var i;
  34006. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34007. for (i = 0; i < vertex_data.normals.length; i++) {
  34008. vertex_data.normals[i] *= -1;
  34009. }
  34010. }
  34011. if (vertex_data.indices) {
  34012. var temp;
  34013. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34014. // reassign indices
  34015. temp = vertex_data.indices[i + 1];
  34016. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34017. vertex_data.indices[i + 2] = temp;
  34018. }
  34019. }
  34020. vertex_data.applyToMesh(this);
  34021. return this;
  34022. };
  34023. // Instances
  34024. /**
  34025. * Creates a new InstancedMesh object from the mesh model.
  34026. * Warning : this method is not supported for Line mesh and LineSystem
  34027. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34028. * @param name defines the name of the new instance
  34029. * @returns a new InstancedMesh
  34030. */
  34031. Mesh.prototype.createInstance = function (name) {
  34032. return new BABYLON.InstancedMesh(name, this);
  34033. };
  34034. /**
  34035. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34036. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34037. * @returns the current mesh
  34038. */
  34039. Mesh.prototype.synchronizeInstances = function () {
  34040. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34041. var instance = this.instances[instanceIndex];
  34042. instance._syncSubMeshes();
  34043. }
  34044. return this;
  34045. };
  34046. /**
  34047. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34048. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34049. * This should be used together with the simplification to avoid disappearing triangles.
  34050. * @param successCallback an optional success callback to be called after the optimization finished.
  34051. * @returns the current mesh
  34052. */
  34053. Mesh.prototype.optimizeIndices = function (successCallback) {
  34054. var _this = this;
  34055. var indices = this.getIndices();
  34056. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34057. if (!positions || !indices) {
  34058. return this;
  34059. }
  34060. var vectorPositions = new Array();
  34061. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34062. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34063. }
  34064. var dupes = new Array();
  34065. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34066. var realPos = vectorPositions.length - 1 - iteration;
  34067. var testedPosition = vectorPositions[realPos];
  34068. for (var j = 0; j < realPos; ++j) {
  34069. var againstPosition = vectorPositions[j];
  34070. if (testedPosition.equals(againstPosition)) {
  34071. dupes[realPos] = j;
  34072. break;
  34073. }
  34074. }
  34075. }, function () {
  34076. for (var i = 0; i < indices.length; ++i) {
  34077. indices[i] = dupes[indices[i]] || indices[i];
  34078. }
  34079. //indices are now reordered
  34080. var originalSubMeshes = _this.subMeshes.slice(0);
  34081. _this.setIndices(indices);
  34082. _this.subMeshes = originalSubMeshes;
  34083. if (successCallback) {
  34084. successCallback(_this);
  34085. }
  34086. });
  34087. return this;
  34088. };
  34089. /**
  34090. * Serialize current mesh
  34091. * @param serializationObject defines the object which will receive the serialization data
  34092. */
  34093. Mesh.prototype.serialize = function (serializationObject) {
  34094. serializationObject.name = this.name;
  34095. serializationObject.id = this.id;
  34096. serializationObject.type = this.getClassName();
  34097. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34098. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34099. }
  34100. serializationObject.position = this.position.asArray();
  34101. if (this.rotationQuaternion) {
  34102. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34103. }
  34104. else if (this.rotation) {
  34105. serializationObject.rotation = this.rotation.asArray();
  34106. }
  34107. serializationObject.scaling = this.scaling.asArray();
  34108. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34109. serializationObject.isEnabled = this.isEnabled(false);
  34110. serializationObject.isVisible = this.isVisible;
  34111. serializationObject.infiniteDistance = this.infiniteDistance;
  34112. serializationObject.pickable = this.isPickable;
  34113. serializationObject.receiveShadows = this.receiveShadows;
  34114. serializationObject.billboardMode = this.billboardMode;
  34115. serializationObject.visibility = this.visibility;
  34116. serializationObject.checkCollisions = this.checkCollisions;
  34117. serializationObject.isBlocker = this.isBlocker;
  34118. // Parent
  34119. if (this.parent) {
  34120. serializationObject.parentId = this.parent.id;
  34121. }
  34122. // Geometry
  34123. serializationObject.isUnIndexed = this.isUnIndexed;
  34124. var geometry = this._geometry;
  34125. if (geometry) {
  34126. var geometryId = geometry.id;
  34127. serializationObject.geometryId = geometryId;
  34128. // SubMeshes
  34129. serializationObject.subMeshes = [];
  34130. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34131. var subMesh = this.subMeshes[subIndex];
  34132. serializationObject.subMeshes.push({
  34133. materialIndex: subMesh.materialIndex,
  34134. verticesStart: subMesh.verticesStart,
  34135. verticesCount: subMesh.verticesCount,
  34136. indexStart: subMesh.indexStart,
  34137. indexCount: subMesh.indexCount
  34138. });
  34139. }
  34140. }
  34141. // Material
  34142. if (this.material) {
  34143. serializationObject.materialId = this.material.id;
  34144. }
  34145. else {
  34146. this.material = null;
  34147. }
  34148. // Morph targets
  34149. if (this.morphTargetManager) {
  34150. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34151. }
  34152. // Skeleton
  34153. if (this.skeleton) {
  34154. serializationObject.skeletonId = this.skeleton.id;
  34155. }
  34156. // Physics
  34157. //TODO implement correct serialization for physics impostors.
  34158. var impostor = this.getPhysicsImpostor();
  34159. if (impostor) {
  34160. serializationObject.physicsMass = impostor.getParam("mass");
  34161. serializationObject.physicsFriction = impostor.getParam("friction");
  34162. serializationObject.physicsRestitution = impostor.getParam("mass");
  34163. serializationObject.physicsImpostor = impostor.type;
  34164. }
  34165. // Metadata
  34166. if (this.metadata) {
  34167. serializationObject.metadata = this.metadata;
  34168. }
  34169. // Instances
  34170. serializationObject.instances = [];
  34171. for (var index = 0; index < this.instances.length; index++) {
  34172. var instance = this.instances[index];
  34173. if (instance.doNotSerialize) {
  34174. continue;
  34175. }
  34176. var serializationInstance = {
  34177. name: instance.name,
  34178. id: instance.id,
  34179. position: instance.position.asArray(),
  34180. scaling: instance.scaling.asArray()
  34181. };
  34182. if (instance.parent) {
  34183. serializationInstance.parentId = instance.parent.id;
  34184. }
  34185. if (instance.rotationQuaternion) {
  34186. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34187. }
  34188. else if (instance.rotation) {
  34189. serializationInstance.rotation = instance.rotation.asArray();
  34190. }
  34191. serializationObject.instances.push(serializationInstance);
  34192. // Animations
  34193. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34194. serializationInstance.ranges = instance.serializeAnimationRanges();
  34195. }
  34196. //
  34197. // Animations
  34198. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34199. serializationObject.ranges = this.serializeAnimationRanges();
  34200. // Layer mask
  34201. serializationObject.layerMask = this.layerMask;
  34202. // Alpha
  34203. serializationObject.alphaIndex = this.alphaIndex;
  34204. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34205. // Overlay
  34206. serializationObject.overlayAlpha = this.overlayAlpha;
  34207. serializationObject.overlayColor = this.overlayColor.asArray();
  34208. serializationObject.renderOverlay = this.renderOverlay;
  34209. // Fog
  34210. serializationObject.applyFog = this.applyFog;
  34211. // Action Manager
  34212. if (this.actionManager) {
  34213. serializationObject.actions = this.actionManager.serialize(this.name);
  34214. }
  34215. };
  34216. /** @hidden */
  34217. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34218. if (!this.geometry) {
  34219. return;
  34220. }
  34221. this._markSubMeshesAsAttributesDirty();
  34222. var morphTargetManager = this._morphTargetManager;
  34223. if (morphTargetManager && morphTargetManager.vertexCount) {
  34224. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34225. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34226. this.morphTargetManager = null;
  34227. return;
  34228. }
  34229. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34230. var morphTarget = morphTargetManager.getActiveTarget(index);
  34231. var positions = morphTarget.getPositions();
  34232. if (!positions) {
  34233. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34234. return;
  34235. }
  34236. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34237. var normals = morphTarget.getNormals();
  34238. if (normals) {
  34239. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34240. }
  34241. var tangents = morphTarget.getTangents();
  34242. if (tangents) {
  34243. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34244. }
  34245. }
  34246. }
  34247. else {
  34248. var index = 0;
  34249. // Positions
  34250. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34251. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34252. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34253. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34254. }
  34255. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34256. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34257. }
  34258. index++;
  34259. }
  34260. }
  34261. };
  34262. // Statics
  34263. /**
  34264. * Returns a new Mesh object parsed from the source provided.
  34265. * @param parsedMesh is the source
  34266. * @param scene defines the hosting scene
  34267. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34268. * @returns a new Mesh
  34269. */
  34270. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34271. var mesh;
  34272. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34273. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34274. }
  34275. else {
  34276. mesh = new Mesh(parsedMesh.name, scene);
  34277. }
  34278. mesh.id = parsedMesh.id;
  34279. if (BABYLON.Tags) {
  34280. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34281. }
  34282. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34283. if (parsedMesh.metadata !== undefined) {
  34284. mesh.metadata = parsedMesh.metadata;
  34285. }
  34286. if (parsedMesh.rotationQuaternion) {
  34287. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34288. }
  34289. else if (parsedMesh.rotation) {
  34290. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34291. }
  34292. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34293. if (parsedMesh.localMatrix) {
  34294. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34295. }
  34296. else if (parsedMesh.pivotMatrix) {
  34297. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34298. }
  34299. mesh.setEnabled(parsedMesh.isEnabled);
  34300. mesh.isVisible = parsedMesh.isVisible;
  34301. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34302. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34303. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34304. if (parsedMesh.applyFog !== undefined) {
  34305. mesh.applyFog = parsedMesh.applyFog;
  34306. }
  34307. if (parsedMesh.pickable !== undefined) {
  34308. mesh.isPickable = parsedMesh.pickable;
  34309. }
  34310. if (parsedMesh.alphaIndex !== undefined) {
  34311. mesh.alphaIndex = parsedMesh.alphaIndex;
  34312. }
  34313. mesh.receiveShadows = parsedMesh.receiveShadows;
  34314. mesh.billboardMode = parsedMesh.billboardMode;
  34315. if (parsedMesh.visibility !== undefined) {
  34316. mesh.visibility = parsedMesh.visibility;
  34317. }
  34318. mesh.checkCollisions = parsedMesh.checkCollisions;
  34319. if (parsedMesh.isBlocker !== undefined) {
  34320. mesh.isBlocker = parsedMesh.isBlocker;
  34321. }
  34322. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34323. // freezeWorldMatrix
  34324. if (parsedMesh.freezeWorldMatrix) {
  34325. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34326. }
  34327. // Parent
  34328. if (parsedMesh.parentId) {
  34329. mesh._waitingParentId = parsedMesh.parentId;
  34330. }
  34331. // Actions
  34332. if (parsedMesh.actions !== undefined) {
  34333. mesh._waitingActions = parsedMesh.actions;
  34334. }
  34335. // Overlay
  34336. if (parsedMesh.overlayAlpha !== undefined) {
  34337. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34338. }
  34339. if (parsedMesh.overlayColor !== undefined) {
  34340. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34341. }
  34342. if (parsedMesh.renderOverlay !== undefined) {
  34343. mesh.renderOverlay = parsedMesh.renderOverlay;
  34344. }
  34345. // Geometry
  34346. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34347. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34348. if (parsedMesh.delayLoadingFile) {
  34349. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34350. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34351. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34352. if (parsedMesh._binaryInfo) {
  34353. mesh._binaryInfo = parsedMesh._binaryInfo;
  34354. }
  34355. mesh._delayInfo = [];
  34356. if (parsedMesh.hasUVs) {
  34357. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34358. }
  34359. if (parsedMesh.hasUVs2) {
  34360. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34361. }
  34362. if (parsedMesh.hasUVs3) {
  34363. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34364. }
  34365. if (parsedMesh.hasUVs4) {
  34366. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34367. }
  34368. if (parsedMesh.hasUVs5) {
  34369. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34370. }
  34371. if (parsedMesh.hasUVs6) {
  34372. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34373. }
  34374. if (parsedMesh.hasColors) {
  34375. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34376. }
  34377. if (parsedMesh.hasMatricesIndices) {
  34378. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34379. }
  34380. if (parsedMesh.hasMatricesWeights) {
  34381. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34382. }
  34383. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34384. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34385. mesh._checkDelayState();
  34386. }
  34387. }
  34388. else {
  34389. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34390. }
  34391. // Material
  34392. if (parsedMesh.materialId) {
  34393. mesh.setMaterialByID(parsedMesh.materialId);
  34394. }
  34395. else {
  34396. mesh.material = null;
  34397. }
  34398. // Morph targets
  34399. if (parsedMesh.morphTargetManagerId > -1) {
  34400. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34401. }
  34402. // Skeleton
  34403. if (parsedMesh.skeletonId > -1) {
  34404. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34405. if (parsedMesh.numBoneInfluencers) {
  34406. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34407. }
  34408. }
  34409. // Animations
  34410. if (parsedMesh.animations) {
  34411. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34412. var parsedAnimation = parsedMesh.animations[animationIndex];
  34413. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34414. }
  34415. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34416. }
  34417. if (parsedMesh.autoAnimate) {
  34418. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34419. }
  34420. // Layer Mask
  34421. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34422. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34423. }
  34424. else {
  34425. mesh.layerMask = 0x0FFFFFFF;
  34426. }
  34427. // Physics
  34428. if (parsedMesh.physicsImpostor) {
  34429. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34430. mass: parsedMesh.physicsMass,
  34431. friction: parsedMesh.physicsFriction,
  34432. restitution: parsedMesh.physicsRestitution
  34433. }, scene);
  34434. }
  34435. // Instances
  34436. if (parsedMesh.instances) {
  34437. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34438. var parsedInstance = parsedMesh.instances[index];
  34439. var instance = mesh.createInstance(parsedInstance.name);
  34440. if (parsedInstance.id) {
  34441. instance.id = parsedInstance.id;
  34442. }
  34443. if (BABYLON.Tags) {
  34444. if (parsedInstance.tags) {
  34445. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34446. }
  34447. else {
  34448. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34449. }
  34450. }
  34451. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34452. if (parsedInstance.parentId) {
  34453. instance._waitingParentId = parsedInstance.parentId;
  34454. }
  34455. if (parsedInstance.rotationQuaternion) {
  34456. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34457. }
  34458. else if (parsedInstance.rotation) {
  34459. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34460. }
  34461. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34462. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34463. instance.checkCollisions = parsedInstance.checkCollisions;
  34464. }
  34465. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34466. instance.isPickable = parsedInstance.pickable;
  34467. }
  34468. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34469. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34470. }
  34471. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34472. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34473. }
  34474. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34475. instance.alphaIndex = parsedInstance.alphaIndex;
  34476. }
  34477. // Physics
  34478. if (parsedInstance.physicsImpostor) {
  34479. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34480. mass: parsedInstance.physicsMass,
  34481. friction: parsedInstance.physicsFriction,
  34482. restitution: parsedInstance.physicsRestitution
  34483. }, scene);
  34484. }
  34485. // Animation
  34486. if (parsedInstance.animations) {
  34487. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34488. parsedAnimation = parsedInstance.animations[animationIndex];
  34489. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34490. }
  34491. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34492. if (parsedInstance.autoAnimate) {
  34493. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34494. }
  34495. }
  34496. }
  34497. }
  34498. return mesh;
  34499. };
  34500. /**
  34501. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34502. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34503. * @param name defines the name of the mesh to create
  34504. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34505. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34506. * @param closePath creates a seam between the first and the last points of each path of the path array
  34507. * @param offset is taken in account only if the `pathArray` is containing a single path
  34508. * @param scene defines the hosting scene
  34509. * @param updatable defines if the mesh must be flagged as updatable
  34510. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34511. * @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)
  34512. * @returns a new Mesh
  34513. */
  34514. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34515. if (closeArray === void 0) { closeArray = false; }
  34516. if (updatable === void 0) { updatable = false; }
  34517. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34518. pathArray: pathArray,
  34519. closeArray: closeArray,
  34520. closePath: closePath,
  34521. offset: offset,
  34522. updatable: updatable,
  34523. sideOrientation: sideOrientation,
  34524. instance: instance
  34525. }, scene);
  34526. };
  34527. /**
  34528. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34529. * @param name defines the name of the mesh to create
  34530. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34531. * @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
  34532. * @param scene defines the hosting scene
  34533. * @param updatable defines if the mesh must be flagged as updatable
  34534. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34535. * @returns a new Mesh
  34536. */
  34537. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34538. if (scene === void 0) { scene = null; }
  34539. var options = {
  34540. radius: radius,
  34541. tessellation: tessellation,
  34542. sideOrientation: sideOrientation,
  34543. updatable: updatable
  34544. };
  34545. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34546. };
  34547. /**
  34548. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34549. * @param name defines the name of the mesh to create
  34550. * @param size sets the size (float) of each box side (default 1)
  34551. * @param scene defines the hosting scene
  34552. * @param updatable defines if the mesh must be flagged as updatable
  34553. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34554. * @returns a new Mesh
  34555. */
  34556. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34557. if (scene === void 0) { scene = null; }
  34558. var options = {
  34559. size: size,
  34560. sideOrientation: sideOrientation,
  34561. updatable: updatable
  34562. };
  34563. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34564. };
  34565. /**
  34566. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34567. * @param name defines the name of the mesh to create
  34568. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34569. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34570. * @param scene defines the hosting scene
  34571. * @param updatable defines if the mesh must be flagged as updatable
  34572. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34573. * @returns a new Mesh
  34574. */
  34575. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34576. var options = {
  34577. segments: segments,
  34578. diameterX: diameter,
  34579. diameterY: diameter,
  34580. diameterZ: diameter,
  34581. sideOrientation: sideOrientation,
  34582. updatable: updatable
  34583. };
  34584. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34585. };
  34586. /**
  34587. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34588. * @param name defines the name of the mesh to create
  34589. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34590. * @param diameterTop set the top cap diameter (floats, default 1)
  34591. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34592. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34593. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34594. * @param scene defines the hosting scene
  34595. * @param updatable defines if the mesh must be flagged as updatable
  34596. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34597. * @returns a new Mesh
  34598. */
  34599. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34600. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34601. if (scene !== undefined) {
  34602. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34603. updatable = scene;
  34604. }
  34605. scene = subdivisions;
  34606. subdivisions = 1;
  34607. }
  34608. var options = {
  34609. height: height,
  34610. diameterTop: diameterTop,
  34611. diameterBottom: diameterBottom,
  34612. tessellation: tessellation,
  34613. subdivisions: subdivisions,
  34614. sideOrientation: sideOrientation,
  34615. updatable: updatable
  34616. };
  34617. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34618. };
  34619. // Torus (Code from SharpDX.org)
  34620. /**
  34621. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34622. * @param name defines the name of the mesh to create
  34623. * @param diameter sets the diameter size (float) of the torus (default 1)
  34624. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34625. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34626. * @param scene defines the hosting scene
  34627. * @param updatable defines if the mesh must be flagged as updatable
  34628. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34629. * @returns a new Mesh
  34630. */
  34631. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34632. var options = {
  34633. diameter: diameter,
  34634. thickness: thickness,
  34635. tessellation: tessellation,
  34636. sideOrientation: sideOrientation,
  34637. updatable: updatable
  34638. };
  34639. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34640. };
  34641. /**
  34642. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34643. * @param name defines the name of the mesh to create
  34644. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34645. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34646. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34647. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34648. * @param p the number of windings on X axis (positive integers, default 2)
  34649. * @param q the number of windings on Y axis (positive integers, default 3)
  34650. * @param scene defines the hosting scene
  34651. * @param updatable defines if the mesh must be flagged as updatable
  34652. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34653. * @returns a new Mesh
  34654. */
  34655. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34656. var options = {
  34657. radius: radius,
  34658. tube: tube,
  34659. radialSegments: radialSegments,
  34660. tubularSegments: tubularSegments,
  34661. p: p,
  34662. q: q,
  34663. sideOrientation: sideOrientation,
  34664. updatable: updatable
  34665. };
  34666. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34667. };
  34668. /**
  34669. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34670. * @param name defines the name of the mesh to create
  34671. * @param points is an array successive Vector3
  34672. * @param scene defines the hosting scene
  34673. * @param updatable defines if the mesh must be flagged as updatable
  34674. * @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).
  34675. * @returns a new Mesh
  34676. */
  34677. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34678. if (scene === void 0) { scene = null; }
  34679. if (updatable === void 0) { updatable = false; }
  34680. if (instance === void 0) { instance = null; }
  34681. var options = {
  34682. points: points,
  34683. updatable: updatable,
  34684. instance: instance
  34685. };
  34686. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34687. };
  34688. /**
  34689. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34690. * @param name defines the name of the mesh to create
  34691. * @param points is an array successive Vector3
  34692. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34693. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34694. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34695. * @param scene defines the hosting scene
  34696. * @param updatable defines if the mesh must be flagged as updatable
  34697. * @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)
  34698. * @returns a new Mesh
  34699. */
  34700. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34701. if (scene === void 0) { scene = null; }
  34702. var options = {
  34703. points: points,
  34704. dashSize: dashSize,
  34705. gapSize: gapSize,
  34706. dashNb: dashNb,
  34707. updatable: updatable,
  34708. instance: instance
  34709. };
  34710. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34711. };
  34712. /**
  34713. * Creates a polygon mesh.
  34714. * Please consider using the same method from the MeshBuilder class instead.
  34715. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34716. * 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.
  34717. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34718. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34719. * Remember you can only change the shape positions, not their number when updating a polygon.
  34720. */
  34721. /**
  34722. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34723. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34724. * @param name defines the name of the mesh to create
  34725. * @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
  34726. * @param scene defines the hosting scene
  34727. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34728. * @param updatable defines if the mesh must be flagged as updatable
  34729. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34730. * @returns a new Mesh
  34731. */
  34732. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34733. var options = {
  34734. shape: shape,
  34735. holes: holes,
  34736. updatable: updatable,
  34737. sideOrientation: sideOrientation
  34738. };
  34739. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34740. };
  34741. /**
  34742. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34743. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34744. * @param name defines the name of the mesh to create
  34745. * @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
  34746. * @param depth defines the height of extrusion
  34747. * @param scene defines the hosting scene
  34748. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34749. * @param updatable defines if the mesh must be flagged as updatable
  34750. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34751. * @returns a new Mesh
  34752. */
  34753. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34754. var options = {
  34755. shape: shape,
  34756. holes: holes,
  34757. depth: depth,
  34758. updatable: updatable,
  34759. sideOrientation: sideOrientation
  34760. };
  34761. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34762. };
  34763. /**
  34764. * Creates an extruded shape mesh.
  34765. * 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
  34766. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34767. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34768. * @param name defines the name of the mesh to create
  34769. * @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
  34770. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34771. * @param scale is the value to scale the shape
  34772. * @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
  34773. * @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
  34774. * @param scene defines the hosting scene
  34775. * @param updatable defines if the mesh must be flagged as updatable
  34776. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34777. * @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)
  34778. * @returns a new Mesh
  34779. */
  34780. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34781. if (scene === void 0) { scene = null; }
  34782. var options = {
  34783. shape: shape,
  34784. path: path,
  34785. scale: scale,
  34786. rotation: rotation,
  34787. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34788. sideOrientation: sideOrientation,
  34789. instance: instance,
  34790. updatable: updatable
  34791. };
  34792. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34793. };
  34794. /**
  34795. * Creates an custom extruded shape mesh.
  34796. * The custom extrusion is a parametric shape.
  34797. * It has no predefined shape. Its final shape will depend on the input parameters.
  34798. * Please consider using the same method from the MeshBuilder class instead
  34799. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34800. * @param name defines the name of the mesh to create
  34801. * @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
  34802. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34803. * @param scaleFunction is a custom Javascript function called on each path point
  34804. * @param rotationFunction is a custom Javascript function called on each path point
  34805. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34806. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34807. * @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
  34808. * @param scene defines the hosting scene
  34809. * @param updatable defines if the mesh must be flagged as updatable
  34810. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34811. * @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)
  34812. * @returns a new Mesh
  34813. */
  34814. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34815. var options = {
  34816. shape: shape,
  34817. path: path,
  34818. scaleFunction: scaleFunction,
  34819. rotationFunction: rotationFunction,
  34820. ribbonCloseArray: ribbonCloseArray,
  34821. ribbonClosePath: ribbonClosePath,
  34822. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34823. sideOrientation: sideOrientation,
  34824. instance: instance,
  34825. updatable: updatable
  34826. };
  34827. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34828. };
  34829. /**
  34830. * Creates lathe mesh.
  34831. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34832. * Please consider using the same method from the MeshBuilder class instead
  34833. * @param name defines the name of the mesh to create
  34834. * @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
  34835. * @param radius is the radius value of the lathe
  34836. * @param tessellation is the side number of the lathe.
  34837. * @param scene defines the hosting scene
  34838. * @param updatable defines if the mesh must be flagged as updatable
  34839. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34840. * @returns a new Mesh
  34841. */
  34842. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34843. var options = {
  34844. shape: shape,
  34845. radius: radius,
  34846. tessellation: tessellation,
  34847. sideOrientation: sideOrientation,
  34848. updatable: updatable
  34849. };
  34850. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34851. };
  34852. /**
  34853. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34854. * @param name defines the name of the mesh to create
  34855. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34856. * @param scene defines the hosting scene
  34857. * @param updatable defines if the mesh must be flagged as updatable
  34858. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34859. * @returns a new Mesh
  34860. */
  34861. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34862. var options = {
  34863. size: size,
  34864. width: size,
  34865. height: size,
  34866. sideOrientation: sideOrientation,
  34867. updatable: updatable
  34868. };
  34869. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34870. };
  34871. /**
  34872. * Creates a ground mesh.
  34873. * Please consider using the same method from the MeshBuilder class instead
  34874. * @param name defines the name of the mesh to create
  34875. * @param width set the width of the ground
  34876. * @param height set the height of the ground
  34877. * @param subdivisions sets the number of subdivisions per side
  34878. * @param scene defines the hosting scene
  34879. * @param updatable defines if the mesh must be flagged as updatable
  34880. * @returns a new Mesh
  34881. */
  34882. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34883. var options = {
  34884. width: width,
  34885. height: height,
  34886. subdivisions: subdivisions,
  34887. updatable: updatable
  34888. };
  34889. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34890. };
  34891. /**
  34892. * Creates a tiled ground mesh.
  34893. * Please consider using the same method from the MeshBuilder class instead
  34894. * @param name defines the name of the mesh to create
  34895. * @param xmin set the ground minimum X coordinate
  34896. * @param zmin set the ground minimum Y coordinate
  34897. * @param xmax set the ground maximum X coordinate
  34898. * @param zmax set the ground maximum Z coordinate
  34899. * @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
  34900. * @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
  34901. * @param scene defines the hosting scene
  34902. * @param updatable defines if the mesh must be flagged as updatable
  34903. * @returns a new Mesh
  34904. */
  34905. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34906. var options = {
  34907. xmin: xmin,
  34908. zmin: zmin,
  34909. xmax: xmax,
  34910. zmax: zmax,
  34911. subdivisions: subdivisions,
  34912. precision: precision,
  34913. updatable: updatable
  34914. };
  34915. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34916. };
  34917. /**
  34918. * Creates a ground mesh from a height map.
  34919. * Please consider using the same method from the MeshBuilder class instead
  34920. * @see http://doc.babylonjs.com/babylon101/height_map
  34921. * @param name defines the name of the mesh to create
  34922. * @param url sets the URL of the height map image resource
  34923. * @param width set the ground width size
  34924. * @param height set the ground height size
  34925. * @param subdivisions sets the number of subdivision per side
  34926. * @param minHeight is the minimum altitude on the ground
  34927. * @param maxHeight is the maximum altitude on the ground
  34928. * @param scene defines the hosting scene
  34929. * @param updatable defines if the mesh must be flagged as updatable
  34930. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34931. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34932. * @returns a new Mesh
  34933. */
  34934. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34935. var options = {
  34936. width: width,
  34937. height: height,
  34938. subdivisions: subdivisions,
  34939. minHeight: minHeight,
  34940. maxHeight: maxHeight,
  34941. updatable: updatable,
  34942. onReady: onReady,
  34943. alphaFilter: alphaFilter
  34944. };
  34945. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34946. };
  34947. /**
  34948. * Creates a tube mesh.
  34949. * The tube is a parametric shape.
  34950. * It has no predefined shape. Its final shape will depend on the input parameters.
  34951. * Please consider using the same method from the MeshBuilder class instead
  34952. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34953. * @param name defines the name of the mesh to create
  34954. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34955. * @param radius sets the tube radius size
  34956. * @param tessellation is the number of sides on the tubular surface
  34957. * @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
  34958. * @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
  34959. * @param scene defines the hosting scene
  34960. * @param updatable defines if the mesh must be flagged as updatable
  34961. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34962. * @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)
  34963. * @returns a new Mesh
  34964. */
  34965. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34966. var options = {
  34967. path: path,
  34968. radius: radius,
  34969. tessellation: tessellation,
  34970. radiusFunction: radiusFunction,
  34971. arc: 1,
  34972. cap: cap,
  34973. updatable: updatable,
  34974. sideOrientation: sideOrientation,
  34975. instance: instance
  34976. };
  34977. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34978. };
  34979. /**
  34980. * Creates a polyhedron mesh.
  34981. * Please consider using the same method from the MeshBuilder class instead.
  34982. * * 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
  34983. * * The parameter `size` (positive float, default 1) sets the polygon size
  34984. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  34985. * * 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`
  34986. * * 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
  34987. * * 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)`)
  34988. * * 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
  34989. * * 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
  34990. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34991. * * 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
  34992. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  34993. * @param name defines the name of the mesh to create
  34994. * @param options defines the options used to create the mesh
  34995. * @param scene defines the hosting scene
  34996. * @returns a new Mesh
  34997. */
  34998. Mesh.CreatePolyhedron = function (name, options, scene) {
  34999. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35000. };
  35001. /**
  35002. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35003. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35004. * * 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`)
  35005. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35006. * * 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
  35007. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35008. * * 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
  35009. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35010. * @param name defines the name of the mesh
  35011. * @param options defines the options used to create the mesh
  35012. * @param scene defines the hosting scene
  35013. * @returns a new Mesh
  35014. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35015. */
  35016. Mesh.CreateIcoSphere = function (name, options, scene) {
  35017. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35018. };
  35019. /**
  35020. * Creates a decal mesh.
  35021. * Please consider using the same method from the MeshBuilder class instead.
  35022. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35023. * @param name defines the name of the mesh
  35024. * @param sourceMesh defines the mesh receiving the decal
  35025. * @param position sets the position of the decal in world coordinates
  35026. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35027. * @param size sets the decal scaling
  35028. * @param angle sets the angle to rotate the decal
  35029. * @returns a new Mesh
  35030. */
  35031. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35032. var options = {
  35033. position: position,
  35034. normal: normal,
  35035. size: size,
  35036. angle: angle
  35037. };
  35038. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35039. };
  35040. // Skeletons
  35041. /**
  35042. * Prepare internal position array for software CPU skinning
  35043. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35044. */
  35045. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35046. if (!this._sourcePositions) {
  35047. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35048. if (!source) {
  35049. return this._sourcePositions;
  35050. }
  35051. this._sourcePositions = new Float32Array(source);
  35052. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35053. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35054. }
  35055. }
  35056. return this._sourcePositions;
  35057. };
  35058. /**
  35059. * Prepare internal normal array for software CPU skinning
  35060. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35061. */
  35062. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35063. if (!this._sourceNormals) {
  35064. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35065. if (!source) {
  35066. return this._sourceNormals;
  35067. }
  35068. this._sourceNormals = new Float32Array(source);
  35069. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35070. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35071. }
  35072. }
  35073. return this._sourceNormals;
  35074. };
  35075. /**
  35076. * Updates the vertex buffer by applying transformation from the bones
  35077. * @param skeleton defines the skeleton to apply to current mesh
  35078. * @returns the current mesh
  35079. */
  35080. Mesh.prototype.applySkeleton = function (skeleton) {
  35081. if (!this.geometry) {
  35082. return this;
  35083. }
  35084. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35085. return this;
  35086. }
  35087. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35088. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35089. return this;
  35090. }
  35091. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35092. return this;
  35093. }
  35094. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35095. return this;
  35096. }
  35097. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35098. return this;
  35099. }
  35100. if (!this._sourcePositions) {
  35101. var submeshes = this.subMeshes.slice();
  35102. this.setPositionsForCPUSkinning();
  35103. this.subMeshes = submeshes;
  35104. }
  35105. if (!this._sourceNormals) {
  35106. this.setNormalsForCPUSkinning();
  35107. }
  35108. // positionsData checks for not being Float32Array will only pass at most once
  35109. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35110. if (!positionsData) {
  35111. return this;
  35112. }
  35113. if (!(positionsData instanceof Float32Array)) {
  35114. positionsData = new Float32Array(positionsData);
  35115. }
  35116. // normalsData checks for not being Float32Array will only pass at most once
  35117. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35118. if (!normalsData) {
  35119. return this;
  35120. }
  35121. if (!(normalsData instanceof Float32Array)) {
  35122. normalsData = new Float32Array(normalsData);
  35123. }
  35124. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35125. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35126. if (!matricesWeightsData || !matricesIndicesData) {
  35127. return this;
  35128. }
  35129. var needExtras = this.numBoneInfluencers > 4;
  35130. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35131. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35132. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35133. var tempVector3 = BABYLON.Vector3.Zero();
  35134. var finalMatrix = new BABYLON.Matrix();
  35135. var tempMatrix = new BABYLON.Matrix();
  35136. var matWeightIdx = 0;
  35137. var inf;
  35138. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35139. var weight;
  35140. for (inf = 0; inf < 4; inf++) {
  35141. weight = matricesWeightsData[matWeightIdx + inf];
  35142. if (weight > 0) {
  35143. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35144. finalMatrix.addToSelf(tempMatrix);
  35145. }
  35146. }
  35147. if (needExtras) {
  35148. for (inf = 0; inf < 4; inf++) {
  35149. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35150. if (weight > 0) {
  35151. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35152. finalMatrix.addToSelf(tempMatrix);
  35153. }
  35154. }
  35155. }
  35156. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35157. tempVector3.toArray(positionsData, index);
  35158. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35159. tempVector3.toArray(normalsData, index);
  35160. finalMatrix.reset();
  35161. }
  35162. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35163. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35164. return this;
  35165. };
  35166. // Tools
  35167. /**
  35168. * 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
  35169. * @param meshes defines the list of meshes to scan
  35170. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35171. */
  35172. Mesh.MinMax = function (meshes) {
  35173. var minVector = null;
  35174. var maxVector = null;
  35175. meshes.forEach(function (mesh, index, array) {
  35176. var boundingInfo = mesh.getBoundingInfo();
  35177. var boundingBox = boundingInfo.boundingBox;
  35178. if (!minVector || !maxVector) {
  35179. minVector = boundingBox.minimumWorld;
  35180. maxVector = boundingBox.maximumWorld;
  35181. }
  35182. else {
  35183. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35184. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35185. }
  35186. });
  35187. if (!minVector || !maxVector) {
  35188. return {
  35189. min: BABYLON.Vector3.Zero(),
  35190. max: BABYLON.Vector3.Zero()
  35191. };
  35192. }
  35193. return {
  35194. min: minVector,
  35195. max: maxVector
  35196. };
  35197. };
  35198. /**
  35199. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35200. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35201. * @returns a vector3
  35202. */
  35203. Mesh.Center = function (meshesOrMinMaxVector) {
  35204. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35205. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35206. };
  35207. /**
  35208. * Merge the array of meshes into a single mesh for performance reasons.
  35209. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35210. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35211. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35212. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35213. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35214. * @returns a new mesh
  35215. */
  35216. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35217. if (disposeSource === void 0) { disposeSource = true; }
  35218. var index;
  35219. if (!allow32BitsIndices) {
  35220. var totalVertices = 0;
  35221. // Counting vertices
  35222. for (index = 0; index < meshes.length; index++) {
  35223. if (meshes[index]) {
  35224. totalVertices += meshes[index].getTotalVertices();
  35225. if (totalVertices > 65536) {
  35226. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35227. return null;
  35228. }
  35229. }
  35230. }
  35231. }
  35232. // Merge
  35233. var vertexData = null;
  35234. var otherVertexData;
  35235. var indiceArray = new Array();
  35236. var source = null;
  35237. for (index = 0; index < meshes.length; index++) {
  35238. if (meshes[index]) {
  35239. var wm = meshes[index].computeWorldMatrix(true);
  35240. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35241. otherVertexData.transform(wm);
  35242. if (vertexData) {
  35243. vertexData.merge(otherVertexData, allow32BitsIndices);
  35244. }
  35245. else {
  35246. vertexData = otherVertexData;
  35247. source = meshes[index];
  35248. }
  35249. if (subdivideWithSubMeshes) {
  35250. indiceArray.push(meshes[index].getTotalIndices());
  35251. }
  35252. }
  35253. }
  35254. source = source;
  35255. if (!meshSubclass) {
  35256. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35257. }
  35258. vertexData.applyToMesh(meshSubclass);
  35259. // Setting properties
  35260. meshSubclass.material = source.material;
  35261. meshSubclass.checkCollisions = source.checkCollisions;
  35262. // Cleaning
  35263. if (disposeSource) {
  35264. for (index = 0; index < meshes.length; index++) {
  35265. if (meshes[index]) {
  35266. meshes[index].dispose();
  35267. }
  35268. }
  35269. }
  35270. // Subdivide
  35271. if (subdivideWithSubMeshes) {
  35272. //-- removal of global submesh
  35273. meshSubclass.releaseSubMeshes();
  35274. index = 0;
  35275. var offset = 0;
  35276. //-- apply subdivision according to index table
  35277. while (index < indiceArray.length) {
  35278. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35279. offset += indiceArray[index];
  35280. index++;
  35281. }
  35282. }
  35283. return meshSubclass;
  35284. };
  35285. // Consts
  35286. /**
  35287. * Mesh side orientation : usually the external or front surface
  35288. */
  35289. Mesh.FRONTSIDE = 0;
  35290. /**
  35291. * Mesh side orientation : usually the internal or back surface
  35292. */
  35293. Mesh.BACKSIDE = 1;
  35294. /**
  35295. * Mesh side orientation : both internal and external or front and back surfaces
  35296. */
  35297. Mesh.DOUBLESIDE = 2;
  35298. /**
  35299. * Mesh side orientation : by default, `FRONTSIDE`
  35300. */
  35301. Mesh.DEFAULTSIDE = 0;
  35302. /**
  35303. * Mesh cap setting : no cap
  35304. */
  35305. Mesh.NO_CAP = 0;
  35306. /**
  35307. * Mesh cap setting : one cap at the beginning of the mesh
  35308. */
  35309. Mesh.CAP_START = 1;
  35310. /**
  35311. * Mesh cap setting : one cap at the end of the mesh
  35312. */
  35313. Mesh.CAP_END = 2;
  35314. /**
  35315. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35316. */
  35317. Mesh.CAP_ALL = 3;
  35318. return Mesh;
  35319. }(BABYLON.AbstractMesh));
  35320. BABYLON.Mesh = Mesh;
  35321. })(BABYLON || (BABYLON = {}));
  35322. //# sourceMappingURL=babylon.mesh.js.map
  35323. var BABYLON;
  35324. (function (BABYLON) {
  35325. /**
  35326. * Base class for submeshes
  35327. */
  35328. var BaseSubMesh = /** @class */ (function () {
  35329. function BaseSubMesh() {
  35330. }
  35331. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35332. /**
  35333. * Gets associated effect
  35334. */
  35335. get: function () {
  35336. return this._materialEffect;
  35337. },
  35338. enumerable: true,
  35339. configurable: true
  35340. });
  35341. /**
  35342. * Sets associated effect (effect used to render this submesh)
  35343. * @param effect defines the effect to associate with
  35344. * @param defines defines the set of defines used to compile this effect
  35345. */
  35346. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35347. if (defines === void 0) { defines = null; }
  35348. if (this._materialEffect === effect) {
  35349. if (!effect) {
  35350. this._materialDefines = null;
  35351. }
  35352. return;
  35353. }
  35354. this._materialDefines = defines;
  35355. this._materialEffect = effect;
  35356. };
  35357. return BaseSubMesh;
  35358. }());
  35359. BABYLON.BaseSubMesh = BaseSubMesh;
  35360. /**
  35361. * Defines a subdivision inside a mesh
  35362. */
  35363. var SubMesh = /** @class */ (function (_super) {
  35364. __extends(SubMesh, _super);
  35365. /**
  35366. * Creates a new submesh
  35367. * @param materialIndex defines the material index to use
  35368. * @param verticesStart defines vertex index start
  35369. * @param verticesCount defines vertices count
  35370. * @param indexStart defines index start
  35371. * @param indexCount defines indices count
  35372. * @param mesh defines the parent mesh
  35373. * @param renderingMesh defines an optional rendering mesh
  35374. * @param createBoundingBox defines if bounding box should be created for this submesh
  35375. */
  35376. function SubMesh(
  35377. /** the material index to use */
  35378. materialIndex,
  35379. /** vertex index start */
  35380. verticesStart,
  35381. /** vertices count */
  35382. verticesCount,
  35383. /** index start */
  35384. indexStart,
  35385. /** indices count */
  35386. indexCount, mesh, renderingMesh, createBoundingBox) {
  35387. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35388. var _this = _super.call(this) || this;
  35389. _this.materialIndex = materialIndex;
  35390. _this.verticesStart = verticesStart;
  35391. _this.verticesCount = verticesCount;
  35392. _this.indexStart = indexStart;
  35393. _this.indexCount = indexCount;
  35394. /** @hidden */
  35395. _this._renderId = 0;
  35396. _this._mesh = mesh;
  35397. _this._renderingMesh = renderingMesh || mesh;
  35398. mesh.subMeshes.push(_this);
  35399. _this._trianglePlanes = [];
  35400. _this._id = mesh.subMeshes.length - 1;
  35401. if (createBoundingBox) {
  35402. _this.refreshBoundingInfo();
  35403. mesh.computeWorldMatrix(true);
  35404. }
  35405. return _this;
  35406. }
  35407. /**
  35408. * Add a new submesh to a mesh
  35409. * @param materialIndex defines the material index to use
  35410. * @param verticesStart defines vertex index start
  35411. * @param verticesCount defines vertices count
  35412. * @param indexStart defines index start
  35413. * @param indexCount defines indices count
  35414. * @param mesh defines the parent mesh
  35415. * @param renderingMesh defines an optional rendering mesh
  35416. * @param createBoundingBox defines if bounding box should be created for this submesh
  35417. * @returns the new submesh
  35418. */
  35419. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35420. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35421. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35422. };
  35423. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35424. /**
  35425. * Returns true if this submesh covers the entire parent mesh
  35426. * @ignorenaming
  35427. */
  35428. get: function () {
  35429. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35430. },
  35431. enumerable: true,
  35432. configurable: true
  35433. });
  35434. /**
  35435. * Returns the submesh BoudingInfo object
  35436. * @returns current bounding info (or mesh's one if the submesh is global)
  35437. */
  35438. SubMesh.prototype.getBoundingInfo = function () {
  35439. if (this.IsGlobal) {
  35440. return this._mesh.getBoundingInfo();
  35441. }
  35442. return this._boundingInfo;
  35443. };
  35444. /**
  35445. * Sets the submesh BoundingInfo
  35446. * @param boundingInfo defines the new bounding info to use
  35447. * @returns the SubMesh
  35448. */
  35449. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35450. this._boundingInfo = boundingInfo;
  35451. return this;
  35452. };
  35453. /**
  35454. * Returns the mesh of the current submesh
  35455. * @return the parent mesh
  35456. */
  35457. SubMesh.prototype.getMesh = function () {
  35458. return this._mesh;
  35459. };
  35460. /**
  35461. * Returns the rendering mesh of the submesh
  35462. * @returns the rendering mesh (could be different from parent mesh)
  35463. */
  35464. SubMesh.prototype.getRenderingMesh = function () {
  35465. return this._renderingMesh;
  35466. };
  35467. /**
  35468. * Returns the submesh material
  35469. * @returns null or the current material
  35470. */
  35471. SubMesh.prototype.getMaterial = function () {
  35472. var rootMaterial = this._renderingMesh.material;
  35473. if (rootMaterial === null || rootMaterial === undefined) {
  35474. return this._mesh.getScene().defaultMaterial;
  35475. }
  35476. else if (rootMaterial.getSubMaterial) {
  35477. var multiMaterial = rootMaterial;
  35478. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35479. if (this._currentMaterial !== effectiveMaterial) {
  35480. this._currentMaterial = effectiveMaterial;
  35481. this._materialDefines = null;
  35482. }
  35483. return effectiveMaterial;
  35484. }
  35485. return rootMaterial;
  35486. };
  35487. // Methods
  35488. /**
  35489. * Sets a new updated BoundingInfo object to the submesh
  35490. * @returns the SubMesh
  35491. */
  35492. SubMesh.prototype.refreshBoundingInfo = function () {
  35493. this._lastColliderWorldVertices = null;
  35494. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35495. return this;
  35496. }
  35497. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35498. if (!data) {
  35499. this._boundingInfo = this._mesh.getBoundingInfo();
  35500. return this;
  35501. }
  35502. var indices = this._renderingMesh.getIndices();
  35503. var extend;
  35504. //is this the only submesh?
  35505. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35506. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35507. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35508. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35509. }
  35510. else {
  35511. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35512. }
  35513. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35514. return this;
  35515. };
  35516. /** @hidden */
  35517. SubMesh.prototype._checkCollision = function (collider) {
  35518. var boundingInfo = this.getBoundingInfo();
  35519. return boundingInfo._checkCollision(collider);
  35520. };
  35521. /**
  35522. * Updates the submesh BoundingInfo
  35523. * @param world defines the world matrix to use to update the bounding info
  35524. * @returns the submesh
  35525. */
  35526. SubMesh.prototype.updateBoundingInfo = function (world) {
  35527. var boundingInfo = this.getBoundingInfo();
  35528. if (!boundingInfo) {
  35529. this.refreshBoundingInfo();
  35530. boundingInfo = this.getBoundingInfo();
  35531. }
  35532. boundingInfo.update(world);
  35533. return this;
  35534. };
  35535. /**
  35536. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35537. * @param frustumPlanes defines the frustum planes
  35538. * @returns true if the submesh is intersecting with the frustum
  35539. */
  35540. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35541. var boundingInfo = this.getBoundingInfo();
  35542. if (!boundingInfo) {
  35543. return false;
  35544. }
  35545. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35546. };
  35547. /**
  35548. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35549. * @param frustumPlanes defines the frustum planes
  35550. * @returns true if the submesh is inside the frustum
  35551. */
  35552. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35553. var boundingInfo = this.getBoundingInfo();
  35554. if (!boundingInfo) {
  35555. return false;
  35556. }
  35557. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35558. };
  35559. /**
  35560. * Renders the submesh
  35561. * @param enableAlphaMode defines if alpha needs to be used
  35562. * @returns the submesh
  35563. */
  35564. SubMesh.prototype.render = function (enableAlphaMode) {
  35565. this._renderingMesh.render(this, enableAlphaMode);
  35566. return this;
  35567. };
  35568. /**
  35569. * @hidden
  35570. */
  35571. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35572. if (!this._linesIndexBuffer) {
  35573. var linesIndices = [];
  35574. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35575. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35576. }
  35577. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35578. this._linesIndexCount = linesIndices.length;
  35579. }
  35580. return this._linesIndexBuffer;
  35581. };
  35582. /**
  35583. * Checks if the submesh intersects with a ray
  35584. * @param ray defines the ray to test
  35585. * @returns true is the passed ray intersects the submesh bounding box
  35586. */
  35587. SubMesh.prototype.canIntersects = function (ray) {
  35588. var boundingInfo = this.getBoundingInfo();
  35589. if (!boundingInfo) {
  35590. return false;
  35591. }
  35592. return ray.intersectsBox(boundingInfo.boundingBox);
  35593. };
  35594. /**
  35595. * Intersects current submesh with a ray
  35596. * @param ray defines the ray to test
  35597. * @param positions defines mesh's positions array
  35598. * @param indices defines mesh's indices array
  35599. * @param fastCheck defines if only bounding info should be used
  35600. * @returns intersection info or null if no intersection
  35601. */
  35602. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35603. var material = this.getMaterial();
  35604. if (!material) {
  35605. return null;
  35606. }
  35607. switch (material.fillMode) {
  35608. case BABYLON.Material.PointListDrawMode:
  35609. case BABYLON.Material.LineListDrawMode:
  35610. case BABYLON.Material.LineLoopDrawMode:
  35611. case BABYLON.Material.LineStripDrawMode:
  35612. case BABYLON.Material.TriangleFanDrawMode:
  35613. case BABYLON.Material.TriangleStripDrawMode:
  35614. return null;
  35615. }
  35616. // LineMesh first as it's also a Mesh...
  35617. if (BABYLON.LinesMesh) {
  35618. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35619. if (mesh instanceof BABYLON.LinesMesh) {
  35620. var linesMesh = mesh;
  35621. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35622. }
  35623. }
  35624. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35625. };
  35626. /** @hidden */
  35627. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35628. var intersectInfo = null;
  35629. // Line test
  35630. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35631. var p0 = positions[indices[index]];
  35632. var p1 = positions[indices[index + 1]];
  35633. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35634. if (length < 0) {
  35635. continue;
  35636. }
  35637. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35638. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35639. if (fastCheck) {
  35640. break;
  35641. }
  35642. }
  35643. }
  35644. return intersectInfo;
  35645. };
  35646. /** @hidden */
  35647. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35648. var intersectInfo = null;
  35649. // Triangles test
  35650. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35651. var p0 = positions[indices[index]];
  35652. var p1 = positions[indices[index + 1]];
  35653. var p2 = positions[indices[index + 2]];
  35654. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35655. if (currentIntersectInfo) {
  35656. if (currentIntersectInfo.distance < 0) {
  35657. continue;
  35658. }
  35659. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35660. intersectInfo = currentIntersectInfo;
  35661. intersectInfo.faceId = index / 3;
  35662. if (fastCheck) {
  35663. break;
  35664. }
  35665. }
  35666. }
  35667. }
  35668. return intersectInfo;
  35669. };
  35670. /** @hidden */
  35671. SubMesh.prototype._rebuild = function () {
  35672. if (this._linesIndexBuffer) {
  35673. this._linesIndexBuffer = null;
  35674. }
  35675. };
  35676. // Clone
  35677. /**
  35678. * Creates a new submesh from the passed mesh
  35679. * @param newMesh defines the new hosting mesh
  35680. * @param newRenderingMesh defines an optional rendering mesh
  35681. * @returns the new submesh
  35682. */
  35683. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35684. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35685. if (!this.IsGlobal) {
  35686. var boundingInfo = this.getBoundingInfo();
  35687. if (!boundingInfo) {
  35688. return result;
  35689. }
  35690. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35691. }
  35692. return result;
  35693. };
  35694. // Dispose
  35695. /**
  35696. * Release associated resources
  35697. */
  35698. SubMesh.prototype.dispose = function () {
  35699. if (this._linesIndexBuffer) {
  35700. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35701. this._linesIndexBuffer = null;
  35702. }
  35703. // Remove from mesh
  35704. var index = this._mesh.subMeshes.indexOf(this);
  35705. this._mesh.subMeshes.splice(index, 1);
  35706. };
  35707. // Statics
  35708. /**
  35709. * Creates a new submesh from indices data
  35710. * @param materialIndex the index of the main mesh material
  35711. * @param startIndex the index where to start the copy in the mesh indices array
  35712. * @param indexCount the number of indices to copy then from the startIndex
  35713. * @param mesh the main mesh to create the submesh from
  35714. * @param renderingMesh the optional rendering mesh
  35715. * @returns a new submesh
  35716. */
  35717. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35718. var minVertexIndex = Number.MAX_VALUE;
  35719. var maxVertexIndex = -Number.MAX_VALUE;
  35720. renderingMesh = (renderingMesh || mesh);
  35721. var indices = renderingMesh.getIndices();
  35722. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35723. var vertexIndex = indices[index];
  35724. if (vertexIndex < minVertexIndex)
  35725. minVertexIndex = vertexIndex;
  35726. if (vertexIndex > maxVertexIndex)
  35727. maxVertexIndex = vertexIndex;
  35728. }
  35729. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35730. };
  35731. return SubMesh;
  35732. }(BaseSubMesh));
  35733. BABYLON.SubMesh = SubMesh;
  35734. })(BABYLON || (BABYLON = {}));
  35735. //# sourceMappingURL=babylon.subMesh.js.map
  35736. var __assign = (this && this.__assign) || function () {
  35737. __assign = Object.assign || function(t) {
  35738. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35739. s = arguments[i];
  35740. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35741. t[p] = s[p];
  35742. }
  35743. return t;
  35744. };
  35745. return __assign.apply(this, arguments);
  35746. };
  35747. var BABYLON;
  35748. (function (BABYLON) {
  35749. /**
  35750. * Manages the defines for the Material
  35751. */
  35752. var MaterialDefines = /** @class */ (function () {
  35753. function MaterialDefines() {
  35754. this._isDirty = true;
  35755. /** @hidden */
  35756. this._areLightsDirty = true;
  35757. /** @hidden */
  35758. this._areAttributesDirty = true;
  35759. /** @hidden */
  35760. this._areTexturesDirty = true;
  35761. /** @hidden */
  35762. this._areFresnelDirty = true;
  35763. /** @hidden */
  35764. this._areMiscDirty = true;
  35765. /** @hidden */
  35766. this._areImageProcessingDirty = true;
  35767. /** @hidden */
  35768. this._normals = false;
  35769. /** @hidden */
  35770. this._uvs = false;
  35771. /** @hidden */
  35772. this._needNormals = false;
  35773. /** @hidden */
  35774. this._needUVs = false;
  35775. }
  35776. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35777. /**
  35778. * Specifies if the material needs to be re-calculated
  35779. */
  35780. get: function () {
  35781. return this._isDirty;
  35782. },
  35783. enumerable: true,
  35784. configurable: true
  35785. });
  35786. /**
  35787. * Marks the material to indicate that it has been re-calculated
  35788. */
  35789. MaterialDefines.prototype.markAsProcessed = function () {
  35790. this._isDirty = false;
  35791. this._areAttributesDirty = false;
  35792. this._areTexturesDirty = false;
  35793. this._areFresnelDirty = false;
  35794. this._areLightsDirty = false;
  35795. this._areMiscDirty = false;
  35796. this._areImageProcessingDirty = false;
  35797. };
  35798. /**
  35799. * Marks the material to indicate that it needs to be re-calculated
  35800. */
  35801. MaterialDefines.prototype.markAsUnprocessed = function () {
  35802. this._isDirty = true;
  35803. };
  35804. /**
  35805. * Marks the material to indicate all of its defines need to be re-calculated
  35806. */
  35807. MaterialDefines.prototype.markAllAsDirty = function () {
  35808. this._areTexturesDirty = true;
  35809. this._areAttributesDirty = true;
  35810. this._areLightsDirty = true;
  35811. this._areFresnelDirty = true;
  35812. this._areMiscDirty = true;
  35813. this._areImageProcessingDirty = true;
  35814. this._isDirty = true;
  35815. };
  35816. /**
  35817. * Marks the material to indicate that image processing needs to be re-calculated
  35818. */
  35819. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35820. this._areImageProcessingDirty = true;
  35821. this._isDirty = true;
  35822. };
  35823. /**
  35824. * Marks the material to indicate the lights need to be re-calculated
  35825. */
  35826. MaterialDefines.prototype.markAsLightDirty = function () {
  35827. this._areLightsDirty = true;
  35828. this._isDirty = true;
  35829. };
  35830. /**
  35831. * Marks the attribute state as changed
  35832. */
  35833. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35834. this._areAttributesDirty = true;
  35835. this._isDirty = true;
  35836. };
  35837. /**
  35838. * Marks the texture state as changed
  35839. */
  35840. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35841. this._areTexturesDirty = true;
  35842. this._isDirty = true;
  35843. };
  35844. /**
  35845. * Marks the fresnel state as changed
  35846. */
  35847. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35848. this._areFresnelDirty = true;
  35849. this._isDirty = true;
  35850. };
  35851. /**
  35852. * Marks the misc state as changed
  35853. */
  35854. MaterialDefines.prototype.markAsMiscDirty = function () {
  35855. this._areMiscDirty = true;
  35856. this._isDirty = true;
  35857. };
  35858. /**
  35859. * Rebuilds the material defines
  35860. */
  35861. MaterialDefines.prototype.rebuild = function () {
  35862. if (this._keys) {
  35863. delete this._keys;
  35864. }
  35865. this._keys = [];
  35866. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35867. var key = _a[_i];
  35868. if (key[0] === "_") {
  35869. continue;
  35870. }
  35871. this._keys.push(key);
  35872. }
  35873. };
  35874. /**
  35875. * Specifies if two material defines are equal
  35876. * @param other - A material define instance to compare to
  35877. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35878. */
  35879. MaterialDefines.prototype.isEqual = function (other) {
  35880. if (this._keys.length !== other._keys.length) {
  35881. return false;
  35882. }
  35883. for (var index = 0; index < this._keys.length; index++) {
  35884. var prop = this._keys[index];
  35885. if (this[prop] !== other[prop]) {
  35886. return false;
  35887. }
  35888. }
  35889. return true;
  35890. };
  35891. /**
  35892. * Clones this instance's defines to another instance
  35893. * @param other - material defines to clone values to
  35894. */
  35895. MaterialDefines.prototype.cloneTo = function (other) {
  35896. if (this._keys.length !== other._keys.length) {
  35897. other._keys = this._keys.slice(0);
  35898. }
  35899. for (var index = 0; index < this._keys.length; index++) {
  35900. var prop = this._keys[index];
  35901. other[prop] = this[prop];
  35902. }
  35903. };
  35904. /**
  35905. * Resets the material define values
  35906. */
  35907. MaterialDefines.prototype.reset = function () {
  35908. for (var index = 0; index < this._keys.length; index++) {
  35909. var prop = this._keys[index];
  35910. var type = typeof this[prop];
  35911. switch (type) {
  35912. case "number":
  35913. this[prop] = 0;
  35914. break;
  35915. case "string":
  35916. this[prop] = "";
  35917. break;
  35918. default:
  35919. this[prop] = false;
  35920. break;
  35921. }
  35922. }
  35923. };
  35924. /**
  35925. * Converts the material define values to a string
  35926. * @returns - String of material define information
  35927. */
  35928. MaterialDefines.prototype.toString = function () {
  35929. var result = "";
  35930. for (var index = 0; index < this._keys.length; index++) {
  35931. var prop = this._keys[index];
  35932. var value = this[prop];
  35933. var type = typeof value;
  35934. switch (type) {
  35935. case "number":
  35936. case "string":
  35937. result += "#define " + prop + " " + value + "\n";
  35938. break;
  35939. default:
  35940. if (value) {
  35941. result += "#define " + prop + "\n";
  35942. }
  35943. break;
  35944. }
  35945. }
  35946. return result;
  35947. };
  35948. return MaterialDefines;
  35949. }());
  35950. BABYLON.MaterialDefines = MaterialDefines;
  35951. /**
  35952. * Base class for the main features of a material in Babylon.js
  35953. */
  35954. var Material = /** @class */ (function () {
  35955. /**
  35956. * Creates a material instance
  35957. * @param name defines the name of the material
  35958. * @param scene defines the scene to reference
  35959. * @param doNotAdd specifies if the material should be added to the scene
  35960. */
  35961. function Material(name, scene, doNotAdd) {
  35962. /**
  35963. * Specifies if the ready state should be checked on each call
  35964. */
  35965. this.checkReadyOnEveryCall = false;
  35966. /**
  35967. * Specifies if the ready state should be checked once
  35968. */
  35969. this.checkReadyOnlyOnce = false;
  35970. /**
  35971. * The state of the material
  35972. */
  35973. this.state = "";
  35974. /**
  35975. * The alpha value of the material
  35976. */
  35977. this._alpha = 1.0;
  35978. /**
  35979. * Specifies if back face culling is enabled
  35980. */
  35981. this._backFaceCulling = true;
  35982. /**
  35983. * Specifies if the material should be serialized
  35984. */
  35985. this.doNotSerialize = false;
  35986. /**
  35987. * Specifies if the effect should be stored on sub meshes
  35988. */
  35989. this.storeEffectOnSubMeshes = false;
  35990. /**
  35991. * An event triggered when the material is disposed
  35992. */
  35993. this.onDisposeObservable = new BABYLON.Observable();
  35994. /**
  35995. * Stores the value of the alpha mode
  35996. */
  35997. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35998. /**
  35999. * Stores the state of the need depth pre-pass value
  36000. */
  36001. this._needDepthPrePass = false;
  36002. /**
  36003. * Specifies if depth writing should be disabled
  36004. */
  36005. this.disableDepthWrite = false;
  36006. /**
  36007. * Specifies if depth writing should be forced
  36008. */
  36009. this.forceDepthWrite = false;
  36010. /**
  36011. * Specifies if there should be a separate pass for culling
  36012. */
  36013. this.separateCullingPass = false;
  36014. /**
  36015. * Stores the state specifing if fog should be enabled
  36016. */
  36017. this._fogEnabled = true;
  36018. /**
  36019. * Stores the size of points
  36020. */
  36021. this.pointSize = 1.0;
  36022. /**
  36023. * Stores the z offset value
  36024. */
  36025. this.zOffset = 0;
  36026. /**
  36027. * @hidden
  36028. * Specifies if the material was previously ready
  36029. */
  36030. this._wasPreviouslyReady = false;
  36031. /**
  36032. * Stores the fill mode state
  36033. */
  36034. this._fillMode = Material.TriangleFillMode;
  36035. this.name = name;
  36036. this.id = name || BABYLON.Tools.RandomId();
  36037. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36038. this.uniqueId = this._scene.getUniqueId();
  36039. if (this._scene.useRightHandedSystem) {
  36040. this.sideOrientation = Material.ClockWiseSideOrientation;
  36041. }
  36042. else {
  36043. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36044. }
  36045. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36046. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36047. if (!doNotAdd) {
  36048. this._scene.materials.push(this);
  36049. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36050. }
  36051. }
  36052. Object.defineProperty(Material, "TriangleFillMode", {
  36053. /**
  36054. * Returns the triangle fill mode
  36055. */
  36056. get: function () {
  36057. return Material._TriangleFillMode;
  36058. },
  36059. enumerable: true,
  36060. configurable: true
  36061. });
  36062. Object.defineProperty(Material, "WireFrameFillMode", {
  36063. /**
  36064. * Returns the wireframe mode
  36065. */
  36066. get: function () {
  36067. return Material._WireFrameFillMode;
  36068. },
  36069. enumerable: true,
  36070. configurable: true
  36071. });
  36072. Object.defineProperty(Material, "PointFillMode", {
  36073. /**
  36074. * Returns the point fill mode
  36075. */
  36076. get: function () {
  36077. return Material._PointFillMode;
  36078. },
  36079. enumerable: true,
  36080. configurable: true
  36081. });
  36082. Object.defineProperty(Material, "PointListDrawMode", {
  36083. /**
  36084. * Returns the point list draw mode
  36085. */
  36086. get: function () {
  36087. return Material._PointListDrawMode;
  36088. },
  36089. enumerable: true,
  36090. configurable: true
  36091. });
  36092. Object.defineProperty(Material, "LineListDrawMode", {
  36093. /**
  36094. * Returns the line list draw mode
  36095. */
  36096. get: function () {
  36097. return Material._LineListDrawMode;
  36098. },
  36099. enumerable: true,
  36100. configurable: true
  36101. });
  36102. Object.defineProperty(Material, "LineLoopDrawMode", {
  36103. /**
  36104. * Returns the line loop draw mode
  36105. */
  36106. get: function () {
  36107. return Material._LineLoopDrawMode;
  36108. },
  36109. enumerable: true,
  36110. configurable: true
  36111. });
  36112. Object.defineProperty(Material, "LineStripDrawMode", {
  36113. /**
  36114. * Returns the line strip draw mode
  36115. */
  36116. get: function () {
  36117. return Material._LineStripDrawMode;
  36118. },
  36119. enumerable: true,
  36120. configurable: true
  36121. });
  36122. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36123. /**
  36124. * Returns the triangle strip draw mode
  36125. */
  36126. get: function () {
  36127. return Material._TriangleStripDrawMode;
  36128. },
  36129. enumerable: true,
  36130. configurable: true
  36131. });
  36132. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36133. /**
  36134. * Returns the triangle fan draw mode
  36135. */
  36136. get: function () {
  36137. return Material._TriangleFanDrawMode;
  36138. },
  36139. enumerable: true,
  36140. configurable: true
  36141. });
  36142. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36143. /**
  36144. * Returns the clock-wise side orientation
  36145. */
  36146. get: function () {
  36147. return Material._ClockWiseSideOrientation;
  36148. },
  36149. enumerable: true,
  36150. configurable: true
  36151. });
  36152. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36153. /**
  36154. * Returns the counter clock-wise side orientation
  36155. */
  36156. get: function () {
  36157. return Material._CounterClockWiseSideOrientation;
  36158. },
  36159. enumerable: true,
  36160. configurable: true
  36161. });
  36162. Object.defineProperty(Material.prototype, "alpha", {
  36163. /**
  36164. * Gets the alpha value of the material
  36165. */
  36166. get: function () {
  36167. return this._alpha;
  36168. },
  36169. /**
  36170. * Sets the alpha value of the material
  36171. */
  36172. set: function (value) {
  36173. if (this._alpha === value) {
  36174. return;
  36175. }
  36176. this._alpha = value;
  36177. this.markAsDirty(Material.MiscDirtyFlag);
  36178. },
  36179. enumerable: true,
  36180. configurable: true
  36181. });
  36182. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36183. /**
  36184. * Gets the back-face culling state
  36185. */
  36186. get: function () {
  36187. return this._backFaceCulling;
  36188. },
  36189. /**
  36190. * Sets the back-face culling state
  36191. */
  36192. set: function (value) {
  36193. if (this._backFaceCulling === value) {
  36194. return;
  36195. }
  36196. this._backFaceCulling = value;
  36197. this.markAsDirty(Material.TextureDirtyFlag);
  36198. },
  36199. enumerable: true,
  36200. configurable: true
  36201. });
  36202. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36203. /**
  36204. * Gets a boolean indicating that current material needs to register RTT
  36205. */
  36206. get: function () {
  36207. return false;
  36208. },
  36209. enumerable: true,
  36210. configurable: true
  36211. });
  36212. Object.defineProperty(Material.prototype, "onDispose", {
  36213. /**
  36214. * Called during a dispose event
  36215. */
  36216. set: function (callback) {
  36217. if (this._onDisposeObserver) {
  36218. this.onDisposeObservable.remove(this._onDisposeObserver);
  36219. }
  36220. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36221. },
  36222. enumerable: true,
  36223. configurable: true
  36224. });
  36225. Object.defineProperty(Material.prototype, "onBindObservable", {
  36226. /**
  36227. * An event triggered when the material is bound
  36228. */
  36229. get: function () {
  36230. if (!this._onBindObservable) {
  36231. this._onBindObservable = new BABYLON.Observable();
  36232. }
  36233. return this._onBindObservable;
  36234. },
  36235. enumerable: true,
  36236. configurable: true
  36237. });
  36238. Object.defineProperty(Material.prototype, "onBind", {
  36239. /**
  36240. * Called during a bind event
  36241. */
  36242. set: function (callback) {
  36243. if (this._onBindObserver) {
  36244. this.onBindObservable.remove(this._onBindObserver);
  36245. }
  36246. this._onBindObserver = this.onBindObservable.add(callback);
  36247. },
  36248. enumerable: true,
  36249. configurable: true
  36250. });
  36251. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36252. /**
  36253. * An event triggered when the material is unbound
  36254. */
  36255. get: function () {
  36256. if (!this._onUnBindObservable) {
  36257. this._onUnBindObservable = new BABYLON.Observable();
  36258. }
  36259. return this._onUnBindObservable;
  36260. },
  36261. enumerable: true,
  36262. configurable: true
  36263. });
  36264. Object.defineProperty(Material.prototype, "alphaMode", {
  36265. /**
  36266. * Gets the value of the alpha mode
  36267. */
  36268. get: function () {
  36269. return this._alphaMode;
  36270. },
  36271. /**
  36272. * Sets the value of the alpha mode.
  36273. *
  36274. * | Value | Type | Description |
  36275. * | --- | --- | --- |
  36276. * | 0 | ALPHA_DISABLE | |
  36277. * | 1 | ALPHA_ADD | |
  36278. * | 2 | ALPHA_COMBINE | |
  36279. * | 3 | ALPHA_SUBTRACT | |
  36280. * | 4 | ALPHA_MULTIPLY | |
  36281. * | 5 | ALPHA_MAXIMIZED | |
  36282. * | 6 | ALPHA_ONEONE | |
  36283. * | 7 | ALPHA_PREMULTIPLIED | |
  36284. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36285. * | 9 | ALPHA_INTERPOLATE | |
  36286. * | 10 | ALPHA_SCREENMODE | |
  36287. *
  36288. */
  36289. set: function (value) {
  36290. if (this._alphaMode === value) {
  36291. return;
  36292. }
  36293. this._alphaMode = value;
  36294. this.markAsDirty(Material.TextureDirtyFlag);
  36295. },
  36296. enumerable: true,
  36297. configurable: true
  36298. });
  36299. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36300. /**
  36301. * Gets the depth pre-pass value
  36302. */
  36303. get: function () {
  36304. return this._needDepthPrePass;
  36305. },
  36306. /**
  36307. * Sets the need depth pre-pass value
  36308. */
  36309. set: function (value) {
  36310. if (this._needDepthPrePass === value) {
  36311. return;
  36312. }
  36313. this._needDepthPrePass = value;
  36314. if (this._needDepthPrePass) {
  36315. this.checkReadyOnEveryCall = true;
  36316. }
  36317. },
  36318. enumerable: true,
  36319. configurable: true
  36320. });
  36321. Object.defineProperty(Material.prototype, "fogEnabled", {
  36322. /**
  36323. * Gets the value of the fog enabled state
  36324. */
  36325. get: function () {
  36326. return this._fogEnabled;
  36327. },
  36328. /**
  36329. * Sets the state for enabling fog
  36330. */
  36331. set: function (value) {
  36332. if (this._fogEnabled === value) {
  36333. return;
  36334. }
  36335. this._fogEnabled = value;
  36336. this.markAsDirty(Material.MiscDirtyFlag);
  36337. },
  36338. enumerable: true,
  36339. configurable: true
  36340. });
  36341. Object.defineProperty(Material.prototype, "wireframe", {
  36342. /**
  36343. * Gets a value specifying if wireframe mode is enabled
  36344. */
  36345. get: function () {
  36346. switch (this._fillMode) {
  36347. case Material.WireFrameFillMode:
  36348. case Material.LineListDrawMode:
  36349. case Material.LineLoopDrawMode:
  36350. case Material.LineStripDrawMode:
  36351. return true;
  36352. }
  36353. return this._scene.forceWireframe;
  36354. },
  36355. /**
  36356. * Sets the state of wireframe mode
  36357. */
  36358. set: function (value) {
  36359. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36360. },
  36361. enumerable: true,
  36362. configurable: true
  36363. });
  36364. Object.defineProperty(Material.prototype, "pointsCloud", {
  36365. /**
  36366. * Gets the value specifying if point clouds are enabled
  36367. */
  36368. get: function () {
  36369. switch (this._fillMode) {
  36370. case Material.PointFillMode:
  36371. case Material.PointListDrawMode:
  36372. return true;
  36373. }
  36374. return this._scene.forcePointsCloud;
  36375. },
  36376. /**
  36377. * Sets the state of point cloud mode
  36378. */
  36379. set: function (value) {
  36380. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36381. },
  36382. enumerable: true,
  36383. configurable: true
  36384. });
  36385. Object.defineProperty(Material.prototype, "fillMode", {
  36386. /**
  36387. * Gets the material fill mode
  36388. */
  36389. get: function () {
  36390. return this._fillMode;
  36391. },
  36392. /**
  36393. * Sets the material fill mode
  36394. */
  36395. set: function (value) {
  36396. if (this._fillMode === value) {
  36397. return;
  36398. }
  36399. this._fillMode = value;
  36400. this.markAsDirty(Material.MiscDirtyFlag);
  36401. },
  36402. enumerable: true,
  36403. configurable: true
  36404. });
  36405. /**
  36406. * Returns a string representation of the current material
  36407. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36408. * @returns a string with material information
  36409. */
  36410. Material.prototype.toString = function (fullDetails) {
  36411. var ret = "Name: " + this.name;
  36412. if (fullDetails) {
  36413. }
  36414. return ret;
  36415. };
  36416. /**
  36417. * Gets the class name of the material
  36418. * @returns a string with the class name of the material
  36419. */
  36420. Material.prototype.getClassName = function () {
  36421. return "Material";
  36422. };
  36423. Object.defineProperty(Material.prototype, "isFrozen", {
  36424. /**
  36425. * Specifies if updates for the material been locked
  36426. */
  36427. get: function () {
  36428. return this.checkReadyOnlyOnce;
  36429. },
  36430. enumerable: true,
  36431. configurable: true
  36432. });
  36433. /**
  36434. * Locks updates for the material
  36435. */
  36436. Material.prototype.freeze = function () {
  36437. this.checkReadyOnlyOnce = true;
  36438. };
  36439. /**
  36440. * Unlocks updates for the material
  36441. */
  36442. Material.prototype.unfreeze = function () {
  36443. this.checkReadyOnlyOnce = false;
  36444. };
  36445. /**
  36446. * Specifies if the material is ready to be used
  36447. * @param mesh defines the mesh to check
  36448. * @param useInstances specifies if instances should be used
  36449. * @returns a boolean indicating if the material is ready to be used
  36450. */
  36451. Material.prototype.isReady = function (mesh, useInstances) {
  36452. return true;
  36453. };
  36454. /**
  36455. * Specifies that the submesh is ready to be used
  36456. * @param mesh defines the mesh to check
  36457. * @param subMesh defines which submesh to check
  36458. * @param useInstances specifies that instances should be used
  36459. * @returns a boolean indicating that the submesh is ready or not
  36460. */
  36461. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36462. return false;
  36463. };
  36464. /**
  36465. * Returns the material effect
  36466. * @returns the effect associated with the material
  36467. */
  36468. Material.prototype.getEffect = function () {
  36469. return this._effect;
  36470. };
  36471. /**
  36472. * Returns the current scene
  36473. * @returns a Scene
  36474. */
  36475. Material.prototype.getScene = function () {
  36476. return this._scene;
  36477. };
  36478. /**
  36479. * Specifies if the material will require alpha blending
  36480. * @returns a boolean specifying if alpha blending is needed
  36481. */
  36482. Material.prototype.needAlphaBlending = function () {
  36483. return (this.alpha < 1.0);
  36484. };
  36485. /**
  36486. * Specifies if the mesh will require alpha blending
  36487. * @param mesh defines the mesh to check
  36488. * @returns a boolean specifying if alpha blending is needed for the mesh
  36489. */
  36490. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36491. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36492. };
  36493. /**
  36494. * Specifies if this material should be rendered in alpha test mode
  36495. * @returns a boolean specifying if an alpha test is needed.
  36496. */
  36497. Material.prototype.needAlphaTesting = function () {
  36498. return false;
  36499. };
  36500. /**
  36501. * Gets the texture used for the alpha test
  36502. * @returns the texture to use for alpha testing
  36503. */
  36504. Material.prototype.getAlphaTestTexture = function () {
  36505. return null;
  36506. };
  36507. /**
  36508. * Marks the material to indicate that it needs to be re-calculated
  36509. */
  36510. Material.prototype.markDirty = function () {
  36511. this._wasPreviouslyReady = false;
  36512. };
  36513. /** @hidden */
  36514. Material.prototype._preBind = function (effect, overrideOrientation) {
  36515. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36516. var engine = this._scene.getEngine();
  36517. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36518. var reverse = orientation === Material.ClockWiseSideOrientation;
  36519. engine.enableEffect(effect ? effect : this._effect);
  36520. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36521. return reverse;
  36522. };
  36523. /**
  36524. * Binds the material to the mesh
  36525. * @param world defines the world transformation matrix
  36526. * @param mesh defines the mesh to bind the material to
  36527. */
  36528. Material.prototype.bind = function (world, mesh) {
  36529. };
  36530. /**
  36531. * Binds the submesh to the material
  36532. * @param world defines the world transformation matrix
  36533. * @param mesh defines the mesh containing the submesh
  36534. * @param subMesh defines the submesh to bind the material to
  36535. */
  36536. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36537. };
  36538. /**
  36539. * Binds the world matrix to the material
  36540. * @param world defines the world transformation matrix
  36541. */
  36542. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36543. };
  36544. /**
  36545. * Binds the scene's uniform buffer to the effect.
  36546. * @param effect defines the effect to bind to the scene uniform buffer
  36547. * @param sceneUbo defines the uniform buffer storing scene data
  36548. */
  36549. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36550. sceneUbo.bindToEffect(effect, "Scene");
  36551. };
  36552. /**
  36553. * Binds the view matrix to the effect
  36554. * @param effect defines the effect to bind the view matrix to
  36555. */
  36556. Material.prototype.bindView = function (effect) {
  36557. if (!this._useUBO) {
  36558. effect.setMatrix("view", this.getScene().getViewMatrix());
  36559. }
  36560. else {
  36561. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36562. }
  36563. };
  36564. /**
  36565. * Binds the view projection matrix to the effect
  36566. * @param effect defines the effect to bind the view projection matrix to
  36567. */
  36568. Material.prototype.bindViewProjection = function (effect) {
  36569. if (!this._useUBO) {
  36570. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36571. }
  36572. else {
  36573. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36574. }
  36575. };
  36576. /**
  36577. * Specifies if material alpha testing should be turned on for the mesh
  36578. * @param mesh defines the mesh to check
  36579. */
  36580. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36581. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36582. };
  36583. /**
  36584. * Processes to execute after binding the material to a mesh
  36585. * @param mesh defines the rendered mesh
  36586. */
  36587. Material.prototype._afterBind = function (mesh) {
  36588. this._scene._cachedMaterial = this;
  36589. if (mesh) {
  36590. this._scene._cachedVisibility = mesh.visibility;
  36591. }
  36592. else {
  36593. this._scene._cachedVisibility = 1;
  36594. }
  36595. if (this._onBindObservable && mesh) {
  36596. this._onBindObservable.notifyObservers(mesh);
  36597. }
  36598. if (this.disableDepthWrite) {
  36599. var engine = this._scene.getEngine();
  36600. this._cachedDepthWriteState = engine.getDepthWrite();
  36601. engine.setDepthWrite(false);
  36602. }
  36603. };
  36604. /**
  36605. * Unbinds the material from the mesh
  36606. */
  36607. Material.prototype.unbind = function () {
  36608. if (this._onUnBindObservable) {
  36609. this._onUnBindObservable.notifyObservers(this);
  36610. }
  36611. if (this.disableDepthWrite) {
  36612. var engine = this._scene.getEngine();
  36613. engine.setDepthWrite(this._cachedDepthWriteState);
  36614. }
  36615. };
  36616. /**
  36617. * Gets the active textures from the material
  36618. * @returns an array of textures
  36619. */
  36620. Material.prototype.getActiveTextures = function () {
  36621. return [];
  36622. };
  36623. /**
  36624. * Specifies if the material uses a texture
  36625. * @param texture defines the texture to check against the material
  36626. * @returns a boolean specifying if the material uses the texture
  36627. */
  36628. Material.prototype.hasTexture = function (texture) {
  36629. return false;
  36630. };
  36631. /**
  36632. * Makes a duplicate of the material, and gives it a new name
  36633. * @param name defines the new name for the duplicated material
  36634. * @returns the cloned material
  36635. */
  36636. Material.prototype.clone = function (name) {
  36637. return null;
  36638. };
  36639. /**
  36640. * Gets the meshes bound to the material
  36641. * @returns an array of meshes bound to the material
  36642. */
  36643. Material.prototype.getBindedMeshes = function () {
  36644. var result = new Array();
  36645. for (var index = 0; index < this._scene.meshes.length; index++) {
  36646. var mesh = this._scene.meshes[index];
  36647. if (mesh.material === this) {
  36648. result.push(mesh);
  36649. }
  36650. }
  36651. return result;
  36652. };
  36653. /**
  36654. * Force shader compilation
  36655. * @param mesh defines the mesh associated with this material
  36656. * @param onCompiled defines a function to execute once the material is compiled
  36657. * @param options defines the options to configure the compilation
  36658. */
  36659. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36660. var _this = this;
  36661. var localOptions = __assign({ clipPlane: false }, options);
  36662. var subMesh = new BABYLON.BaseSubMesh();
  36663. var scene = this.getScene();
  36664. var checkReady = function () {
  36665. if (!_this._scene || !_this._scene.getEngine()) {
  36666. return;
  36667. }
  36668. if (subMesh._materialDefines) {
  36669. subMesh._materialDefines._renderId = -1;
  36670. }
  36671. var clipPlaneState = scene.clipPlane;
  36672. if (localOptions.clipPlane) {
  36673. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36674. }
  36675. if (_this.storeEffectOnSubMeshes) {
  36676. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36677. if (onCompiled) {
  36678. onCompiled(_this);
  36679. }
  36680. }
  36681. else {
  36682. setTimeout(checkReady, 16);
  36683. }
  36684. }
  36685. else {
  36686. if (_this.isReady(mesh)) {
  36687. if (onCompiled) {
  36688. onCompiled(_this);
  36689. }
  36690. }
  36691. else {
  36692. setTimeout(checkReady, 16);
  36693. }
  36694. }
  36695. if (localOptions.clipPlane) {
  36696. scene.clipPlane = clipPlaneState;
  36697. }
  36698. };
  36699. checkReady();
  36700. };
  36701. /**
  36702. * Force shader compilation
  36703. * @param mesh defines the mesh that will use this material
  36704. * @param options defines additional options for compiling the shaders
  36705. * @returns a promise that resolves when the compilation completes
  36706. */
  36707. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36708. var _this = this;
  36709. return new Promise(function (resolve) {
  36710. _this.forceCompilation(mesh, function () {
  36711. resolve();
  36712. }, options);
  36713. });
  36714. };
  36715. /**
  36716. * Marks a define in the material to indicate that it needs to be re-computed
  36717. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36718. */
  36719. Material.prototype.markAsDirty = function (flag) {
  36720. if (flag & Material.TextureDirtyFlag) {
  36721. this._markAllSubMeshesAsTexturesDirty();
  36722. }
  36723. if (flag & Material.LightDirtyFlag) {
  36724. this._markAllSubMeshesAsLightsDirty();
  36725. }
  36726. if (flag & Material.FresnelDirtyFlag) {
  36727. this._markAllSubMeshesAsFresnelDirty();
  36728. }
  36729. if (flag & Material.AttributesDirtyFlag) {
  36730. this._markAllSubMeshesAsAttributesDirty();
  36731. }
  36732. if (flag & Material.MiscDirtyFlag) {
  36733. this._markAllSubMeshesAsMiscDirty();
  36734. }
  36735. this.getScene().resetCachedMaterial();
  36736. };
  36737. /**
  36738. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36739. * @param func defines a function which checks material defines against the submeshes
  36740. */
  36741. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36742. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36743. var mesh = _a[_i];
  36744. if (!mesh.subMeshes) {
  36745. continue;
  36746. }
  36747. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36748. var subMesh = _c[_b];
  36749. if (subMesh.getMaterial() !== this) {
  36750. continue;
  36751. }
  36752. if (!subMesh._materialDefines) {
  36753. continue;
  36754. }
  36755. func(subMesh._materialDefines);
  36756. }
  36757. }
  36758. };
  36759. /**
  36760. * Indicates that image processing needs to be re-calculated for all submeshes
  36761. */
  36762. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36763. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36764. };
  36765. /**
  36766. * Indicates that textures need to be re-calculated for all submeshes
  36767. */
  36768. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36769. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36770. };
  36771. /**
  36772. * Indicates that fresnel needs to be re-calculated for all submeshes
  36773. */
  36774. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36775. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36776. };
  36777. /**
  36778. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36779. */
  36780. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36781. this._markAllSubMeshesAsDirty(function (defines) {
  36782. defines.markAsFresnelDirty();
  36783. defines.markAsMiscDirty();
  36784. });
  36785. };
  36786. /**
  36787. * Indicates that lights need to be re-calculated for all submeshes
  36788. */
  36789. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36790. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36791. };
  36792. /**
  36793. * Indicates that attributes need to be re-calculated for all submeshes
  36794. */
  36795. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36796. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36797. };
  36798. /**
  36799. * Indicates that misc needs to be re-calculated for all submeshes
  36800. */
  36801. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36802. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36803. };
  36804. /**
  36805. * Indicates that textures and misc need to be re-calculated for all submeshes
  36806. */
  36807. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36808. this._markAllSubMeshesAsDirty(function (defines) {
  36809. defines.markAsTexturesDirty();
  36810. defines.markAsMiscDirty();
  36811. });
  36812. };
  36813. /**
  36814. * Disposes the material
  36815. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36816. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36817. */
  36818. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36819. // Animations
  36820. this.getScene().stopAnimation(this);
  36821. this.getScene().freeProcessedMaterials();
  36822. // Remove from scene
  36823. var index = this._scene.materials.indexOf(this);
  36824. if (index >= 0) {
  36825. this._scene.materials.splice(index, 1);
  36826. }
  36827. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36828. // Remove from meshes
  36829. for (index = 0; index < this._scene.meshes.length; index++) {
  36830. var mesh = this._scene.meshes[index];
  36831. if (mesh.material === this) {
  36832. mesh.material = null;
  36833. if (mesh.geometry) {
  36834. var geometry = (mesh.geometry);
  36835. if (this.storeEffectOnSubMeshes) {
  36836. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36837. var subMesh = _a[_i];
  36838. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36839. if (forceDisposeEffect && subMesh._materialEffect) {
  36840. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36841. }
  36842. }
  36843. }
  36844. else {
  36845. geometry._releaseVertexArrayObject(this._effect);
  36846. }
  36847. }
  36848. }
  36849. }
  36850. this._uniformBuffer.dispose();
  36851. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36852. if (forceDisposeEffect && this._effect) {
  36853. if (!this.storeEffectOnSubMeshes) {
  36854. this._scene.getEngine()._releaseEffect(this._effect);
  36855. }
  36856. this._effect = null;
  36857. }
  36858. // Callback
  36859. this.onDisposeObservable.notifyObservers(this);
  36860. this.onDisposeObservable.clear();
  36861. if (this._onBindObservable) {
  36862. this._onBindObservable.clear();
  36863. }
  36864. if (this._onUnBindObservable) {
  36865. this._onUnBindObservable.clear();
  36866. }
  36867. };
  36868. /**
  36869. * Serializes this material
  36870. * @returns the serialized material object
  36871. */
  36872. Material.prototype.serialize = function () {
  36873. return BABYLON.SerializationHelper.Serialize(this);
  36874. };
  36875. /**
  36876. * Creates a MultiMaterial from parsed MultiMaterial data.
  36877. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36878. * @param scene defines the hosting scene
  36879. * @returns a new MultiMaterial
  36880. */
  36881. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36882. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36883. multiMaterial.id = parsedMultiMaterial.id;
  36884. if (BABYLON.Tags) {
  36885. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36886. }
  36887. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36888. var subMatId = parsedMultiMaterial.materials[matIndex];
  36889. if (subMatId) {
  36890. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36891. }
  36892. else {
  36893. multiMaterial.subMaterials.push(null);
  36894. }
  36895. }
  36896. return multiMaterial;
  36897. };
  36898. /**
  36899. * Creates a material from parsed material data
  36900. * @param parsedMaterial defines parsed material data
  36901. * @param scene defines the hosting scene
  36902. * @param rootUrl defines the root URL to use to load textures
  36903. * @returns a new material
  36904. */
  36905. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36906. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36907. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36908. }
  36909. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36910. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36911. if (!BABYLON.LegacyPBRMaterial) {
  36912. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36913. return;
  36914. }
  36915. }
  36916. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36917. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36918. };
  36919. // Triangle views
  36920. Material._TriangleFillMode = 0;
  36921. Material._WireFrameFillMode = 1;
  36922. Material._PointFillMode = 2;
  36923. // Draw modes
  36924. Material._PointListDrawMode = 3;
  36925. Material._LineListDrawMode = 4;
  36926. Material._LineLoopDrawMode = 5;
  36927. Material._LineStripDrawMode = 6;
  36928. Material._TriangleStripDrawMode = 7;
  36929. Material._TriangleFanDrawMode = 8;
  36930. /**
  36931. * Stores the clock-wise side orientation
  36932. */
  36933. Material._ClockWiseSideOrientation = 0;
  36934. /**
  36935. * Stores the counter clock-wise side orientation
  36936. */
  36937. Material._CounterClockWiseSideOrientation = 1;
  36938. /**
  36939. * The dirty texture flag value
  36940. */
  36941. Material.TextureDirtyFlag = 1;
  36942. /**
  36943. * The dirty light flag value
  36944. */
  36945. Material.LightDirtyFlag = 2;
  36946. /**
  36947. * The dirty fresnel flag value
  36948. */
  36949. Material.FresnelDirtyFlag = 4;
  36950. /**
  36951. * The dirty attribute flag value
  36952. */
  36953. Material.AttributesDirtyFlag = 8;
  36954. /**
  36955. * The dirty misc flag value
  36956. */
  36957. Material.MiscDirtyFlag = 16;
  36958. /**
  36959. * The all dirty flag value
  36960. */
  36961. Material.AllDirtyFlag = 31;
  36962. __decorate([
  36963. BABYLON.serialize()
  36964. ], Material.prototype, "id", void 0);
  36965. __decorate([
  36966. BABYLON.serialize()
  36967. ], Material.prototype, "uniqueId", void 0);
  36968. __decorate([
  36969. BABYLON.serialize()
  36970. ], Material.prototype, "name", void 0);
  36971. __decorate([
  36972. BABYLON.serialize()
  36973. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36974. __decorate([
  36975. BABYLON.serialize()
  36976. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36977. __decorate([
  36978. BABYLON.serialize()
  36979. ], Material.prototype, "state", void 0);
  36980. __decorate([
  36981. BABYLON.serialize("alpha")
  36982. ], Material.prototype, "_alpha", void 0);
  36983. __decorate([
  36984. BABYLON.serialize("backFaceCulling")
  36985. ], Material.prototype, "_backFaceCulling", void 0);
  36986. __decorate([
  36987. BABYLON.serialize()
  36988. ], Material.prototype, "sideOrientation", void 0);
  36989. __decorate([
  36990. BABYLON.serialize("alphaMode")
  36991. ], Material.prototype, "_alphaMode", void 0);
  36992. __decorate([
  36993. BABYLON.serialize()
  36994. ], Material.prototype, "_needDepthPrePass", void 0);
  36995. __decorate([
  36996. BABYLON.serialize()
  36997. ], Material.prototype, "disableDepthWrite", void 0);
  36998. __decorate([
  36999. BABYLON.serialize()
  37000. ], Material.prototype, "forceDepthWrite", void 0);
  37001. __decorate([
  37002. BABYLON.serialize()
  37003. ], Material.prototype, "separateCullingPass", void 0);
  37004. __decorate([
  37005. BABYLON.serialize("fogEnabled")
  37006. ], Material.prototype, "_fogEnabled", void 0);
  37007. __decorate([
  37008. BABYLON.serialize()
  37009. ], Material.prototype, "pointSize", void 0);
  37010. __decorate([
  37011. BABYLON.serialize()
  37012. ], Material.prototype, "zOffset", void 0);
  37013. __decorate([
  37014. BABYLON.serialize()
  37015. ], Material.prototype, "wireframe", null);
  37016. __decorate([
  37017. BABYLON.serialize()
  37018. ], Material.prototype, "pointsCloud", null);
  37019. __decorate([
  37020. BABYLON.serialize()
  37021. ], Material.prototype, "fillMode", null);
  37022. return Material;
  37023. }());
  37024. BABYLON.Material = Material;
  37025. })(BABYLON || (BABYLON = {}));
  37026. //# sourceMappingURL=babylon.material.js.map
  37027. var BABYLON;
  37028. (function (BABYLON) {
  37029. /**
  37030. * Uniform buffer objects.
  37031. *
  37032. * Handles blocks of uniform on the GPU.
  37033. *
  37034. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37035. *
  37036. * For more information, please refer to :
  37037. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37038. */
  37039. var UniformBuffer = /** @class */ (function () {
  37040. /**
  37041. * Instantiates a new Uniform buffer objects.
  37042. *
  37043. * Handles blocks of uniform on the GPU.
  37044. *
  37045. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37046. *
  37047. * For more information, please refer to :
  37048. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37049. * @param engine Define the engine the buffer is associated with
  37050. * @param data Define the data contained in the buffer
  37051. * @param dynamic Define if the buffer is updatable
  37052. */
  37053. function UniformBuffer(engine, data, dynamic) {
  37054. this._engine = engine;
  37055. this._noUBO = !engine.supportsUniformBuffers;
  37056. this._dynamic = dynamic;
  37057. this._data = data || [];
  37058. this._uniformLocations = {};
  37059. this._uniformSizes = {};
  37060. this._uniformLocationPointer = 0;
  37061. this._needSync = false;
  37062. if (this._noUBO) {
  37063. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37064. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37065. this.updateFloat = this._updateFloatForEffect;
  37066. this.updateFloat2 = this._updateFloat2ForEffect;
  37067. this.updateFloat3 = this._updateFloat3ForEffect;
  37068. this.updateFloat4 = this._updateFloat4ForEffect;
  37069. this.updateMatrix = this._updateMatrixForEffect;
  37070. this.updateVector3 = this._updateVector3ForEffect;
  37071. this.updateVector4 = this._updateVector4ForEffect;
  37072. this.updateColor3 = this._updateColor3ForEffect;
  37073. this.updateColor4 = this._updateColor4ForEffect;
  37074. }
  37075. else {
  37076. this._engine._uniformBuffers.push(this);
  37077. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37078. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37079. this.updateFloat = this._updateFloatForUniform;
  37080. this.updateFloat2 = this._updateFloat2ForUniform;
  37081. this.updateFloat3 = this._updateFloat3ForUniform;
  37082. this.updateFloat4 = this._updateFloat4ForUniform;
  37083. this.updateMatrix = this._updateMatrixForUniform;
  37084. this.updateVector3 = this._updateVector3ForUniform;
  37085. this.updateVector4 = this._updateVector4ForUniform;
  37086. this.updateColor3 = this._updateColor3ForUniform;
  37087. this.updateColor4 = this._updateColor4ForUniform;
  37088. }
  37089. }
  37090. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37091. /**
  37092. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37093. * or just falling back on setUniformXXX calls.
  37094. */
  37095. get: function () {
  37096. return !this._noUBO;
  37097. },
  37098. enumerable: true,
  37099. configurable: true
  37100. });
  37101. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37102. /**
  37103. * Indicates if the WebGL underlying uniform buffer is in sync
  37104. * with the javascript cache data.
  37105. */
  37106. get: function () {
  37107. return !this._needSync;
  37108. },
  37109. enumerable: true,
  37110. configurable: true
  37111. });
  37112. /**
  37113. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37114. * Also, a dynamic UniformBuffer will disable cache verification and always
  37115. * update the underlying WebGL uniform buffer to the GPU.
  37116. * @returns if Dynamic, otherwise false
  37117. */
  37118. UniformBuffer.prototype.isDynamic = function () {
  37119. return this._dynamic !== undefined;
  37120. };
  37121. /**
  37122. * The data cache on JS side.
  37123. * @returns the underlying data as a float array
  37124. */
  37125. UniformBuffer.prototype.getData = function () {
  37126. return this._bufferData;
  37127. };
  37128. /**
  37129. * The underlying WebGL Uniform buffer.
  37130. * @returns the webgl buffer
  37131. */
  37132. UniformBuffer.prototype.getBuffer = function () {
  37133. return this._buffer;
  37134. };
  37135. /**
  37136. * std140 layout specifies how to align data within an UBO structure.
  37137. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37138. * for specs.
  37139. */
  37140. UniformBuffer.prototype._fillAlignment = function (size) {
  37141. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37142. // and 4x4 matrices
  37143. // TODO : change if other types are used
  37144. var alignment;
  37145. if (size <= 2) {
  37146. alignment = size;
  37147. }
  37148. else {
  37149. alignment = 4;
  37150. }
  37151. if ((this._uniformLocationPointer % alignment) !== 0) {
  37152. var oldPointer = this._uniformLocationPointer;
  37153. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37154. var diff = this._uniformLocationPointer - oldPointer;
  37155. for (var i = 0; i < diff; i++) {
  37156. this._data.push(0);
  37157. }
  37158. }
  37159. };
  37160. /**
  37161. * Adds an uniform in the buffer.
  37162. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37163. * for the layout to be correct !
  37164. * @param name Name of the uniform, as used in the uniform block in the shader.
  37165. * @param size Data size, or data directly.
  37166. */
  37167. UniformBuffer.prototype.addUniform = function (name, size) {
  37168. if (this._noUBO) {
  37169. return;
  37170. }
  37171. if (this._uniformLocations[name] !== undefined) {
  37172. // Already existing uniform
  37173. return;
  37174. }
  37175. // This function must be called in the order of the shader layout !
  37176. // size can be the size of the uniform, or data directly
  37177. var data;
  37178. if (size instanceof Array) {
  37179. data = size;
  37180. size = data.length;
  37181. }
  37182. else {
  37183. size = size;
  37184. data = [];
  37185. // Fill with zeros
  37186. for (var i = 0; i < size; i++) {
  37187. data.push(0);
  37188. }
  37189. }
  37190. this._fillAlignment(size);
  37191. this._uniformSizes[name] = size;
  37192. this._uniformLocations[name] = this._uniformLocationPointer;
  37193. this._uniformLocationPointer += size;
  37194. for (var i = 0; i < size; i++) {
  37195. this._data.push(data[i]);
  37196. }
  37197. this._needSync = true;
  37198. };
  37199. /**
  37200. * Adds a Matrix 4x4 to the uniform buffer.
  37201. * @param name Name of the uniform, as used in the uniform block in the shader.
  37202. * @param mat A 4x4 matrix.
  37203. */
  37204. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37205. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37206. };
  37207. /**
  37208. * Adds a vec2 to the uniform buffer.
  37209. * @param name Name of the uniform, as used in the uniform block in the shader.
  37210. * @param x Define the x component value of the vec2
  37211. * @param y Define the y component value of the vec2
  37212. */
  37213. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37214. var temp = [x, y];
  37215. this.addUniform(name, temp);
  37216. };
  37217. /**
  37218. * Adds a vec3 to the uniform buffer.
  37219. * @param name Name of the uniform, as used in the uniform block in the shader.
  37220. * @param x Define the x component value of the vec3
  37221. * @param y Define the y component value of the vec3
  37222. * @param z Define the z component value of the vec3
  37223. */
  37224. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37225. var temp = [x, y, z];
  37226. this.addUniform(name, temp);
  37227. };
  37228. /**
  37229. * Adds a vec3 to the uniform buffer.
  37230. * @param name Name of the uniform, as used in the uniform block in the shader.
  37231. * @param color Define the vec3 from a Color
  37232. */
  37233. UniformBuffer.prototype.addColor3 = function (name, color) {
  37234. var temp = new Array();
  37235. color.toArray(temp);
  37236. this.addUniform(name, temp);
  37237. };
  37238. /**
  37239. * Adds a vec4 to the uniform buffer.
  37240. * @param name Name of the uniform, as used in the uniform block in the shader.
  37241. * @param color Define the rgb components from a Color
  37242. * @param alpha Define the a component of the vec4
  37243. */
  37244. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37245. var temp = new Array();
  37246. color.toArray(temp);
  37247. temp.push(alpha);
  37248. this.addUniform(name, temp);
  37249. };
  37250. /**
  37251. * Adds a vec3 to the uniform buffer.
  37252. * @param name Name of the uniform, as used in the uniform block in the shader.
  37253. * @param vector Define the vec3 components from a Vector
  37254. */
  37255. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37256. var temp = new Array();
  37257. vector.toArray(temp);
  37258. this.addUniform(name, temp);
  37259. };
  37260. /**
  37261. * Adds a Matrix 3x3 to the uniform buffer.
  37262. * @param name Name of the uniform, as used in the uniform block in the shader.
  37263. */
  37264. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37265. this.addUniform(name, 12);
  37266. };
  37267. /**
  37268. * Adds a Matrix 2x2 to the uniform buffer.
  37269. * @param name Name of the uniform, as used in the uniform block in the shader.
  37270. */
  37271. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37272. this.addUniform(name, 8);
  37273. };
  37274. /**
  37275. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37276. */
  37277. UniformBuffer.prototype.create = function () {
  37278. if (this._noUBO) {
  37279. return;
  37280. }
  37281. if (this._buffer) {
  37282. return; // nothing to do
  37283. }
  37284. // See spec, alignment must be filled as a vec4
  37285. this._fillAlignment(4);
  37286. this._bufferData = new Float32Array(this._data);
  37287. this._rebuild();
  37288. this._needSync = true;
  37289. };
  37290. /** @hidden */
  37291. UniformBuffer.prototype._rebuild = function () {
  37292. if (this._noUBO) {
  37293. return;
  37294. }
  37295. if (this._dynamic) {
  37296. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37297. }
  37298. else {
  37299. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37300. }
  37301. };
  37302. /**
  37303. * Updates the WebGL Uniform Buffer on the GPU.
  37304. * If the `dynamic` flag is set to true, no cache comparison is done.
  37305. * Otherwise, the buffer will be updated only if the cache differs.
  37306. */
  37307. UniformBuffer.prototype.update = function () {
  37308. if (!this._buffer) {
  37309. this.create();
  37310. return;
  37311. }
  37312. if (!this._dynamic && !this._needSync) {
  37313. return;
  37314. }
  37315. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37316. this._needSync = false;
  37317. };
  37318. /**
  37319. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37320. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37321. * @param data Define the flattened data
  37322. * @param size Define the size of the data.
  37323. */
  37324. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37325. var location = this._uniformLocations[uniformName];
  37326. if (location === undefined) {
  37327. if (this._buffer) {
  37328. // Cannot add an uniform if the buffer is already created
  37329. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37330. return;
  37331. }
  37332. this.addUniform(uniformName, size);
  37333. location = this._uniformLocations[uniformName];
  37334. }
  37335. if (!this._buffer) {
  37336. this.create();
  37337. }
  37338. if (!this._dynamic) {
  37339. // Cache for static uniform buffers
  37340. var changed = false;
  37341. for (var i = 0; i < size; i++) {
  37342. if (this._bufferData[location + i] !== data[i]) {
  37343. changed = true;
  37344. this._bufferData[location + i] = data[i];
  37345. }
  37346. }
  37347. this._needSync = this._needSync || changed;
  37348. }
  37349. else {
  37350. // No cache for dynamic
  37351. for (var i = 0; i < size; i++) {
  37352. this._bufferData[location + i] = data[i];
  37353. }
  37354. }
  37355. };
  37356. // Update methods
  37357. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37358. // To match std140, matrix must be realigned
  37359. for (var i = 0; i < 3; i++) {
  37360. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37361. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37362. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37363. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37364. }
  37365. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37366. };
  37367. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37368. this._currentEffect.setMatrix3x3(name, matrix);
  37369. };
  37370. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37371. this._currentEffect.setMatrix2x2(name, matrix);
  37372. };
  37373. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37374. // To match std140, matrix must be realigned
  37375. for (var i = 0; i < 2; i++) {
  37376. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37377. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37378. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37379. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37380. }
  37381. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37382. };
  37383. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37384. this._currentEffect.setFloat(name, x);
  37385. };
  37386. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37387. UniformBuffer._tempBuffer[0] = x;
  37388. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37389. };
  37390. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37391. if (suffix === void 0) { suffix = ""; }
  37392. this._currentEffect.setFloat2(name + suffix, x, y);
  37393. };
  37394. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37395. if (suffix === void 0) { suffix = ""; }
  37396. UniformBuffer._tempBuffer[0] = x;
  37397. UniformBuffer._tempBuffer[1] = y;
  37398. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37399. };
  37400. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37401. if (suffix === void 0) { suffix = ""; }
  37402. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37403. };
  37404. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37405. if (suffix === void 0) { suffix = ""; }
  37406. UniformBuffer._tempBuffer[0] = x;
  37407. UniformBuffer._tempBuffer[1] = y;
  37408. UniformBuffer._tempBuffer[2] = z;
  37409. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37410. };
  37411. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37412. if (suffix === void 0) { suffix = ""; }
  37413. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37414. };
  37415. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37416. if (suffix === void 0) { suffix = ""; }
  37417. UniformBuffer._tempBuffer[0] = x;
  37418. UniformBuffer._tempBuffer[1] = y;
  37419. UniformBuffer._tempBuffer[2] = z;
  37420. UniformBuffer._tempBuffer[3] = w;
  37421. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37422. };
  37423. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37424. this._currentEffect.setMatrix(name, mat);
  37425. };
  37426. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37427. this.updateUniform(name, mat.toArray(), 16);
  37428. };
  37429. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37430. this._currentEffect.setVector3(name, vector);
  37431. };
  37432. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37433. vector.toArray(UniformBuffer._tempBuffer);
  37434. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37435. };
  37436. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37437. this._currentEffect.setVector4(name, vector);
  37438. };
  37439. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37440. vector.toArray(UniformBuffer._tempBuffer);
  37441. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37442. };
  37443. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37444. if (suffix === void 0) { suffix = ""; }
  37445. this._currentEffect.setColor3(name + suffix, color);
  37446. };
  37447. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37448. if (suffix === void 0) { suffix = ""; }
  37449. color.toArray(UniformBuffer._tempBuffer);
  37450. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37451. };
  37452. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37453. if (suffix === void 0) { suffix = ""; }
  37454. this._currentEffect.setColor4(name + suffix, color, alpha);
  37455. };
  37456. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37457. if (suffix === void 0) { suffix = ""; }
  37458. color.toArray(UniformBuffer._tempBuffer);
  37459. UniformBuffer._tempBuffer[3] = alpha;
  37460. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37461. };
  37462. /**
  37463. * Sets a sampler uniform on the effect.
  37464. * @param name Define the name of the sampler.
  37465. * @param texture Define the texture to set in the sampler
  37466. */
  37467. UniformBuffer.prototype.setTexture = function (name, texture) {
  37468. this._currentEffect.setTexture(name, texture);
  37469. };
  37470. /**
  37471. * Directly updates the value of the uniform in the cache AND on the GPU.
  37472. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37473. * @param data Define the flattened data
  37474. */
  37475. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37476. this.updateUniform(uniformName, data, data.length);
  37477. this.update();
  37478. };
  37479. /**
  37480. * Binds this uniform buffer to an effect.
  37481. * @param effect Define the effect to bind the buffer to
  37482. * @param name Name of the uniform block in the shader.
  37483. */
  37484. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37485. this._currentEffect = effect;
  37486. if (this._noUBO || !this._buffer) {
  37487. return;
  37488. }
  37489. effect.bindUniformBuffer(this._buffer, name);
  37490. };
  37491. /**
  37492. * Disposes the uniform buffer.
  37493. */
  37494. UniformBuffer.prototype.dispose = function () {
  37495. if (this._noUBO) {
  37496. return;
  37497. }
  37498. var index = this._engine._uniformBuffers.indexOf(this);
  37499. if (index !== -1) {
  37500. this._engine._uniformBuffers.splice(index, 1);
  37501. }
  37502. if (!this._buffer) {
  37503. return;
  37504. }
  37505. if (this._engine._releaseBuffer(this._buffer)) {
  37506. this._buffer = null;
  37507. }
  37508. };
  37509. // Pool for avoiding memory leaks
  37510. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37511. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37512. return UniformBuffer;
  37513. }());
  37514. BABYLON.UniformBuffer = UniformBuffer;
  37515. })(BABYLON || (BABYLON = {}));
  37516. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37517. var BABYLON;
  37518. (function (BABYLON) {
  37519. /**
  37520. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37521. */
  37522. var VertexData = /** @class */ (function () {
  37523. function VertexData() {
  37524. }
  37525. /**
  37526. * Uses the passed data array to set the set the values for the specified kind of data
  37527. * @param data a linear array of floating numbers
  37528. * @param kind the type of data that is being set, eg positions, colors etc
  37529. */
  37530. VertexData.prototype.set = function (data, kind) {
  37531. switch (kind) {
  37532. case BABYLON.VertexBuffer.PositionKind:
  37533. this.positions = data;
  37534. break;
  37535. case BABYLON.VertexBuffer.NormalKind:
  37536. this.normals = data;
  37537. break;
  37538. case BABYLON.VertexBuffer.TangentKind:
  37539. this.tangents = data;
  37540. break;
  37541. case BABYLON.VertexBuffer.UVKind:
  37542. this.uvs = data;
  37543. break;
  37544. case BABYLON.VertexBuffer.UV2Kind:
  37545. this.uvs2 = data;
  37546. break;
  37547. case BABYLON.VertexBuffer.UV3Kind:
  37548. this.uvs3 = data;
  37549. break;
  37550. case BABYLON.VertexBuffer.UV4Kind:
  37551. this.uvs4 = data;
  37552. break;
  37553. case BABYLON.VertexBuffer.UV5Kind:
  37554. this.uvs5 = data;
  37555. break;
  37556. case BABYLON.VertexBuffer.UV6Kind:
  37557. this.uvs6 = data;
  37558. break;
  37559. case BABYLON.VertexBuffer.ColorKind:
  37560. this.colors = data;
  37561. break;
  37562. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37563. this.matricesIndices = data;
  37564. break;
  37565. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37566. this.matricesWeights = data;
  37567. break;
  37568. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37569. this.matricesIndicesExtra = data;
  37570. break;
  37571. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37572. this.matricesWeightsExtra = data;
  37573. break;
  37574. }
  37575. };
  37576. /**
  37577. * Associates the vertexData to the passed Mesh.
  37578. * Sets it as updatable or not (default `false`)
  37579. * @param mesh the mesh the vertexData is applied to
  37580. * @param updatable when used and having the value true allows new data to update the vertexData
  37581. * @returns the VertexData
  37582. */
  37583. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37584. this._applyTo(mesh, updatable);
  37585. return this;
  37586. };
  37587. /**
  37588. * Associates the vertexData to the passed Geometry.
  37589. * Sets it as updatable or not (default `false`)
  37590. * @param geometry the geometry the vertexData is applied to
  37591. * @param updatable when used and having the value true allows new data to update the vertexData
  37592. * @returns VertexData
  37593. */
  37594. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37595. this._applyTo(geometry, updatable);
  37596. return this;
  37597. };
  37598. /**
  37599. * Updates the associated mesh
  37600. * @param mesh the mesh to be updated
  37601. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37602. * @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
  37603. * @returns VertexData
  37604. */
  37605. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37606. this._update(mesh);
  37607. return this;
  37608. };
  37609. /**
  37610. * Updates the associated geometry
  37611. * @param geometry the geometry to be updated
  37612. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37613. * @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
  37614. * @returns VertexData.
  37615. */
  37616. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37617. this._update(geometry);
  37618. return this;
  37619. };
  37620. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37621. if (updatable === void 0) { updatable = false; }
  37622. if (this.positions) {
  37623. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37624. }
  37625. if (this.normals) {
  37626. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37627. }
  37628. if (this.tangents) {
  37629. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37630. }
  37631. if (this.uvs) {
  37632. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37633. }
  37634. if (this.uvs2) {
  37635. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37636. }
  37637. if (this.uvs3) {
  37638. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37639. }
  37640. if (this.uvs4) {
  37641. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37642. }
  37643. if (this.uvs5) {
  37644. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37645. }
  37646. if (this.uvs6) {
  37647. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37648. }
  37649. if (this.colors) {
  37650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37651. }
  37652. if (this.matricesIndices) {
  37653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37654. }
  37655. if (this.matricesWeights) {
  37656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37657. }
  37658. if (this.matricesIndicesExtra) {
  37659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37660. }
  37661. if (this.matricesWeightsExtra) {
  37662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37663. }
  37664. if (this.indices) {
  37665. meshOrGeometry.setIndices(this.indices, null, updatable);
  37666. }
  37667. else {
  37668. meshOrGeometry.setIndices([], null);
  37669. }
  37670. return this;
  37671. };
  37672. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37673. if (this.positions) {
  37674. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37675. }
  37676. if (this.normals) {
  37677. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37678. }
  37679. if (this.tangents) {
  37680. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37681. }
  37682. if (this.uvs) {
  37683. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37684. }
  37685. if (this.uvs2) {
  37686. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37687. }
  37688. if (this.uvs3) {
  37689. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37690. }
  37691. if (this.uvs4) {
  37692. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37693. }
  37694. if (this.uvs5) {
  37695. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37696. }
  37697. if (this.uvs6) {
  37698. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37699. }
  37700. if (this.colors) {
  37701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37702. }
  37703. if (this.matricesIndices) {
  37704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37705. }
  37706. if (this.matricesWeights) {
  37707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37708. }
  37709. if (this.matricesIndicesExtra) {
  37710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37711. }
  37712. if (this.matricesWeightsExtra) {
  37713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37714. }
  37715. if (this.indices) {
  37716. meshOrGeometry.setIndices(this.indices, null);
  37717. }
  37718. return this;
  37719. };
  37720. /**
  37721. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37722. * @param matrix the transforming matrix
  37723. * @returns the VertexData
  37724. */
  37725. VertexData.prototype.transform = function (matrix) {
  37726. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37727. var transformed = BABYLON.Vector3.Zero();
  37728. var index;
  37729. if (this.positions) {
  37730. var position = BABYLON.Vector3.Zero();
  37731. for (index = 0; index < this.positions.length; index += 3) {
  37732. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37733. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37734. this.positions[index] = transformed.x;
  37735. this.positions[index + 1] = transformed.y;
  37736. this.positions[index + 2] = transformed.z;
  37737. }
  37738. }
  37739. if (this.normals) {
  37740. var normal = BABYLON.Vector3.Zero();
  37741. for (index = 0; index < this.normals.length; index += 3) {
  37742. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37743. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37744. this.normals[index] = transformed.x;
  37745. this.normals[index + 1] = transformed.y;
  37746. this.normals[index + 2] = transformed.z;
  37747. }
  37748. }
  37749. if (this.tangents) {
  37750. var tangent = BABYLON.Vector4.Zero();
  37751. var tangentTransformed = BABYLON.Vector4.Zero();
  37752. for (index = 0; index < this.tangents.length; index += 4) {
  37753. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37754. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37755. this.tangents[index] = tangentTransformed.x;
  37756. this.tangents[index + 1] = tangentTransformed.y;
  37757. this.tangents[index + 2] = tangentTransformed.z;
  37758. this.tangents[index + 3] = tangentTransformed.w;
  37759. }
  37760. }
  37761. if (flip && this.indices) {
  37762. for (index = 0; index < this.indices.length; index += 3) {
  37763. var tmp = this.indices[index + 1];
  37764. this.indices[index + 1] = this.indices[index + 2];
  37765. this.indices[index + 2] = tmp;
  37766. }
  37767. }
  37768. return this;
  37769. };
  37770. /**
  37771. * Merges the passed VertexData into the current one
  37772. * @param other the VertexData to be merged into the current one
  37773. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37774. * @returns the modified VertexData
  37775. */
  37776. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37777. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37778. this._validate();
  37779. other._validate();
  37780. if (!this.normals !== !other.normals ||
  37781. !this.tangents !== !other.tangents ||
  37782. !this.uvs !== !other.uvs ||
  37783. !this.uvs2 !== !other.uvs2 ||
  37784. !this.uvs3 !== !other.uvs3 ||
  37785. !this.uvs4 !== !other.uvs4 ||
  37786. !this.uvs5 !== !other.uvs5 ||
  37787. !this.uvs6 !== !other.uvs6 ||
  37788. !this.colors !== !other.colors ||
  37789. !this.matricesIndices !== !other.matricesIndices ||
  37790. !this.matricesWeights !== !other.matricesWeights ||
  37791. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37792. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37793. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37794. }
  37795. if (other.indices) {
  37796. if (!this.indices) {
  37797. this.indices = [];
  37798. }
  37799. var offset = this.positions ? this.positions.length / 3 : 0;
  37800. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37801. if (isSrcTypedArray) {
  37802. var len = this.indices.length + other.indices.length;
  37803. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37804. temp.set(this.indices);
  37805. var decal = this.indices.length;
  37806. for (var index = 0; index < other.indices.length; index++) {
  37807. temp[decal + index] = other.indices[index] + offset;
  37808. }
  37809. this.indices = temp;
  37810. }
  37811. else {
  37812. for (var index = 0; index < other.indices.length; index++) {
  37813. this.indices.push(other.indices[index] + offset);
  37814. }
  37815. }
  37816. }
  37817. this.positions = this._mergeElement(this.positions, other.positions);
  37818. this.normals = this._mergeElement(this.normals, other.normals);
  37819. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37820. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37821. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37822. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37823. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37824. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37825. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37826. this.colors = this._mergeElement(this.colors, other.colors);
  37827. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37828. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37829. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37830. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37831. return this;
  37832. };
  37833. VertexData.prototype._mergeElement = function (source, other) {
  37834. if (!source) {
  37835. return other;
  37836. }
  37837. if (!other) {
  37838. return source;
  37839. }
  37840. var len = other.length + source.length;
  37841. var isSrcTypedArray = source instanceof Float32Array;
  37842. var isOthTypedArray = other instanceof Float32Array;
  37843. // use non-loop method when the source is Float32Array
  37844. if (isSrcTypedArray) {
  37845. var ret32 = new Float32Array(len);
  37846. ret32.set(source);
  37847. ret32.set(other, source.length);
  37848. return ret32;
  37849. // source is number[], when other is also use concat
  37850. }
  37851. else if (!isOthTypedArray) {
  37852. return source.concat(other);
  37853. // source is a number[], but other is a Float32Array, loop required
  37854. }
  37855. else {
  37856. var ret = source.slice(0); // copy source to a separate array
  37857. for (var i = 0, len = other.length; i < len; i++) {
  37858. ret.push(other[i]);
  37859. }
  37860. return ret;
  37861. }
  37862. };
  37863. VertexData.prototype._validate = function () {
  37864. if (!this.positions) {
  37865. throw new Error("Positions are required");
  37866. }
  37867. var getElementCount = function (kind, values) {
  37868. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37869. if ((values.length % stride) !== 0) {
  37870. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37871. }
  37872. return values.length / stride;
  37873. };
  37874. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37875. var validateElementCount = function (kind, values) {
  37876. var elementCount = getElementCount(kind, values);
  37877. if (elementCount !== positionsElementCount) {
  37878. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37879. }
  37880. };
  37881. if (this.normals)
  37882. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37883. if (this.tangents)
  37884. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37885. if (this.uvs)
  37886. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37887. if (this.uvs2)
  37888. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37889. if (this.uvs3)
  37890. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37891. if (this.uvs4)
  37892. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37893. if (this.uvs5)
  37894. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37895. if (this.uvs6)
  37896. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37897. if (this.colors)
  37898. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37899. if (this.matricesIndices)
  37900. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37901. if (this.matricesWeights)
  37902. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37903. if (this.matricesIndicesExtra)
  37904. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37905. if (this.matricesWeightsExtra)
  37906. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37907. };
  37908. /**
  37909. * Serializes the VertexData
  37910. * @returns a serialized object
  37911. */
  37912. VertexData.prototype.serialize = function () {
  37913. var serializationObject = this.serialize();
  37914. if (this.positions) {
  37915. serializationObject.positions = this.positions;
  37916. }
  37917. if (this.normals) {
  37918. serializationObject.normals = this.normals;
  37919. }
  37920. if (this.tangents) {
  37921. serializationObject.tangents = this.tangents;
  37922. }
  37923. if (this.uvs) {
  37924. serializationObject.uvs = this.uvs;
  37925. }
  37926. if (this.uvs2) {
  37927. serializationObject.uvs2 = this.uvs2;
  37928. }
  37929. if (this.uvs3) {
  37930. serializationObject.uvs3 = this.uvs3;
  37931. }
  37932. if (this.uvs4) {
  37933. serializationObject.uvs4 = this.uvs4;
  37934. }
  37935. if (this.uvs5) {
  37936. serializationObject.uvs5 = this.uvs5;
  37937. }
  37938. if (this.uvs6) {
  37939. serializationObject.uvs6 = this.uvs6;
  37940. }
  37941. if (this.colors) {
  37942. serializationObject.colors = this.colors;
  37943. }
  37944. if (this.matricesIndices) {
  37945. serializationObject.matricesIndices = this.matricesIndices;
  37946. serializationObject.matricesIndices._isExpanded = true;
  37947. }
  37948. if (this.matricesWeights) {
  37949. serializationObject.matricesWeights = this.matricesWeights;
  37950. }
  37951. if (this.matricesIndicesExtra) {
  37952. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37953. serializationObject.matricesIndicesExtra._isExpanded = true;
  37954. }
  37955. if (this.matricesWeightsExtra) {
  37956. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37957. }
  37958. serializationObject.indices = this.indices;
  37959. return serializationObject;
  37960. };
  37961. // Statics
  37962. /**
  37963. * Extracts the vertexData from a mesh
  37964. * @param mesh the mesh from which to extract the VertexData
  37965. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37966. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37967. * @returns the object VertexData associated to the passed mesh
  37968. */
  37969. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37970. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37971. };
  37972. /**
  37973. * Extracts the vertexData from the geometry
  37974. * @param geometry the geometry from which to extract the VertexData
  37975. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37976. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37977. * @returns the object VertexData associated to the passed mesh
  37978. */
  37979. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37980. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37981. };
  37982. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37983. var result = new VertexData();
  37984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37985. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37986. }
  37987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37988. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37989. }
  37990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37991. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37992. }
  37993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37994. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37995. }
  37996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37997. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37998. }
  37999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38000. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38001. }
  38002. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38003. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38004. }
  38005. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38006. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38007. }
  38008. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38009. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38010. }
  38011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38012. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38013. }
  38014. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38015. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38016. }
  38017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38018. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38019. }
  38020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38021. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38022. }
  38023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38024. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38025. }
  38026. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38027. return result;
  38028. };
  38029. /**
  38030. * Creates the VertexData for a Ribbon
  38031. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38032. * * pathArray array of paths, each of which an array of successive Vector3
  38033. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38034. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38035. * * 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
  38036. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38037. * * 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)
  38038. * * 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)
  38039. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38040. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38041. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38042. * @returns the VertexData of the ribbon
  38043. */
  38044. VertexData.CreateRibbon = function (options) {
  38045. var pathArray = options.pathArray;
  38046. var closeArray = options.closeArray || false;
  38047. var closePath = options.closePath || false;
  38048. var invertUV = options.invertUV || false;
  38049. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38050. var offset = options.offset || defaultOffset;
  38051. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38052. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38053. var customUV = options.uvs;
  38054. var customColors = options.colors;
  38055. var positions = [];
  38056. var indices = [];
  38057. var normals = [];
  38058. var uvs = [];
  38059. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38060. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38061. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38062. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38063. var minlg; // minimal length among all paths from pathArray
  38064. var lg = []; // array of path lengths : nb of vertex per path
  38065. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38066. var p; // path iterator
  38067. var i; // point iterator
  38068. var j; // point iterator
  38069. // if single path in pathArray
  38070. if (pathArray.length < 2) {
  38071. var ar1 = [];
  38072. var ar2 = [];
  38073. for (i = 0; i < pathArray[0].length - offset; i++) {
  38074. ar1.push(pathArray[0][i]);
  38075. ar2.push(pathArray[0][i + offset]);
  38076. }
  38077. pathArray = [ar1, ar2];
  38078. }
  38079. // positions and horizontal distances (u)
  38080. var idc = 0;
  38081. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38082. var path;
  38083. var l;
  38084. minlg = pathArray[0].length;
  38085. var vectlg;
  38086. var dist;
  38087. for (p = 0; p < pathArray.length; p++) {
  38088. uTotalDistance[p] = 0;
  38089. us[p] = [0];
  38090. path = pathArray[p];
  38091. l = path.length;
  38092. minlg = (minlg < l) ? minlg : l;
  38093. j = 0;
  38094. while (j < l) {
  38095. positions.push(path[j].x, path[j].y, path[j].z);
  38096. if (j > 0) {
  38097. vectlg = path[j].subtract(path[j - 1]).length();
  38098. dist = vectlg + uTotalDistance[p];
  38099. us[p].push(dist);
  38100. uTotalDistance[p] = dist;
  38101. }
  38102. j++;
  38103. }
  38104. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38105. j--;
  38106. positions.push(path[0].x, path[0].y, path[0].z);
  38107. vectlg = path[j].subtract(path[0]).length();
  38108. dist = vectlg + uTotalDistance[p];
  38109. us[p].push(dist);
  38110. uTotalDistance[p] = dist;
  38111. }
  38112. lg[p] = l + closePathCorr;
  38113. idx[p] = idc;
  38114. idc += (l + closePathCorr);
  38115. }
  38116. // vertical distances (v)
  38117. var path1;
  38118. var path2;
  38119. var vertex1 = null;
  38120. var vertex2 = null;
  38121. for (i = 0; i < minlg + closePathCorr; i++) {
  38122. vTotalDistance[i] = 0;
  38123. vs[i] = [0];
  38124. for (p = 0; p < pathArray.length - 1; p++) {
  38125. path1 = pathArray[p];
  38126. path2 = pathArray[p + 1];
  38127. if (i === minlg) { // closePath
  38128. vertex1 = path1[0];
  38129. vertex2 = path2[0];
  38130. }
  38131. else {
  38132. vertex1 = path1[i];
  38133. vertex2 = path2[i];
  38134. }
  38135. vectlg = vertex2.subtract(vertex1).length();
  38136. dist = vectlg + vTotalDistance[i];
  38137. vs[i].push(dist);
  38138. vTotalDistance[i] = dist;
  38139. }
  38140. if (closeArray && vertex2 && vertex1) {
  38141. path1 = pathArray[p];
  38142. path2 = pathArray[0];
  38143. if (i === minlg) { // closePath
  38144. vertex2 = path2[0];
  38145. }
  38146. vectlg = vertex2.subtract(vertex1).length();
  38147. dist = vectlg + vTotalDistance[i];
  38148. vTotalDistance[i] = dist;
  38149. }
  38150. }
  38151. // uvs
  38152. var u;
  38153. var v;
  38154. if (customUV) {
  38155. for (p = 0; p < customUV.length; p++) {
  38156. uvs.push(customUV[p].x, customUV[p].y);
  38157. }
  38158. }
  38159. else {
  38160. for (p = 0; p < pathArray.length; p++) {
  38161. for (i = 0; i < minlg + closePathCorr; i++) {
  38162. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38163. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38164. if (invertUV) {
  38165. uvs.push(v, u);
  38166. }
  38167. else {
  38168. uvs.push(u, v);
  38169. }
  38170. }
  38171. }
  38172. }
  38173. // indices
  38174. p = 0; // path index
  38175. var pi = 0; // positions array index
  38176. var l1 = lg[p] - 1; // path1 length
  38177. var l2 = lg[p + 1] - 1; // path2 length
  38178. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38179. var shft = idx[1] - idx[0]; // shift
  38180. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38181. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38182. // 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
  38183. indices.push(pi, pi + shft, pi + 1);
  38184. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38185. pi += 1;
  38186. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38187. p++;
  38188. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38189. shft = idx[0] - idx[p];
  38190. l1 = lg[p] - 1;
  38191. l2 = lg[0] - 1;
  38192. }
  38193. else {
  38194. shft = idx[p + 1] - idx[p];
  38195. l1 = lg[p] - 1;
  38196. l2 = lg[p + 1] - 1;
  38197. }
  38198. pi = idx[p];
  38199. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38200. }
  38201. }
  38202. // normals
  38203. VertexData.ComputeNormals(positions, indices, normals);
  38204. if (closePath) { // update both the first and last vertex normals to their average value
  38205. var indexFirst = 0;
  38206. var indexLast = 0;
  38207. for (p = 0; p < pathArray.length; p++) {
  38208. indexFirst = idx[p] * 3;
  38209. if (p + 1 < pathArray.length) {
  38210. indexLast = (idx[p + 1] - 1) * 3;
  38211. }
  38212. else {
  38213. indexLast = normals.length - 3;
  38214. }
  38215. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38216. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38217. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38218. normals[indexLast] = normals[indexFirst];
  38219. normals[indexLast + 1] = normals[indexFirst + 1];
  38220. normals[indexLast + 2] = normals[indexFirst + 2];
  38221. }
  38222. }
  38223. // sides
  38224. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38225. // Colors
  38226. var colors = null;
  38227. if (customColors) {
  38228. colors = new Float32Array(customColors.length * 4);
  38229. for (var c = 0; c < customColors.length; c++) {
  38230. colors[c * 4] = customColors[c].r;
  38231. colors[c * 4 + 1] = customColors[c].g;
  38232. colors[c * 4 + 2] = customColors[c].b;
  38233. colors[c * 4 + 3] = customColors[c].a;
  38234. }
  38235. }
  38236. // Result
  38237. var vertexData = new VertexData();
  38238. var positions32 = new Float32Array(positions);
  38239. var normals32 = new Float32Array(normals);
  38240. var uvs32 = new Float32Array(uvs);
  38241. vertexData.indices = indices;
  38242. vertexData.positions = positions32;
  38243. vertexData.normals = normals32;
  38244. vertexData.uvs = uvs32;
  38245. if (colors) {
  38246. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38247. }
  38248. if (closePath) {
  38249. vertexData._idx = idx;
  38250. }
  38251. return vertexData;
  38252. };
  38253. /**
  38254. * Creates the VertexData for a box
  38255. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38256. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38257. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38258. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38259. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38260. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38261. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38262. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38263. * * 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)
  38264. * * 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)
  38265. * @returns the VertexData of the box
  38266. */
  38267. VertexData.CreateBox = function (options) {
  38268. var normalsSource = [
  38269. new BABYLON.Vector3(0, 0, 1),
  38270. new BABYLON.Vector3(0, 0, -1),
  38271. new BABYLON.Vector3(1, 0, 0),
  38272. new BABYLON.Vector3(-1, 0, 0),
  38273. new BABYLON.Vector3(0, 1, 0),
  38274. new BABYLON.Vector3(0, -1, 0)
  38275. ];
  38276. var indices = [];
  38277. var positions = [];
  38278. var normals = [];
  38279. var uvs = [];
  38280. var width = options.width || options.size || 1;
  38281. var height = options.height || options.size || 1;
  38282. var depth = options.depth || options.size || 1;
  38283. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38284. var faceUV = options.faceUV || new Array(6);
  38285. var faceColors = options.faceColors;
  38286. var colors = [];
  38287. // default face colors and UV if undefined
  38288. for (var f = 0; f < 6; f++) {
  38289. if (faceUV[f] === undefined) {
  38290. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38291. }
  38292. if (faceColors && faceColors[f] === undefined) {
  38293. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38294. }
  38295. }
  38296. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38297. // Create each face in turn.
  38298. for (var index = 0; index < normalsSource.length; index++) {
  38299. var normal = normalsSource[index];
  38300. // Get two vectors perpendicular to the face normal and to each other.
  38301. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38302. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38303. // Six indices (two triangles) per face.
  38304. var verticesLength = positions.length / 3;
  38305. indices.push(verticesLength);
  38306. indices.push(verticesLength + 1);
  38307. indices.push(verticesLength + 2);
  38308. indices.push(verticesLength);
  38309. indices.push(verticesLength + 2);
  38310. indices.push(verticesLength + 3);
  38311. // Four vertices per face.
  38312. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38313. positions.push(vertex.x, vertex.y, vertex.z);
  38314. normals.push(normal.x, normal.y, normal.z);
  38315. uvs.push(faceUV[index].z, faceUV[index].w);
  38316. if (faceColors) {
  38317. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38318. }
  38319. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38320. positions.push(vertex.x, vertex.y, vertex.z);
  38321. normals.push(normal.x, normal.y, normal.z);
  38322. uvs.push(faceUV[index].x, faceUV[index].w);
  38323. if (faceColors) {
  38324. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38325. }
  38326. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38327. positions.push(vertex.x, vertex.y, vertex.z);
  38328. normals.push(normal.x, normal.y, normal.z);
  38329. uvs.push(faceUV[index].x, faceUV[index].y);
  38330. if (faceColors) {
  38331. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38332. }
  38333. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38334. positions.push(vertex.x, vertex.y, vertex.z);
  38335. normals.push(normal.x, normal.y, normal.z);
  38336. uvs.push(faceUV[index].z, faceUV[index].y);
  38337. if (faceColors) {
  38338. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38339. }
  38340. }
  38341. // sides
  38342. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38343. // Result
  38344. var vertexData = new VertexData();
  38345. vertexData.indices = indices;
  38346. vertexData.positions = positions;
  38347. vertexData.normals = normals;
  38348. vertexData.uvs = uvs;
  38349. if (faceColors) {
  38350. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38351. vertexData.colors = totalColors;
  38352. }
  38353. return vertexData;
  38354. };
  38355. /**
  38356. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38357. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38358. * * segments sets the number of horizontal strips optional, default 32
  38359. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38360. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38361. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38362. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38363. * * 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
  38364. * * 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
  38365. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38366. * * 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)
  38367. * * 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)
  38368. * @returns the VertexData of the ellipsoid
  38369. */
  38370. VertexData.CreateSphere = function (options) {
  38371. var segments = options.segments || 32;
  38372. var diameterX = options.diameterX || options.diameter || 1;
  38373. var diameterY = options.diameterY || options.diameter || 1;
  38374. var diameterZ = options.diameterZ || options.diameter || 1;
  38375. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38376. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38377. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38378. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38379. var totalZRotationSteps = 2 + segments;
  38380. var totalYRotationSteps = 2 * totalZRotationSteps;
  38381. var indices = [];
  38382. var positions = [];
  38383. var normals = [];
  38384. var uvs = [];
  38385. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38386. var normalizedZ = zRotationStep / totalZRotationSteps;
  38387. var angleZ = normalizedZ * Math.PI * slice;
  38388. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38389. var normalizedY = yRotationStep / totalYRotationSteps;
  38390. var angleY = normalizedY * Math.PI * 2 * arc;
  38391. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38392. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38393. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38394. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38395. var vertex = complete.multiply(radius);
  38396. var normal = complete.divide(radius).normalize();
  38397. positions.push(vertex.x, vertex.y, vertex.z);
  38398. normals.push(normal.x, normal.y, normal.z);
  38399. uvs.push(normalizedY, normalizedZ);
  38400. }
  38401. if (zRotationStep > 0) {
  38402. var verticesCount = positions.length / 3;
  38403. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38404. indices.push((firstIndex));
  38405. indices.push((firstIndex + 1));
  38406. indices.push(firstIndex + totalYRotationSteps + 1);
  38407. indices.push((firstIndex + totalYRotationSteps + 1));
  38408. indices.push((firstIndex + 1));
  38409. indices.push((firstIndex + totalYRotationSteps + 2));
  38410. }
  38411. }
  38412. }
  38413. // Sides
  38414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38415. // Result
  38416. var vertexData = new VertexData();
  38417. vertexData.indices = indices;
  38418. vertexData.positions = positions;
  38419. vertexData.normals = normals;
  38420. vertexData.uvs = uvs;
  38421. return vertexData;
  38422. };
  38423. /**
  38424. * Creates the VertexData for a cylinder, cone or prism
  38425. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38426. * * height sets the height (y direction) of the cylinder, optional, default 2
  38427. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38428. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38429. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38430. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38431. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38432. * * 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
  38433. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38434. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38435. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38436. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38437. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38438. * * 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)
  38439. * * 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)
  38440. * @returns the VertexData of the cylinder, cone or prism
  38441. */
  38442. VertexData.CreateCylinder = function (options) {
  38443. var height = options.height || 2;
  38444. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38445. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38446. var tessellation = options.tessellation || 24;
  38447. var subdivisions = options.subdivisions || 1;
  38448. var hasRings = options.hasRings ? true : false;
  38449. var enclose = options.enclose ? true : false;
  38450. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38451. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38452. var faceUV = options.faceUV || new Array(3);
  38453. var faceColors = options.faceColors;
  38454. // default face colors and UV if undefined
  38455. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38456. var ringNb = (hasRings) ? subdivisions : 1;
  38457. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38458. var f;
  38459. for (f = 0; f < surfaceNb; f++) {
  38460. if (faceColors && faceColors[f] === undefined) {
  38461. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38462. }
  38463. }
  38464. for (f = 0; f < surfaceNb; f++) {
  38465. if (faceUV && faceUV[f] === undefined) {
  38466. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38467. }
  38468. }
  38469. var indices = new Array();
  38470. var positions = new Array();
  38471. var normals = new Array();
  38472. var uvs = new Array();
  38473. var colors = new Array();
  38474. var angle_step = Math.PI * 2 * arc / tessellation;
  38475. var angle;
  38476. var h;
  38477. var radius;
  38478. var tan = (diameterBottom - diameterTop) / 2 / height;
  38479. var ringVertex = BABYLON.Vector3.Zero();
  38480. var ringNormal = BABYLON.Vector3.Zero();
  38481. var ringFirstVertex = BABYLON.Vector3.Zero();
  38482. var ringFirstNormal = BABYLON.Vector3.Zero();
  38483. var quadNormal = BABYLON.Vector3.Zero();
  38484. var Y = BABYLON.Axis.Y;
  38485. // positions, normals, uvs
  38486. var i;
  38487. var j;
  38488. var r;
  38489. var ringIdx = 1;
  38490. var s = 1; // surface index
  38491. var cs = 0;
  38492. var v = 0;
  38493. for (i = 0; i <= subdivisions; i++) {
  38494. h = i / subdivisions;
  38495. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38496. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38497. for (r = 0; r < ringIdx; r++) {
  38498. if (hasRings) {
  38499. s += r;
  38500. }
  38501. if (enclose) {
  38502. s += 2 * r;
  38503. }
  38504. for (j = 0; j <= tessellation; j++) {
  38505. angle = j * angle_step;
  38506. // position
  38507. ringVertex.x = Math.cos(-angle) * radius;
  38508. ringVertex.y = -height / 2 + h * height;
  38509. ringVertex.z = Math.sin(-angle) * radius;
  38510. // normal
  38511. if (diameterTop === 0 && i === subdivisions) {
  38512. // if no top cap, reuse former normals
  38513. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38514. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38515. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38516. }
  38517. else {
  38518. ringNormal.x = ringVertex.x;
  38519. ringNormal.z = ringVertex.z;
  38520. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38521. ringNormal.normalize();
  38522. }
  38523. // keep first ring vertex values for enclose
  38524. if (j === 0) {
  38525. ringFirstVertex.copyFrom(ringVertex);
  38526. ringFirstNormal.copyFrom(ringNormal);
  38527. }
  38528. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38529. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38530. if (hasRings) {
  38531. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38532. }
  38533. else {
  38534. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38535. }
  38536. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38537. if (faceColors) {
  38538. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38539. }
  38540. }
  38541. // if enclose, add four vertices and their dedicated normals
  38542. if (arc !== 1 && enclose) {
  38543. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38544. positions.push(0, ringVertex.y, 0);
  38545. positions.push(0, ringVertex.y, 0);
  38546. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38547. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38548. quadNormal.normalize();
  38549. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38550. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38551. quadNormal.normalize();
  38552. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38553. if (hasRings) {
  38554. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38555. }
  38556. else {
  38557. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38558. }
  38559. uvs.push(faceUV[s + 1].x, v);
  38560. uvs.push(faceUV[s + 1].z, v);
  38561. if (hasRings) {
  38562. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38563. }
  38564. else {
  38565. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38566. }
  38567. uvs.push(faceUV[s + 2].x, v);
  38568. uvs.push(faceUV[s + 2].z, v);
  38569. if (faceColors) {
  38570. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38571. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38572. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38573. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38574. }
  38575. }
  38576. if (cs !== s) {
  38577. cs = s;
  38578. }
  38579. }
  38580. }
  38581. // indices
  38582. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38583. var s;
  38584. i = 0;
  38585. for (s = 0; s < subdivisions; s++) {
  38586. var i0 = 0;
  38587. var i1 = 0;
  38588. var i2 = 0;
  38589. var i3 = 0;
  38590. for (j = 0; j < tessellation; j++) {
  38591. i0 = i * (e + 1) + j;
  38592. i1 = (i + 1) * (e + 1) + j;
  38593. i2 = i * (e + 1) + (j + 1);
  38594. i3 = (i + 1) * (e + 1) + (j + 1);
  38595. indices.push(i0, i1, i2);
  38596. indices.push(i3, i2, i1);
  38597. }
  38598. if (arc !== 1 && enclose) { // if enclose, add two quads
  38599. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38600. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38601. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38602. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38603. }
  38604. i = (hasRings) ? (i + 2) : (i + 1);
  38605. }
  38606. // Caps
  38607. var createCylinderCap = function (isTop) {
  38608. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38609. if (radius === 0) {
  38610. return;
  38611. }
  38612. // Cap positions, normals & uvs
  38613. var angle;
  38614. var circleVector;
  38615. var i;
  38616. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38617. var c = null;
  38618. if (faceColors) {
  38619. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38620. }
  38621. // cap center
  38622. var vbase = positions.length / 3;
  38623. var offset = isTop ? height / 2 : -height / 2;
  38624. var center = new BABYLON.Vector3(0, offset, 0);
  38625. positions.push(center.x, center.y, center.z);
  38626. normals.push(0, isTop ? 1 : -1, 0);
  38627. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38628. if (c) {
  38629. colors.push(c.r, c.g, c.b, c.a);
  38630. }
  38631. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38632. for (i = 0; i <= tessellation; i++) {
  38633. angle = Math.PI * 2 * i * arc / tessellation;
  38634. var cos = Math.cos(-angle);
  38635. var sin = Math.sin(-angle);
  38636. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38637. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38638. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38639. normals.push(0, isTop ? 1 : -1, 0);
  38640. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38641. if (c) {
  38642. colors.push(c.r, c.g, c.b, c.a);
  38643. }
  38644. }
  38645. // Cap indices
  38646. for (i = 0; i < tessellation; i++) {
  38647. if (!isTop) {
  38648. indices.push(vbase);
  38649. indices.push(vbase + (i + 1));
  38650. indices.push(vbase + (i + 2));
  38651. }
  38652. else {
  38653. indices.push(vbase);
  38654. indices.push(vbase + (i + 2));
  38655. indices.push(vbase + (i + 1));
  38656. }
  38657. }
  38658. };
  38659. // add caps to geometry
  38660. createCylinderCap(false);
  38661. createCylinderCap(true);
  38662. // Sides
  38663. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38664. var vertexData = new VertexData();
  38665. vertexData.indices = indices;
  38666. vertexData.positions = positions;
  38667. vertexData.normals = normals;
  38668. vertexData.uvs = uvs;
  38669. if (faceColors) {
  38670. vertexData.colors = colors;
  38671. }
  38672. return vertexData;
  38673. };
  38674. /**
  38675. * Creates the VertexData for a torus
  38676. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38677. * * diameter the diameter of the torus, optional default 1
  38678. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38679. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38680. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38681. * * 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)
  38682. * * 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)
  38683. * @returns the VertexData of the torus
  38684. */
  38685. VertexData.CreateTorus = function (options) {
  38686. var indices = [];
  38687. var positions = [];
  38688. var normals = [];
  38689. var uvs = [];
  38690. var diameter = options.diameter || 1;
  38691. var thickness = options.thickness || 0.5;
  38692. var tessellation = options.tessellation || 16;
  38693. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38694. var stride = tessellation + 1;
  38695. for (var i = 0; i <= tessellation; i++) {
  38696. var u = i / tessellation;
  38697. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38698. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38699. for (var j = 0; j <= tessellation; j++) {
  38700. var v = 1 - j / tessellation;
  38701. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38702. var dx = Math.cos(innerAngle);
  38703. var dy = Math.sin(innerAngle);
  38704. // Create a vertex.
  38705. var normal = new BABYLON.Vector3(dx, dy, 0);
  38706. var position = normal.scale(thickness / 2);
  38707. var textureCoordinate = new BABYLON.Vector2(u, v);
  38708. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38709. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38710. positions.push(position.x, position.y, position.z);
  38711. normals.push(normal.x, normal.y, normal.z);
  38712. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38713. // And create indices for two triangles.
  38714. var nextI = (i + 1) % stride;
  38715. var nextJ = (j + 1) % stride;
  38716. indices.push(i * stride + j);
  38717. indices.push(i * stride + nextJ);
  38718. indices.push(nextI * stride + j);
  38719. indices.push(i * stride + nextJ);
  38720. indices.push(nextI * stride + nextJ);
  38721. indices.push(nextI * stride + j);
  38722. }
  38723. }
  38724. // Sides
  38725. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38726. // Result
  38727. var vertexData = new VertexData();
  38728. vertexData.indices = indices;
  38729. vertexData.positions = positions;
  38730. vertexData.normals = normals;
  38731. vertexData.uvs = uvs;
  38732. return vertexData;
  38733. };
  38734. /**
  38735. * Creates the VertexData of the LineSystem
  38736. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38737. * - lines an array of lines, each line being an array of successive Vector3
  38738. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38739. * @returns the VertexData of the LineSystem
  38740. */
  38741. VertexData.CreateLineSystem = function (options) {
  38742. var indices = [];
  38743. var positions = [];
  38744. var lines = options.lines;
  38745. var colors = options.colors;
  38746. var vertexColors = [];
  38747. var idx = 0;
  38748. for (var l = 0; l < lines.length; l++) {
  38749. var points = lines[l];
  38750. for (var index = 0; index < points.length; index++) {
  38751. positions.push(points[index].x, points[index].y, points[index].z);
  38752. if (colors) {
  38753. var color = colors[l];
  38754. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38755. }
  38756. if (index > 0) {
  38757. indices.push(idx - 1);
  38758. indices.push(idx);
  38759. }
  38760. idx++;
  38761. }
  38762. }
  38763. var vertexData = new VertexData();
  38764. vertexData.indices = indices;
  38765. vertexData.positions = positions;
  38766. if (colors) {
  38767. vertexData.colors = vertexColors;
  38768. }
  38769. return vertexData;
  38770. };
  38771. /**
  38772. * Create the VertexData for a DashedLines
  38773. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38774. * - points an array successive Vector3
  38775. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38776. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38777. * - dashNb the intended total number of dashes, optional, default 200
  38778. * @returns the VertexData for the DashedLines
  38779. */
  38780. VertexData.CreateDashedLines = function (options) {
  38781. var dashSize = options.dashSize || 3;
  38782. var gapSize = options.gapSize || 1;
  38783. var dashNb = options.dashNb || 200;
  38784. var points = options.points;
  38785. var positions = new Array();
  38786. var indices = new Array();
  38787. var curvect = BABYLON.Vector3.Zero();
  38788. var lg = 0;
  38789. var nb = 0;
  38790. var shft = 0;
  38791. var dashshft = 0;
  38792. var curshft = 0;
  38793. var idx = 0;
  38794. var i = 0;
  38795. for (i = 0; i < points.length - 1; i++) {
  38796. points[i + 1].subtractToRef(points[i], curvect);
  38797. lg += curvect.length();
  38798. }
  38799. shft = lg / dashNb;
  38800. dashshft = dashSize * shft / (dashSize + gapSize);
  38801. for (i = 0; i < points.length - 1; i++) {
  38802. points[i + 1].subtractToRef(points[i], curvect);
  38803. nb = Math.floor(curvect.length() / shft);
  38804. curvect.normalize();
  38805. for (var j = 0; j < nb; j++) {
  38806. curshft = shft * j;
  38807. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38808. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38809. indices.push(idx, idx + 1);
  38810. idx += 2;
  38811. }
  38812. }
  38813. // Result
  38814. var vertexData = new VertexData();
  38815. vertexData.positions = positions;
  38816. vertexData.indices = indices;
  38817. return vertexData;
  38818. };
  38819. /**
  38820. * Creates the VertexData for a Ground
  38821. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38822. * - width the width (x direction) of the ground, optional, default 1
  38823. * - height the height (z direction) of the ground, optional, default 1
  38824. * - subdivisions the number of subdivisions per side, optional, default 1
  38825. * @returns the VertexData of the Ground
  38826. */
  38827. VertexData.CreateGround = function (options) {
  38828. var indices = [];
  38829. var positions = [];
  38830. var normals = [];
  38831. var uvs = [];
  38832. var row, col;
  38833. var width = options.width || 1;
  38834. var height = options.height || 1;
  38835. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38836. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38837. for (row = 0; row <= subdivisionsY; row++) {
  38838. for (col = 0; col <= subdivisionsX; col++) {
  38839. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38840. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38841. positions.push(position.x, position.y, position.z);
  38842. normals.push(normal.x, normal.y, normal.z);
  38843. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38844. }
  38845. }
  38846. for (row = 0; row < subdivisionsY; row++) {
  38847. for (col = 0; col < subdivisionsX; col++) {
  38848. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38849. indices.push(col + 1 + row * (subdivisionsX + 1));
  38850. indices.push(col + row * (subdivisionsX + 1));
  38851. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38852. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38853. indices.push(col + row * (subdivisionsX + 1));
  38854. }
  38855. }
  38856. // Result
  38857. var vertexData = new VertexData();
  38858. vertexData.indices = indices;
  38859. vertexData.positions = positions;
  38860. vertexData.normals = normals;
  38861. vertexData.uvs = uvs;
  38862. return vertexData;
  38863. };
  38864. /**
  38865. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38866. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38867. * * xmin the ground minimum X coordinate, optional, default -1
  38868. * * zmin the ground minimum Z coordinate, optional, default -1
  38869. * * xmax the ground maximum X coordinate, optional, default 1
  38870. * * zmax the ground maximum Z coordinate, optional, default 1
  38871. * * 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}
  38872. * * 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}
  38873. * @returns the VertexData of the TiledGround
  38874. */
  38875. VertexData.CreateTiledGround = function (options) {
  38876. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38877. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38878. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38879. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38880. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38881. var precision = options.precision || { w: 1, h: 1 };
  38882. var indices = new Array();
  38883. var positions = new Array();
  38884. var normals = new Array();
  38885. var uvs = new Array();
  38886. var row, col, tileRow, tileCol;
  38887. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38888. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38889. precision.w = (precision.w < 1) ? 1 : precision.w;
  38890. precision.h = (precision.h < 1) ? 1 : precision.h;
  38891. var tileSize = {
  38892. 'w': (xmax - xmin) / subdivisions.w,
  38893. 'h': (zmax - zmin) / subdivisions.h
  38894. };
  38895. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38896. // Indices
  38897. var base = positions.length / 3;
  38898. var rowLength = precision.w + 1;
  38899. for (row = 0; row < precision.h; row++) {
  38900. for (col = 0; col < precision.w; col++) {
  38901. var square = [
  38902. base + col + row * rowLength,
  38903. base + (col + 1) + row * rowLength,
  38904. base + (col + 1) + (row + 1) * rowLength,
  38905. base + col + (row + 1) * rowLength
  38906. ];
  38907. indices.push(square[1]);
  38908. indices.push(square[2]);
  38909. indices.push(square[3]);
  38910. indices.push(square[0]);
  38911. indices.push(square[1]);
  38912. indices.push(square[3]);
  38913. }
  38914. }
  38915. // Position, normals and uvs
  38916. var position = BABYLON.Vector3.Zero();
  38917. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38918. for (row = 0; row <= precision.h; row++) {
  38919. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38920. for (col = 0; col <= precision.w; col++) {
  38921. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38922. position.y = 0;
  38923. positions.push(position.x, position.y, position.z);
  38924. normals.push(normal.x, normal.y, normal.z);
  38925. uvs.push(col / precision.w, row / precision.h);
  38926. }
  38927. }
  38928. }
  38929. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38930. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38931. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38932. }
  38933. }
  38934. // Result
  38935. var vertexData = new VertexData();
  38936. vertexData.indices = indices;
  38937. vertexData.positions = positions;
  38938. vertexData.normals = normals;
  38939. vertexData.uvs = uvs;
  38940. return vertexData;
  38941. };
  38942. /**
  38943. * Creates the VertexData of the Ground designed from a heightmap
  38944. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38945. * * width the width (x direction) of the ground
  38946. * * height the height (z direction) of the ground
  38947. * * subdivisions the number of subdivisions per side
  38948. * * minHeight the minimum altitude on the ground, optional, default 0
  38949. * * maxHeight the maximum altitude on the ground, optional default 1
  38950. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38951. * * buffer the array holding the image color data
  38952. * * bufferWidth the width of image
  38953. * * bufferHeight the height of image
  38954. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38955. * @returns the VertexData of the Ground designed from a heightmap
  38956. */
  38957. VertexData.CreateGroundFromHeightMap = function (options) {
  38958. var indices = [];
  38959. var positions = [];
  38960. var normals = [];
  38961. var uvs = [];
  38962. var row, col;
  38963. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38964. var alphaFilter = options.alphaFilter || 0.0;
  38965. // Vertices
  38966. for (row = 0; row <= options.subdivisions; row++) {
  38967. for (col = 0; col <= options.subdivisions; col++) {
  38968. 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));
  38969. // Compute height
  38970. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38971. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38972. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38973. var r = options.buffer[pos] / 255.0;
  38974. var g = options.buffer[pos + 1] / 255.0;
  38975. var b = options.buffer[pos + 2] / 255.0;
  38976. var a = options.buffer[pos + 3] / 255.0;
  38977. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38978. // If our alpha channel is not within our filter then we will assign a 'special' height
  38979. // Then when building the indices, we will ignore any vertex that is using the special height
  38980. if (a >= alphaFilter)
  38981. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38982. else {
  38983. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  38984. }
  38985. // Add vertex
  38986. positions.push(position.x, position.y, position.z);
  38987. normals.push(0, 0, 0);
  38988. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38989. }
  38990. }
  38991. // Indices
  38992. for (row = 0; row < options.subdivisions; row++) {
  38993. for (col = 0; col < options.subdivisions; col++) {
  38994. // Calculate Indices
  38995. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  38996. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  38997. var idx3 = (col + row * (options.subdivisions + 1));
  38998. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  38999. // Check that all indices are visible (based on our special height)
  39000. // Only display the vertex if all Indices are visible
  39001. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39002. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39003. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39004. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39005. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39006. indices.push(idx1);
  39007. indices.push(idx2);
  39008. indices.push(idx3);
  39009. }
  39010. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39011. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39012. indices.push(idx4);
  39013. indices.push(idx1);
  39014. indices.push(idx3);
  39015. }
  39016. }
  39017. }
  39018. // Normals
  39019. VertexData.ComputeNormals(positions, indices, normals);
  39020. // Result
  39021. var vertexData = new VertexData();
  39022. vertexData.indices = indices;
  39023. vertexData.positions = positions;
  39024. vertexData.normals = normals;
  39025. vertexData.uvs = uvs;
  39026. return vertexData;
  39027. };
  39028. /**
  39029. * Creates the VertexData for a Plane
  39030. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39031. * * size sets the width and height of the plane to the value of size, optional default 1
  39032. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39033. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39034. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39035. * * 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)
  39036. * * 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)
  39037. * @returns the VertexData of the box
  39038. */
  39039. VertexData.CreatePlane = function (options) {
  39040. var indices = [];
  39041. var positions = [];
  39042. var normals = [];
  39043. var uvs = [];
  39044. var width = options.width || options.size || 1;
  39045. var height = options.height || options.size || 1;
  39046. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39047. // Vertices
  39048. var halfWidth = width / 2.0;
  39049. var halfHeight = height / 2.0;
  39050. positions.push(-halfWidth, -halfHeight, 0);
  39051. normals.push(0, 0, -1.0);
  39052. uvs.push(0.0, 0.0);
  39053. positions.push(halfWidth, -halfHeight, 0);
  39054. normals.push(0, 0, -1.0);
  39055. uvs.push(1.0, 0.0);
  39056. positions.push(halfWidth, halfHeight, 0);
  39057. normals.push(0, 0, -1.0);
  39058. uvs.push(1.0, 1.0);
  39059. positions.push(-halfWidth, halfHeight, 0);
  39060. normals.push(0, 0, -1.0);
  39061. uvs.push(0.0, 1.0);
  39062. // Indices
  39063. indices.push(0);
  39064. indices.push(1);
  39065. indices.push(2);
  39066. indices.push(0);
  39067. indices.push(2);
  39068. indices.push(3);
  39069. // Sides
  39070. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39071. // Result
  39072. var vertexData = new VertexData();
  39073. vertexData.indices = indices;
  39074. vertexData.positions = positions;
  39075. vertexData.normals = normals;
  39076. vertexData.uvs = uvs;
  39077. return vertexData;
  39078. };
  39079. /**
  39080. * Creates the VertexData of the Disc or regular Polygon
  39081. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39082. * * radius the radius of the disc, optional default 0.5
  39083. * * tessellation the number of polygon sides, optional, default 64
  39084. * * 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
  39085. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39086. * * 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)
  39087. * * 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)
  39088. * @returns the VertexData of the box
  39089. */
  39090. VertexData.CreateDisc = function (options) {
  39091. var positions = new Array();
  39092. var indices = new Array();
  39093. var normals = new Array();
  39094. var uvs = new Array();
  39095. var radius = options.radius || 0.5;
  39096. var tessellation = options.tessellation || 64;
  39097. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39098. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39099. // positions and uvs
  39100. positions.push(0, 0, 0); // disc center first
  39101. uvs.push(0.5, 0.5);
  39102. var theta = Math.PI * 2 * arc;
  39103. var step = theta / tessellation;
  39104. for (var a = 0; a < theta; a += step) {
  39105. var x = Math.cos(a);
  39106. var y = Math.sin(a);
  39107. var u = (x + 1) / 2;
  39108. var v = (1 - y) / 2;
  39109. positions.push(radius * x, radius * y, 0);
  39110. uvs.push(u, v);
  39111. }
  39112. if (arc === 1) {
  39113. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39114. uvs.push(uvs[2], uvs[3]);
  39115. }
  39116. //indices
  39117. var vertexNb = positions.length / 3;
  39118. for (var i = 1; i < vertexNb - 1; i++) {
  39119. indices.push(i + 1, 0, i);
  39120. }
  39121. // result
  39122. VertexData.ComputeNormals(positions, indices, normals);
  39123. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39124. var vertexData = new VertexData();
  39125. vertexData.indices = indices;
  39126. vertexData.positions = positions;
  39127. vertexData.normals = normals;
  39128. vertexData.uvs = uvs;
  39129. return vertexData;
  39130. };
  39131. /**
  39132. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39133. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39134. * @param polygon a mesh built from polygonTriangulation.build()
  39135. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39136. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39137. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39138. * @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)
  39139. * @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)
  39140. * @returns the VertexData of the Polygon
  39141. */
  39142. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39143. var faceUV = fUV || new Array(3);
  39144. var faceColors = fColors;
  39145. var colors = [];
  39146. // default face colors and UV if undefined
  39147. for (var f = 0; f < 3; f++) {
  39148. if (faceUV[f] === undefined) {
  39149. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39150. }
  39151. if (faceColors && faceColors[f] === undefined) {
  39152. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39153. }
  39154. }
  39155. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39156. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39157. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39158. var indices = polygon.getIndices();
  39159. // set face colours and textures
  39160. var idx = 0;
  39161. var face = 0;
  39162. for (var index = 0; index < normals.length; index += 3) {
  39163. //Edge Face no. 1
  39164. if (Math.abs(normals[index + 1]) < 0.001) {
  39165. face = 1;
  39166. }
  39167. //Top Face no. 0
  39168. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39169. face = 0;
  39170. }
  39171. //Bottom Face no. 2
  39172. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39173. face = 2;
  39174. }
  39175. idx = index / 3;
  39176. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39177. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39178. if (faceColors) {
  39179. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39180. }
  39181. }
  39182. // sides
  39183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39184. // Result
  39185. var vertexData = new VertexData();
  39186. vertexData.indices = indices;
  39187. vertexData.positions = positions;
  39188. vertexData.normals = normals;
  39189. vertexData.uvs = uvs;
  39190. if (faceColors) {
  39191. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39192. vertexData.colors = totalColors;
  39193. }
  39194. return vertexData;
  39195. };
  39196. /**
  39197. * Creates the VertexData of the IcoSphere
  39198. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39199. * * radius the radius of the IcoSphere, optional default 1
  39200. * * radiusX allows stretching in the x direction, optional, default radius
  39201. * * radiusY allows stretching in the y direction, optional, default radius
  39202. * * radiusZ allows stretching in the z direction, optional, default radius
  39203. * * flat when true creates a flat shaded mesh, optional, default true
  39204. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39205. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39206. * * 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)
  39207. * * 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)
  39208. * @returns the VertexData of the IcoSphere
  39209. */
  39210. VertexData.CreateIcoSphere = function (options) {
  39211. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39212. var radius = options.radius || 1;
  39213. var flat = (options.flat === undefined) ? true : options.flat;
  39214. var subdivisions = options.subdivisions || 4;
  39215. var radiusX = options.radiusX || radius;
  39216. var radiusY = options.radiusY || radius;
  39217. var radiusZ = options.radiusZ || radius;
  39218. var t = (1 + Math.sqrt(5)) / 2;
  39219. // 12 vertex x,y,z
  39220. var ico_vertices = [
  39221. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39222. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39223. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39224. ];
  39225. // index of 3 vertex makes a face of icopshere
  39226. var ico_indices = [
  39227. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39228. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39229. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39230. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39231. ];
  39232. // vertex for uv have aliased position, not for UV
  39233. var vertices_unalias_id = [
  39234. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39235. // vertex alias
  39236. 0,
  39237. 2,
  39238. 3,
  39239. 3,
  39240. 3,
  39241. 4,
  39242. 7,
  39243. 8,
  39244. 9,
  39245. 9,
  39246. 10,
  39247. 11 // 23: B + 12
  39248. ];
  39249. // uv as integer step (not pixels !)
  39250. var ico_vertexuv = [
  39251. 5, 1, 3, 1, 6, 4, 0, 0,
  39252. 5, 3, 4, 2, 2, 2, 4, 0,
  39253. 2, 0, 1, 1, 6, 0, 6, 2,
  39254. // vertex alias (for same vertex on different faces)
  39255. 0, 4,
  39256. 3, 3,
  39257. 4, 4,
  39258. 3, 1,
  39259. 4, 2,
  39260. 4, 4,
  39261. 0, 2,
  39262. 1, 1,
  39263. 2, 2,
  39264. 3, 3,
  39265. 1, 3,
  39266. 2, 4 // 23: B + 12
  39267. ];
  39268. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39269. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39270. // First island of uv mapping
  39271. // v = 4h 3+ 2
  39272. // v = 3h 9+ 4
  39273. // v = 2h 9+ 5 B
  39274. // v = 1h 9 1 0
  39275. // v = 0h 3 8 7 A
  39276. // u = 0 1 2 3 4 5 6 *a
  39277. // Second island of uv mapping
  39278. // v = 4h 0+ B+ 4+
  39279. // v = 3h A+ 2+
  39280. // v = 2h 7+ 6 3+
  39281. // v = 1h 8+ 3+
  39282. // v = 0h
  39283. // u = 0 1 2 3 4 5 6 *a
  39284. // Face layout on texture UV mapping
  39285. // ============
  39286. // \ 4 /\ 16 / ======
  39287. // \ / \ / /\ 11 /
  39288. // \/ 7 \/ / \ /
  39289. // ======= / 10 \/
  39290. // /\ 17 /\ =======
  39291. // / \ / \ \ 15 /\
  39292. // / 8 \/ 12 \ \ / \
  39293. // ============ \/ 6 \
  39294. // \ 18 /\ ============
  39295. // \ / \ \ 5 /\ 0 /
  39296. // \/ 13 \ \ / \ /
  39297. // ======= \/ 1 \/
  39298. // =============
  39299. // /\ 19 /\ 2 /\
  39300. // / \ / \ / \
  39301. // / 14 \/ 9 \/ 3 \
  39302. // ===================
  39303. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39304. var ustep = 138 / 1024;
  39305. var vstep = 239 / 1024;
  39306. var uoffset = 60 / 1024;
  39307. var voffset = 26 / 1024;
  39308. // Second island should have margin, not to touch the first island
  39309. // avoid any borderline artefact in pixel rounding
  39310. var island_u_offset = -40 / 1024;
  39311. var island_v_offset = +20 / 1024;
  39312. // face is either island 0 or 1 :
  39313. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39314. var island = [
  39315. 0, 0, 0, 0, 1,
  39316. 0, 0, 1, 1, 0,
  39317. 0, 0, 1, 1, 0,
  39318. 0, 1, 1, 1, 0 // 15 - 19
  39319. ];
  39320. var indices = new Array();
  39321. var positions = new Array();
  39322. var normals = new Array();
  39323. var uvs = new Array();
  39324. var current_indice = 0;
  39325. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39326. var face_vertex_pos = new Array(3);
  39327. var face_vertex_uv = new Array(3);
  39328. var v012;
  39329. for (v012 = 0; v012 < 3; v012++) {
  39330. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39331. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39332. }
  39333. // create all with normals
  39334. for (var face = 0; face < 20; face++) {
  39335. // 3 vertex per face
  39336. for (v012 = 0; v012 < 3; v012++) {
  39337. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39338. var v_id = ico_indices[3 * face + v012];
  39339. // vertex have 3D position (x,y,z)
  39340. 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]);
  39341. // Normalize to get normal, then scale to radius
  39342. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39343. // uv Coordinates from vertex ID
  39344. 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);
  39345. }
  39346. // Subdivide the face (interpolate pos, norm, uv)
  39347. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39348. // - norm is linear interpolation of vertex corner normal
  39349. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39350. // - uv is linear interpolation
  39351. //
  39352. // Topology is as below for sub-divide by 2
  39353. // vertex shown as v0,v1,v2
  39354. // interp index is i1 to progress in range [v0,v1[
  39355. // interp index is i2 to progress in range [v0,v2[
  39356. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39357. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39358. //
  39359. //
  39360. // i2 v2
  39361. // ^ ^
  39362. // / / \
  39363. // / / \
  39364. // / / \
  39365. // / / (0,1) \
  39366. // / #---------\
  39367. // / / \ (0,0)'/ \
  39368. // / / \ / \
  39369. // / / \ / \
  39370. // / / (0,0) \ / (1,0) \
  39371. // / #---------#---------\
  39372. // v0 v1
  39373. //
  39374. // --------------------> i1
  39375. //
  39376. // interp of (i1,i2):
  39377. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39378. // along i1 : lerp(x0,x1, i1/(S-i2))
  39379. //
  39380. // centroid of triangle is needed to get help normal computation
  39381. // (c1,c2) are used for centroid location
  39382. var interp_vertex = function (i1, i2, c1, c2) {
  39383. // vertex is interpolated from
  39384. // - face_vertex_pos[0..2]
  39385. // - face_vertex_uv[0..2]
  39386. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39387. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39388. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39389. pos_interp.normalize();
  39390. var vertex_normal;
  39391. if (flat) {
  39392. // in flat mode, recalculate normal as face centroid normal
  39393. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39394. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39395. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39396. }
  39397. else {
  39398. // in smooth mode, recalculate normal from each single vertex position
  39399. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39400. }
  39401. // Vertex normal need correction due to X,Y,Z radius scaling
  39402. vertex_normal.x /= radiusX;
  39403. vertex_normal.y /= radiusY;
  39404. vertex_normal.z /= radiusZ;
  39405. vertex_normal.normalize();
  39406. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39407. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39408. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39409. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39410. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39411. uvs.push(uv_interp.x, uv_interp.y);
  39412. // push each vertex has member of a face
  39413. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39414. indices.push(current_indice);
  39415. current_indice++;
  39416. };
  39417. for (var i2 = 0; i2 < subdivisions; i2++) {
  39418. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39419. // face : (i1,i2) for /\ :
  39420. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39421. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39422. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39423. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39424. if (i1 + i2 + 1 < subdivisions) {
  39425. // face : (i1,i2)' for \/ :
  39426. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39427. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39428. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39429. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39430. }
  39431. }
  39432. }
  39433. }
  39434. // Sides
  39435. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39436. // Result
  39437. var vertexData = new VertexData();
  39438. vertexData.indices = indices;
  39439. vertexData.positions = positions;
  39440. vertexData.normals = normals;
  39441. vertexData.uvs = uvs;
  39442. return vertexData;
  39443. };
  39444. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39445. /**
  39446. * Creates the VertexData for a Polyhedron
  39447. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39448. * * type provided types are:
  39449. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39450. * * 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)
  39451. * * size the size of the IcoSphere, optional default 1
  39452. * * sizeX allows stretching in the x direction, optional, default size
  39453. * * sizeY allows stretching in the y direction, optional, default size
  39454. * * sizeZ allows stretching in the z direction, optional, default size
  39455. * * 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
  39456. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39457. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39458. * * flat when true creates a flat shaded mesh, optional, default true
  39459. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39460. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39461. * * 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)
  39462. * * 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)
  39463. * @returns the VertexData of the Polyhedron
  39464. */
  39465. VertexData.CreatePolyhedron = function (options) {
  39466. // provided polyhedron types :
  39467. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39468. // 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)
  39469. var polyhedra = [];
  39470. 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]] };
  39471. 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]] };
  39472. polyhedra[2] = {
  39473. 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]],
  39474. 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]]
  39475. };
  39476. polyhedra[3] = {
  39477. 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]],
  39478. 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]]
  39479. };
  39480. polyhedra[4] = {
  39481. 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]],
  39482. 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]]
  39483. };
  39484. 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]] };
  39485. 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]] };
  39486. 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]] };
  39487. 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]] };
  39488. 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]] };
  39489. 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]] };
  39490. 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]] };
  39491. 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]] };
  39492. 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]] };
  39493. polyhedra[14] = {
  39494. 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]],
  39495. 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]]
  39496. };
  39497. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39498. var size = options.size;
  39499. var sizeX = options.sizeX || size || 1;
  39500. var sizeY = options.sizeY || size || 1;
  39501. var sizeZ = options.sizeZ || size || 1;
  39502. var data = options.custom || polyhedra[type];
  39503. var nbfaces = data.face.length;
  39504. var faceUV = options.faceUV || new Array(nbfaces);
  39505. var faceColors = options.faceColors;
  39506. var flat = (options.flat === undefined) ? true : options.flat;
  39507. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39508. var positions = new Array();
  39509. var indices = new Array();
  39510. var normals = new Array();
  39511. var uvs = new Array();
  39512. var colors = new Array();
  39513. var index = 0;
  39514. var faceIdx = 0; // face cursor in the array "indexes"
  39515. var indexes = new Array();
  39516. var i = 0;
  39517. var f = 0;
  39518. var u, v, ang, x, y, tmp;
  39519. // default face colors and UV if undefined
  39520. if (flat) {
  39521. for (f = 0; f < nbfaces; f++) {
  39522. if (faceColors && faceColors[f] === undefined) {
  39523. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39524. }
  39525. if (faceUV && faceUV[f] === undefined) {
  39526. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39527. }
  39528. }
  39529. }
  39530. if (!flat) {
  39531. for (i = 0; i < data.vertex.length; i++) {
  39532. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39533. uvs.push(0, 0);
  39534. }
  39535. for (f = 0; f < nbfaces; f++) {
  39536. for (i = 0; i < data.face[f].length - 2; i++) {
  39537. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39538. }
  39539. }
  39540. }
  39541. else {
  39542. for (f = 0; f < nbfaces; f++) {
  39543. var fl = data.face[f].length; // number of vertices of the current face
  39544. ang = 2 * Math.PI / fl;
  39545. x = 0.5 * Math.tan(ang / 2);
  39546. y = 0.5;
  39547. // positions, uvs, colors
  39548. for (i = 0; i < fl; i++) {
  39549. // positions
  39550. 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);
  39551. indexes.push(index);
  39552. index++;
  39553. // uvs
  39554. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39555. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39556. uvs.push(u, v);
  39557. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39558. y = x * Math.sin(ang) + y * Math.cos(ang);
  39559. x = tmp;
  39560. // colors
  39561. if (faceColors) {
  39562. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39563. }
  39564. }
  39565. // indices from indexes
  39566. for (i = 0; i < fl - 2; i++) {
  39567. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39568. }
  39569. faceIdx += fl;
  39570. }
  39571. }
  39572. VertexData.ComputeNormals(positions, indices, normals);
  39573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39574. var vertexData = new VertexData();
  39575. vertexData.positions = positions;
  39576. vertexData.indices = indices;
  39577. vertexData.normals = normals;
  39578. vertexData.uvs = uvs;
  39579. if (faceColors && flat) {
  39580. vertexData.colors = colors;
  39581. }
  39582. return vertexData;
  39583. };
  39584. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39585. /**
  39586. * Creates the VertexData for a TorusKnot
  39587. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39588. * * radius the radius of the torus knot, optional, default 2
  39589. * * tube the thickness of the tube, optional, default 0.5
  39590. * * radialSegments the number of sides on each tube segments, optional, default 32
  39591. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39592. * * p the number of windings around the z axis, optional, default 2
  39593. * * q the number of windings around the x axis, optional, default 3
  39594. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39595. * * 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)
  39596. * * 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)
  39597. * @returns the VertexData of the Torus Knot
  39598. */
  39599. VertexData.CreateTorusKnot = function (options) {
  39600. var indices = new Array();
  39601. var positions = new Array();
  39602. var normals = new Array();
  39603. var uvs = new Array();
  39604. var radius = options.radius || 2;
  39605. var tube = options.tube || 0.5;
  39606. var radialSegments = options.radialSegments || 32;
  39607. var tubularSegments = options.tubularSegments || 32;
  39608. var p = options.p || 2;
  39609. var q = options.q || 3;
  39610. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39611. // Helper
  39612. var getPos = function (angle) {
  39613. var cu = Math.cos(angle);
  39614. var su = Math.sin(angle);
  39615. var quOverP = q / p * angle;
  39616. var cs = Math.cos(quOverP);
  39617. var tx = radius * (2 + cs) * 0.5 * cu;
  39618. var ty = radius * (2 + cs) * su * 0.5;
  39619. var tz = radius * Math.sin(quOverP) * 0.5;
  39620. return new BABYLON.Vector3(tx, ty, tz);
  39621. };
  39622. // Vertices
  39623. var i;
  39624. var j;
  39625. for (i = 0; i <= radialSegments; i++) {
  39626. var modI = i % radialSegments;
  39627. var u = modI / radialSegments * 2 * p * Math.PI;
  39628. var p1 = getPos(u);
  39629. var p2 = getPos(u + 0.01);
  39630. var tang = p2.subtract(p1);
  39631. var n = p2.add(p1);
  39632. var bitan = BABYLON.Vector3.Cross(tang, n);
  39633. n = BABYLON.Vector3.Cross(bitan, tang);
  39634. bitan.normalize();
  39635. n.normalize();
  39636. for (j = 0; j < tubularSegments; j++) {
  39637. var modJ = j % tubularSegments;
  39638. var v = modJ / tubularSegments * 2 * Math.PI;
  39639. var cx = -tube * Math.cos(v);
  39640. var cy = tube * Math.sin(v);
  39641. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39642. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39643. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39644. uvs.push(i / radialSegments);
  39645. uvs.push(j / tubularSegments);
  39646. }
  39647. }
  39648. for (i = 0; i < radialSegments; i++) {
  39649. for (j = 0; j < tubularSegments; j++) {
  39650. var jNext = (j + 1) % tubularSegments;
  39651. var a = i * tubularSegments + j;
  39652. var b = (i + 1) * tubularSegments + j;
  39653. var c = (i + 1) * tubularSegments + jNext;
  39654. var d = i * tubularSegments + jNext;
  39655. indices.push(d);
  39656. indices.push(b);
  39657. indices.push(a);
  39658. indices.push(d);
  39659. indices.push(c);
  39660. indices.push(b);
  39661. }
  39662. }
  39663. // Normals
  39664. VertexData.ComputeNormals(positions, indices, normals);
  39665. // Sides
  39666. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39667. // Result
  39668. var vertexData = new VertexData();
  39669. vertexData.indices = indices;
  39670. vertexData.positions = positions;
  39671. vertexData.normals = normals;
  39672. vertexData.uvs = uvs;
  39673. return vertexData;
  39674. };
  39675. // Tools
  39676. /**
  39677. * Compute normals for given positions and indices
  39678. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39679. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39680. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39681. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39682. * * facetNormals : optional array of facet normals (vector3)
  39683. * * facetPositions : optional array of facet positions (vector3)
  39684. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39685. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39686. * * bInfo : optional bounding info, required for facetPartitioning computation
  39687. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39688. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39689. * * useRightHandedSystem: optional boolean to for right handed system computation
  39690. * * depthSort : optional boolean to enable the facet depth sort computation
  39691. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39692. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39693. */
  39694. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39695. // temporary scalar variables
  39696. var index = 0; // facet index
  39697. var p1p2x = 0.0; // p1p2 vector x coordinate
  39698. var p1p2y = 0.0; // p1p2 vector y coordinate
  39699. var p1p2z = 0.0; // p1p2 vector z coordinate
  39700. var p3p2x = 0.0; // p3p2 vector x coordinate
  39701. var p3p2y = 0.0; // p3p2 vector y coordinate
  39702. var p3p2z = 0.0; // p3p2 vector z coordinate
  39703. var faceNormalx = 0.0; // facet normal x coordinate
  39704. var faceNormaly = 0.0; // facet normal y coordinate
  39705. var faceNormalz = 0.0; // facet normal z coordinate
  39706. var length = 0.0; // facet normal length before normalization
  39707. var v1x = 0; // vector1 x index in the positions array
  39708. var v1y = 0; // vector1 y index in the positions array
  39709. var v1z = 0; // vector1 z index in the positions array
  39710. var v2x = 0; // vector2 x index in the positions array
  39711. var v2y = 0; // vector2 y index in the positions array
  39712. var v2z = 0; // vector2 z index in the positions array
  39713. var v3x = 0; // vector3 x index in the positions array
  39714. var v3y = 0; // vector3 y index in the positions array
  39715. var v3z = 0; // vector3 z index in the positions array
  39716. var computeFacetNormals = false;
  39717. var computeFacetPositions = false;
  39718. var computeFacetPartitioning = false;
  39719. var computeDepthSort = false;
  39720. var faceNormalSign = 1;
  39721. var ratio = 0;
  39722. var distanceTo = null;
  39723. if (options) {
  39724. computeFacetNormals = (options.facetNormals) ? true : false;
  39725. computeFacetPositions = (options.facetPositions) ? true : false;
  39726. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39727. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39728. ratio = options.ratio || 0;
  39729. computeDepthSort = (options.depthSort) ? true : false;
  39730. distanceTo = (options.distanceTo);
  39731. if (computeDepthSort) {
  39732. if (distanceTo === undefined) {
  39733. distanceTo = BABYLON.Vector3.Zero();
  39734. }
  39735. var depthSortedFacets = options.depthSortedFacets;
  39736. }
  39737. }
  39738. // facetPartitioning reinit if needed
  39739. var xSubRatio = 0;
  39740. var ySubRatio = 0;
  39741. var zSubRatio = 0;
  39742. var subSq = 0;
  39743. if (computeFacetPartitioning && options && options.bbSize) {
  39744. var ox = 0; // X partitioning index for facet position
  39745. var oy = 0; // Y partinioning index for facet position
  39746. var oz = 0; // Z partinioning index for facet position
  39747. var b1x = 0; // X partitioning index for facet v1 vertex
  39748. var b1y = 0; // Y partitioning index for facet v1 vertex
  39749. var b1z = 0; // z partitioning index for facet v1 vertex
  39750. var b2x = 0; // X partitioning index for facet v2 vertex
  39751. var b2y = 0; // Y partitioning index for facet v2 vertex
  39752. var b2z = 0; // Z partitioning index for facet v2 vertex
  39753. var b3x = 0; // X partitioning index for facet v3 vertex
  39754. var b3y = 0; // Y partitioning index for facet v3 vertex
  39755. var b3z = 0; // Z partitioning index for facet v3 vertex
  39756. var block_idx_o = 0; // facet barycenter block index
  39757. var block_idx_v1 = 0; // v1 vertex block index
  39758. var block_idx_v2 = 0; // v2 vertex block index
  39759. var block_idx_v3 = 0; // v3 vertex block index
  39760. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39761. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39762. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39763. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39764. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39765. subSq = options.subDiv.max * options.subDiv.max;
  39766. options.facetPartitioning.length = 0;
  39767. }
  39768. // reset the normals
  39769. for (index = 0; index < positions.length; index++) {
  39770. normals[index] = 0.0;
  39771. }
  39772. // Loop : 1 indice triplet = 1 facet
  39773. var nbFaces = (indices.length / 3) | 0;
  39774. for (index = 0; index < nbFaces; index++) {
  39775. // get the indexes of the coordinates of each vertex of the facet
  39776. v1x = indices[index * 3] * 3;
  39777. v1y = v1x + 1;
  39778. v1z = v1x + 2;
  39779. v2x = indices[index * 3 + 1] * 3;
  39780. v2y = v2x + 1;
  39781. v2z = v2x + 2;
  39782. v3x = indices[index * 3 + 2] * 3;
  39783. v3y = v3x + 1;
  39784. v3z = v3x + 2;
  39785. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39786. p1p2y = positions[v1y] - positions[v2y];
  39787. p1p2z = positions[v1z] - positions[v2z];
  39788. p3p2x = positions[v3x] - positions[v2x];
  39789. p3p2y = positions[v3y] - positions[v2y];
  39790. p3p2z = positions[v3z] - positions[v2z];
  39791. // compute the face normal with the cross product
  39792. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39793. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39794. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39795. // normalize this normal and store it in the array facetData
  39796. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39797. length = (length === 0) ? 1.0 : length;
  39798. faceNormalx /= length;
  39799. faceNormaly /= length;
  39800. faceNormalz /= length;
  39801. if (computeFacetNormals && options) {
  39802. options.facetNormals[index].x = faceNormalx;
  39803. options.facetNormals[index].y = faceNormaly;
  39804. options.facetNormals[index].z = faceNormalz;
  39805. }
  39806. if (computeFacetPositions && options) {
  39807. // compute and the facet barycenter coordinates in the array facetPositions
  39808. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39809. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39810. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39811. }
  39812. if (computeFacetPartitioning && options) {
  39813. // store the facet indexes in arrays in the main facetPartitioning array :
  39814. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39815. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39816. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39817. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39818. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39819. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39820. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39821. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39822. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39823. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39824. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39825. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39826. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39827. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39828. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39829. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39830. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39831. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39832. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39833. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39834. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39835. // push each facet index in each block containing the vertex
  39836. options.facetPartitioning[block_idx_v1].push(index);
  39837. if (block_idx_v2 != block_idx_v1) {
  39838. options.facetPartitioning[block_idx_v2].push(index);
  39839. }
  39840. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39841. options.facetPartitioning[block_idx_v3].push(index);
  39842. }
  39843. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39844. options.facetPartitioning[block_idx_o].push(index);
  39845. }
  39846. }
  39847. if (computeDepthSort && options && options.facetPositions) {
  39848. var dsf = depthSortedFacets[index];
  39849. dsf.ind = index * 3;
  39850. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39851. }
  39852. // compute the normals anyway
  39853. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39854. normals[v1y] += faceNormaly;
  39855. normals[v1z] += faceNormalz;
  39856. normals[v2x] += faceNormalx;
  39857. normals[v2y] += faceNormaly;
  39858. normals[v2z] += faceNormalz;
  39859. normals[v3x] += faceNormalx;
  39860. normals[v3y] += faceNormaly;
  39861. normals[v3z] += faceNormalz;
  39862. }
  39863. // last normalization of each normal
  39864. for (index = 0; index < normals.length / 3; index++) {
  39865. faceNormalx = normals[index * 3];
  39866. faceNormaly = normals[index * 3 + 1];
  39867. faceNormalz = normals[index * 3 + 2];
  39868. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39869. length = (length === 0) ? 1.0 : length;
  39870. faceNormalx /= length;
  39871. faceNormaly /= length;
  39872. faceNormalz /= length;
  39873. normals[index * 3] = faceNormalx;
  39874. normals[index * 3 + 1] = faceNormaly;
  39875. normals[index * 3 + 2] = faceNormalz;
  39876. }
  39877. };
  39878. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39879. var li = indices.length;
  39880. var ln = normals.length;
  39881. var i;
  39882. var n;
  39883. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39884. switch (sideOrientation) {
  39885. case BABYLON.Mesh.FRONTSIDE:
  39886. // nothing changed
  39887. break;
  39888. case BABYLON.Mesh.BACKSIDE:
  39889. var tmp;
  39890. // indices
  39891. for (i = 0; i < li; i += 3) {
  39892. tmp = indices[i];
  39893. indices[i] = indices[i + 2];
  39894. indices[i + 2] = tmp;
  39895. }
  39896. // normals
  39897. for (n = 0; n < ln; n++) {
  39898. normals[n] = -normals[n];
  39899. }
  39900. break;
  39901. case BABYLON.Mesh.DOUBLESIDE:
  39902. // positions
  39903. var lp = positions.length;
  39904. var l = lp / 3;
  39905. for (var p = 0; p < lp; p++) {
  39906. positions[lp + p] = positions[p];
  39907. }
  39908. // indices
  39909. for (i = 0; i < li; i += 3) {
  39910. indices[i + li] = indices[i + 2] + l;
  39911. indices[i + 1 + li] = indices[i + 1] + l;
  39912. indices[i + 2 + li] = indices[i] + l;
  39913. }
  39914. // normals
  39915. for (n = 0; n < ln; n++) {
  39916. normals[ln + n] = -normals[n];
  39917. }
  39918. // uvs
  39919. var lu = uvs.length;
  39920. var u = 0;
  39921. for (u = 0; u < lu; u++) {
  39922. uvs[u + lu] = uvs[u];
  39923. }
  39924. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39925. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39926. u = 0;
  39927. for (i = 0; i < lu / 2; i++) {
  39928. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39929. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39930. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39931. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39932. u += 2;
  39933. }
  39934. break;
  39935. }
  39936. };
  39937. /**
  39938. * Applies VertexData created from the imported parameters to the geometry
  39939. * @param parsedVertexData the parsed data from an imported file
  39940. * @param geometry the geometry to apply the VertexData to
  39941. */
  39942. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39943. var vertexData = new VertexData();
  39944. // positions
  39945. var positions = parsedVertexData.positions;
  39946. if (positions) {
  39947. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39948. }
  39949. // normals
  39950. var normals = parsedVertexData.normals;
  39951. if (normals) {
  39952. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39953. }
  39954. // tangents
  39955. var tangents = parsedVertexData.tangents;
  39956. if (tangents) {
  39957. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39958. }
  39959. // uvs
  39960. var uvs = parsedVertexData.uvs;
  39961. if (uvs) {
  39962. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39963. }
  39964. // uv2s
  39965. var uv2s = parsedVertexData.uv2s;
  39966. if (uv2s) {
  39967. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39968. }
  39969. // uv3s
  39970. var uv3s = parsedVertexData.uv3s;
  39971. if (uv3s) {
  39972. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39973. }
  39974. // uv4s
  39975. var uv4s = parsedVertexData.uv4s;
  39976. if (uv4s) {
  39977. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39978. }
  39979. // uv5s
  39980. var uv5s = parsedVertexData.uv5s;
  39981. if (uv5s) {
  39982. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39983. }
  39984. // uv6s
  39985. var uv6s = parsedVertexData.uv6s;
  39986. if (uv6s) {
  39987. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39988. }
  39989. // colors
  39990. var colors = parsedVertexData.colors;
  39991. if (colors) {
  39992. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39993. }
  39994. // matricesIndices
  39995. var matricesIndices = parsedVertexData.matricesIndices;
  39996. if (matricesIndices) {
  39997. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39998. }
  39999. // matricesWeights
  40000. var matricesWeights = parsedVertexData.matricesWeights;
  40001. if (matricesWeights) {
  40002. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40003. }
  40004. // indices
  40005. var indices = parsedVertexData.indices;
  40006. if (indices) {
  40007. vertexData.indices = indices;
  40008. }
  40009. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40010. };
  40011. return VertexData;
  40012. }());
  40013. BABYLON.VertexData = VertexData;
  40014. })(BABYLON || (BABYLON = {}));
  40015. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40016. var BABYLON;
  40017. (function (BABYLON) {
  40018. /**
  40019. * Class used to store geometry data (vertex buffers + index buffer)
  40020. */
  40021. var Geometry = /** @class */ (function () {
  40022. /**
  40023. * Creates a new geometry
  40024. * @param id defines the unique ID
  40025. * @param scene defines the hosting scene
  40026. * @param vertexData defines the VertexData used to get geometry data
  40027. * @param updatable defines if geometry must be updatable (false by default)
  40028. * @param mesh defines the mesh that will be associated with the geometry
  40029. */
  40030. function Geometry(id, scene, vertexData, updatable, mesh) {
  40031. if (updatable === void 0) { updatable = false; }
  40032. if (mesh === void 0) { mesh = null; }
  40033. /**
  40034. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40035. */
  40036. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40037. this._totalVertices = 0;
  40038. this._isDisposed = false;
  40039. this._indexBufferIsUpdatable = false;
  40040. this.id = id;
  40041. this._engine = scene.getEngine();
  40042. this._meshes = [];
  40043. this._scene = scene;
  40044. //Init vertex buffer cache
  40045. this._vertexBuffers = {};
  40046. this._indices = [];
  40047. this._updatable = updatable;
  40048. // vertexData
  40049. if (vertexData) {
  40050. this.setAllVerticesData(vertexData, updatable);
  40051. }
  40052. else {
  40053. this._totalVertices = 0;
  40054. this._indices = [];
  40055. }
  40056. if (this._engine.getCaps().vertexArrayObject) {
  40057. this._vertexArrayObjects = {};
  40058. }
  40059. // applyToMesh
  40060. if (mesh) {
  40061. if (mesh.getClassName() === "LinesMesh") {
  40062. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40063. this._updateExtend();
  40064. }
  40065. this.applyToMesh(mesh);
  40066. mesh.computeWorldMatrix(true);
  40067. }
  40068. }
  40069. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40070. /**
  40071. * 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
  40072. */
  40073. get: function () {
  40074. return this._boundingBias;
  40075. },
  40076. /**
  40077. * 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
  40078. */
  40079. set: function (value) {
  40080. if (this._boundingBias) {
  40081. if (this._boundingBias.equals(value)) {
  40082. return;
  40083. }
  40084. this._boundingBias.copyFrom(value);
  40085. }
  40086. else {
  40087. this._boundingBias = value.clone();
  40088. }
  40089. this._updateBoundingInfo(true, null);
  40090. },
  40091. enumerable: true,
  40092. configurable: true
  40093. });
  40094. /**
  40095. * Static function used to attach a new empty geometry to a mesh
  40096. * @param mesh defines the mesh to attach the geometry to
  40097. * @returns the new Geometry
  40098. */
  40099. Geometry.CreateGeometryForMesh = function (mesh) {
  40100. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40101. geometry.applyToMesh(mesh);
  40102. return geometry;
  40103. };
  40104. Object.defineProperty(Geometry.prototype, "extend", {
  40105. /**
  40106. * Gets the current extend of the geometry
  40107. */
  40108. get: function () {
  40109. return this._extend;
  40110. },
  40111. enumerable: true,
  40112. configurable: true
  40113. });
  40114. /**
  40115. * Gets the hosting scene
  40116. * @returns the hosting Scene
  40117. */
  40118. Geometry.prototype.getScene = function () {
  40119. return this._scene;
  40120. };
  40121. /**
  40122. * Gets the hosting engine
  40123. * @returns the hosting Engine
  40124. */
  40125. Geometry.prototype.getEngine = function () {
  40126. return this._engine;
  40127. };
  40128. /**
  40129. * Defines if the geometry is ready to use
  40130. * @returns true if the geometry is ready to be used
  40131. */
  40132. Geometry.prototype.isReady = function () {
  40133. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40134. };
  40135. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40136. /**
  40137. * Gets a value indicating that the geometry should not be serialized
  40138. */
  40139. get: function () {
  40140. for (var index = 0; index < this._meshes.length; index++) {
  40141. if (!this._meshes[index].doNotSerialize) {
  40142. return false;
  40143. }
  40144. }
  40145. return true;
  40146. },
  40147. enumerable: true,
  40148. configurable: true
  40149. });
  40150. /** @hidden */
  40151. Geometry.prototype._rebuild = function () {
  40152. if (this._vertexArrayObjects) {
  40153. this._vertexArrayObjects = {};
  40154. }
  40155. // Index buffer
  40156. if (this._meshes.length !== 0 && this._indices) {
  40157. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40158. }
  40159. // Vertex buffers
  40160. for (var key in this._vertexBuffers) {
  40161. var vertexBuffer = this._vertexBuffers[key];
  40162. vertexBuffer._rebuild();
  40163. }
  40164. };
  40165. /**
  40166. * Affects all geometry data in one call
  40167. * @param vertexData defines the geometry data
  40168. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40169. */
  40170. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40171. vertexData.applyToGeometry(this, updatable);
  40172. this.notifyUpdate();
  40173. };
  40174. /**
  40175. * Set specific vertex data
  40176. * @param kind defines the data kind (Position, normal, etc...)
  40177. * @param data defines the vertex data to use
  40178. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40179. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40180. */
  40181. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40182. if (updatable === void 0) { updatable = false; }
  40183. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40184. this.setVerticesBuffer(buffer);
  40185. };
  40186. /**
  40187. * Removes a specific vertex data
  40188. * @param kind defines the data kind (Position, normal, etc...)
  40189. */
  40190. Geometry.prototype.removeVerticesData = function (kind) {
  40191. if (this._vertexBuffers[kind]) {
  40192. this._vertexBuffers[kind].dispose();
  40193. delete this._vertexBuffers[kind];
  40194. }
  40195. };
  40196. /**
  40197. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40198. * @param buffer defines the vertex buffer to use
  40199. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40200. */
  40201. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40202. if (totalVertices === void 0) { totalVertices = null; }
  40203. var kind = buffer.getKind();
  40204. if (this._vertexBuffers[kind]) {
  40205. this._vertexBuffers[kind].dispose();
  40206. }
  40207. this._vertexBuffers[kind] = buffer;
  40208. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40209. var data = buffer.getData();
  40210. if (totalVertices != null) {
  40211. this._totalVertices = totalVertices;
  40212. }
  40213. else {
  40214. if (data != null) {
  40215. this._totalVertices = data.length / (buffer.byteStride / 4);
  40216. }
  40217. }
  40218. this._updateExtend(data);
  40219. this._resetPointsArrayCache();
  40220. var meshes = this._meshes;
  40221. var numOfMeshes = meshes.length;
  40222. for (var index = 0; index < numOfMeshes; index++) {
  40223. var mesh = meshes[index];
  40224. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40225. mesh._createGlobalSubMesh(false);
  40226. mesh.computeWorldMatrix(true);
  40227. }
  40228. }
  40229. this.notifyUpdate(kind);
  40230. if (this._vertexArrayObjects) {
  40231. this._disposeVertexArrayObjects();
  40232. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40233. }
  40234. };
  40235. /**
  40236. * Update a specific vertex buffer
  40237. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40238. * It will do nothing if the buffer is not updatable
  40239. * @param kind defines the data kind (Position, normal, etc...)
  40240. * @param data defines the data to use
  40241. * @param offset defines the offset in the target buffer where to store the data
  40242. * @param useBytes set to true if the offset is in bytes
  40243. */
  40244. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40245. if (useBytes === void 0) { useBytes = false; }
  40246. var vertexBuffer = this.getVertexBuffer(kind);
  40247. if (!vertexBuffer) {
  40248. return;
  40249. }
  40250. vertexBuffer.updateDirectly(data, offset, useBytes);
  40251. this.notifyUpdate(kind);
  40252. };
  40253. /**
  40254. * Update a specific vertex buffer
  40255. * This function will create a new buffer if the current one is not updatable
  40256. * @param kind defines the data kind (Position, normal, etc...)
  40257. * @param data defines the data to use
  40258. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40259. */
  40260. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40261. if (updateExtends === void 0) { updateExtends = false; }
  40262. var vertexBuffer = this.getVertexBuffer(kind);
  40263. if (!vertexBuffer) {
  40264. return;
  40265. }
  40266. vertexBuffer.update(data);
  40267. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40268. this._updateBoundingInfo(updateExtends, data);
  40269. }
  40270. this.notifyUpdate(kind);
  40271. };
  40272. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40273. if (updateExtends) {
  40274. this._updateExtend(data);
  40275. }
  40276. var meshes = this._meshes;
  40277. var numOfMeshes = meshes.length;
  40278. this._resetPointsArrayCache();
  40279. for (var index = 0; index < numOfMeshes; index++) {
  40280. var mesh = meshes[index];
  40281. if (updateExtends) {
  40282. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40283. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40284. var subMesh = mesh.subMeshes[subIndex];
  40285. subMesh.refreshBoundingInfo();
  40286. }
  40287. }
  40288. }
  40289. };
  40290. /** @hidden */
  40291. Geometry.prototype._bind = function (effect, indexToBind) {
  40292. if (!effect) {
  40293. return;
  40294. }
  40295. if (indexToBind === undefined) {
  40296. indexToBind = this._indexBuffer;
  40297. }
  40298. var vbs = this.getVertexBuffers();
  40299. if (!vbs) {
  40300. return;
  40301. }
  40302. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40303. this._engine.bindBuffers(vbs, indexToBind, effect);
  40304. return;
  40305. }
  40306. // Using VAO
  40307. if (!this._vertexArrayObjects[effect.key]) {
  40308. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40309. }
  40310. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40311. };
  40312. /**
  40313. * Gets total number of vertices
  40314. * @returns the total number of vertices
  40315. */
  40316. Geometry.prototype.getTotalVertices = function () {
  40317. if (!this.isReady()) {
  40318. return 0;
  40319. }
  40320. return this._totalVertices;
  40321. };
  40322. /**
  40323. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40324. * @param kind defines the data kind (Position, normal, etc...)
  40325. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40326. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40327. * @returns a float array containing vertex data
  40328. */
  40329. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40330. var vertexBuffer = this.getVertexBuffer(kind);
  40331. if (!vertexBuffer) {
  40332. return null;
  40333. }
  40334. var data = vertexBuffer.getData();
  40335. if (!data) {
  40336. return null;
  40337. }
  40338. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40339. var count = this._totalVertices * vertexBuffer.getSize();
  40340. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40341. var copy_1 = new Array(count);
  40342. vertexBuffer.forEach(count, function (value, index) {
  40343. copy_1[index] = value;
  40344. });
  40345. return copy_1;
  40346. }
  40347. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40348. if (data instanceof Array) {
  40349. var offset = vertexBuffer.byteOffset / 4;
  40350. return BABYLON.Tools.Slice(data, offset, offset + count);
  40351. }
  40352. else if (data instanceof ArrayBuffer) {
  40353. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40354. }
  40355. else {
  40356. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40357. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40358. var result = new Float32Array(count);
  40359. var source = new Float32Array(data.buffer, offset, count);
  40360. result.set(source);
  40361. return result;
  40362. }
  40363. return new Float32Array(data.buffer, offset, count);
  40364. }
  40365. }
  40366. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40367. return BABYLON.Tools.Slice(data);
  40368. }
  40369. return data;
  40370. };
  40371. /**
  40372. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40373. * @param kind defines the data kind (Position, normal, etc...)
  40374. * @returns true if the vertex buffer with the specified kind is updatable
  40375. */
  40376. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40377. var vb = this._vertexBuffers[kind];
  40378. if (!vb) {
  40379. return false;
  40380. }
  40381. return vb.isUpdatable();
  40382. };
  40383. /**
  40384. * Gets a specific vertex buffer
  40385. * @param kind defines the data kind (Position, normal, etc...)
  40386. * @returns a VertexBuffer
  40387. */
  40388. Geometry.prototype.getVertexBuffer = function (kind) {
  40389. if (!this.isReady()) {
  40390. return null;
  40391. }
  40392. return this._vertexBuffers[kind];
  40393. };
  40394. /**
  40395. * Returns all vertex buffers
  40396. * @return an object holding all vertex buffers indexed by kind
  40397. */
  40398. Geometry.prototype.getVertexBuffers = function () {
  40399. if (!this.isReady()) {
  40400. return null;
  40401. }
  40402. return this._vertexBuffers;
  40403. };
  40404. /**
  40405. * Gets a boolean indicating if specific vertex buffer is present
  40406. * @param kind defines the data kind (Position, normal, etc...)
  40407. * @returns true if data is present
  40408. */
  40409. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40410. if (!this._vertexBuffers) {
  40411. if (this._delayInfo) {
  40412. return this._delayInfo.indexOf(kind) !== -1;
  40413. }
  40414. return false;
  40415. }
  40416. return this._vertexBuffers[kind] !== undefined;
  40417. };
  40418. /**
  40419. * Gets a list of all attached data kinds (Position, normal, etc...)
  40420. * @returns a list of string containing all kinds
  40421. */
  40422. Geometry.prototype.getVerticesDataKinds = function () {
  40423. var result = [];
  40424. var kind;
  40425. if (!this._vertexBuffers && this._delayInfo) {
  40426. for (kind in this._delayInfo) {
  40427. result.push(kind);
  40428. }
  40429. }
  40430. else {
  40431. for (kind in this._vertexBuffers) {
  40432. result.push(kind);
  40433. }
  40434. }
  40435. return result;
  40436. };
  40437. /**
  40438. * Update index buffer
  40439. * @param indices defines the indices to store in the index buffer
  40440. * @param offset defines the offset in the target buffer where to store the data
  40441. */
  40442. Geometry.prototype.updateIndices = function (indices, offset) {
  40443. if (!this._indexBuffer) {
  40444. return;
  40445. }
  40446. if (!this._indexBufferIsUpdatable) {
  40447. this.setIndices(indices, null, true);
  40448. }
  40449. else {
  40450. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40451. }
  40452. };
  40453. /**
  40454. * Creates a new index buffer
  40455. * @param indices defines the indices to store in the index buffer
  40456. * @param totalVertices defines the total number of vertices (could be null)
  40457. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40458. */
  40459. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40460. if (totalVertices === void 0) { totalVertices = null; }
  40461. if (updatable === void 0) { updatable = false; }
  40462. if (this._indexBuffer) {
  40463. this._engine._releaseBuffer(this._indexBuffer);
  40464. }
  40465. this._disposeVertexArrayObjects();
  40466. this._indices = indices;
  40467. this._indexBufferIsUpdatable = updatable;
  40468. if (this._meshes.length !== 0 && this._indices) {
  40469. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40470. }
  40471. if (totalVertices != undefined) { // including null and undefined
  40472. this._totalVertices = totalVertices;
  40473. }
  40474. var meshes = this._meshes;
  40475. var numOfMeshes = meshes.length;
  40476. for (var index = 0; index < numOfMeshes; index++) {
  40477. meshes[index]._createGlobalSubMesh(true);
  40478. }
  40479. this.notifyUpdate();
  40480. };
  40481. /**
  40482. * Return the total number of indices
  40483. * @returns the total number of indices
  40484. */
  40485. Geometry.prototype.getTotalIndices = function () {
  40486. if (!this.isReady()) {
  40487. return 0;
  40488. }
  40489. return this._indices.length;
  40490. };
  40491. /**
  40492. * Gets the index buffer array
  40493. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40494. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40495. * @returns the index buffer array
  40496. */
  40497. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40498. if (!this.isReady()) {
  40499. return null;
  40500. }
  40501. var orig = this._indices;
  40502. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40503. return orig;
  40504. }
  40505. else {
  40506. var len = orig.length;
  40507. var copy = [];
  40508. for (var i = 0; i < len; i++) {
  40509. copy.push(orig[i]);
  40510. }
  40511. return copy;
  40512. }
  40513. };
  40514. /**
  40515. * Gets the index buffer
  40516. * @return the index buffer
  40517. */
  40518. Geometry.prototype.getIndexBuffer = function () {
  40519. if (!this.isReady()) {
  40520. return null;
  40521. }
  40522. return this._indexBuffer;
  40523. };
  40524. /** @hidden */
  40525. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40526. if (effect === void 0) { effect = null; }
  40527. if (!effect || !this._vertexArrayObjects) {
  40528. return;
  40529. }
  40530. if (this._vertexArrayObjects[effect.key]) {
  40531. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40532. delete this._vertexArrayObjects[effect.key];
  40533. }
  40534. };
  40535. /**
  40536. * Release the associated resources for a specific mesh
  40537. * @param mesh defines the source mesh
  40538. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40539. */
  40540. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40541. var meshes = this._meshes;
  40542. var index = meshes.indexOf(mesh);
  40543. if (index === -1) {
  40544. return;
  40545. }
  40546. meshes.splice(index, 1);
  40547. mesh._geometry = null;
  40548. if (meshes.length === 0 && shouldDispose) {
  40549. this.dispose();
  40550. }
  40551. };
  40552. /**
  40553. * Apply current geometry to a given mesh
  40554. * @param mesh defines the mesh to apply geometry to
  40555. */
  40556. Geometry.prototype.applyToMesh = function (mesh) {
  40557. if (mesh._geometry === this) {
  40558. return;
  40559. }
  40560. var previousGeometry = mesh._geometry;
  40561. if (previousGeometry) {
  40562. previousGeometry.releaseForMesh(mesh);
  40563. }
  40564. var meshes = this._meshes;
  40565. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40566. mesh._geometry = this;
  40567. this._scene.pushGeometry(this);
  40568. meshes.push(mesh);
  40569. if (this.isReady()) {
  40570. this._applyToMesh(mesh);
  40571. }
  40572. else {
  40573. mesh._boundingInfo = this._boundingInfo;
  40574. }
  40575. };
  40576. Geometry.prototype._updateExtend = function (data) {
  40577. if (data === void 0) { data = null; }
  40578. if (!data) {
  40579. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40580. }
  40581. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40582. };
  40583. Geometry.prototype._applyToMesh = function (mesh) {
  40584. var numOfMeshes = this._meshes.length;
  40585. // vertexBuffers
  40586. for (var kind in this._vertexBuffers) {
  40587. if (numOfMeshes === 1) {
  40588. this._vertexBuffers[kind].create();
  40589. }
  40590. var buffer = this._vertexBuffers[kind].getBuffer();
  40591. if (buffer)
  40592. buffer.references = numOfMeshes;
  40593. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40594. if (!this._extend) {
  40595. this._updateExtend();
  40596. }
  40597. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40598. mesh._createGlobalSubMesh(false);
  40599. //bounding info was just created again, world matrix should be applied again.
  40600. mesh._updateBoundingInfo();
  40601. }
  40602. }
  40603. // indexBuffer
  40604. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40605. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40606. }
  40607. if (this._indexBuffer) {
  40608. this._indexBuffer.references = numOfMeshes;
  40609. }
  40610. };
  40611. Geometry.prototype.notifyUpdate = function (kind) {
  40612. if (this.onGeometryUpdated) {
  40613. this.onGeometryUpdated(this, kind);
  40614. }
  40615. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40616. var mesh = _a[_i];
  40617. mesh._markSubMeshesAsAttributesDirty();
  40618. }
  40619. };
  40620. /**
  40621. * Load the geometry if it was flagged as delay loaded
  40622. * @param scene defines the hosting scene
  40623. * @param onLoaded defines a callback called when the geometry is loaded
  40624. */
  40625. Geometry.prototype.load = function (scene, onLoaded) {
  40626. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40627. return;
  40628. }
  40629. if (this.isReady()) {
  40630. if (onLoaded) {
  40631. onLoaded();
  40632. }
  40633. return;
  40634. }
  40635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40636. this._queueLoad(scene, onLoaded);
  40637. };
  40638. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40639. var _this = this;
  40640. if (!this.delayLoadingFile) {
  40641. return;
  40642. }
  40643. scene._addPendingData(this);
  40644. scene._loadFile(this.delayLoadingFile, function (data) {
  40645. if (!_this._delayLoadingFunction) {
  40646. return;
  40647. }
  40648. _this._delayLoadingFunction(JSON.parse(data), _this);
  40649. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40650. _this._delayInfo = [];
  40651. scene._removePendingData(_this);
  40652. var meshes = _this._meshes;
  40653. var numOfMeshes = meshes.length;
  40654. for (var index = 0; index < numOfMeshes; index++) {
  40655. _this._applyToMesh(meshes[index]);
  40656. }
  40657. if (onLoaded) {
  40658. onLoaded();
  40659. }
  40660. }, undefined, true);
  40661. };
  40662. /**
  40663. * Invert the geometry to move from a right handed system to a left handed one.
  40664. */
  40665. Geometry.prototype.toLeftHanded = function () {
  40666. // Flip faces
  40667. var tIndices = this.getIndices(false);
  40668. if (tIndices != null && tIndices.length > 0) {
  40669. for (var i = 0; i < tIndices.length; i += 3) {
  40670. var tTemp = tIndices[i + 0];
  40671. tIndices[i + 0] = tIndices[i + 2];
  40672. tIndices[i + 2] = tTemp;
  40673. }
  40674. this.setIndices(tIndices);
  40675. }
  40676. // Negate position.z
  40677. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40678. if (tPositions != null && tPositions.length > 0) {
  40679. for (var i = 0; i < tPositions.length; i += 3) {
  40680. tPositions[i + 2] = -tPositions[i + 2];
  40681. }
  40682. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40683. }
  40684. // Negate normal.z
  40685. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40686. if (tNormals != null && tNormals.length > 0) {
  40687. for (var i = 0; i < tNormals.length; i += 3) {
  40688. tNormals[i + 2] = -tNormals[i + 2];
  40689. }
  40690. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40691. }
  40692. };
  40693. // Cache
  40694. /** @hidden */
  40695. Geometry.prototype._resetPointsArrayCache = function () {
  40696. this._positions = null;
  40697. };
  40698. /** @hidden */
  40699. Geometry.prototype._generatePointsArray = function () {
  40700. if (this._positions)
  40701. return true;
  40702. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40703. if (!data || data.length === 0) {
  40704. return false;
  40705. }
  40706. this._positions = [];
  40707. for (var index = 0; index < data.length; index += 3) {
  40708. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40709. }
  40710. return true;
  40711. };
  40712. /**
  40713. * Gets a value indicating if the geometry is disposed
  40714. * @returns true if the geometry was disposed
  40715. */
  40716. Geometry.prototype.isDisposed = function () {
  40717. return this._isDisposed;
  40718. };
  40719. Geometry.prototype._disposeVertexArrayObjects = function () {
  40720. if (this._vertexArrayObjects) {
  40721. for (var kind in this._vertexArrayObjects) {
  40722. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40723. }
  40724. this._vertexArrayObjects = {};
  40725. }
  40726. };
  40727. /**
  40728. * Free all associated resources
  40729. */
  40730. Geometry.prototype.dispose = function () {
  40731. var meshes = this._meshes;
  40732. var numOfMeshes = meshes.length;
  40733. var index;
  40734. for (index = 0; index < numOfMeshes; index++) {
  40735. this.releaseForMesh(meshes[index]);
  40736. }
  40737. this._meshes = [];
  40738. this._disposeVertexArrayObjects();
  40739. for (var kind in this._vertexBuffers) {
  40740. this._vertexBuffers[kind].dispose();
  40741. }
  40742. this._vertexBuffers = {};
  40743. this._totalVertices = 0;
  40744. if (this._indexBuffer) {
  40745. this._engine._releaseBuffer(this._indexBuffer);
  40746. }
  40747. this._indexBuffer = null;
  40748. this._indices = [];
  40749. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40750. this.delayLoadingFile = null;
  40751. this._delayLoadingFunction = null;
  40752. this._delayInfo = [];
  40753. this._boundingInfo = null;
  40754. this._scene.removeGeometry(this);
  40755. this._isDisposed = true;
  40756. };
  40757. /**
  40758. * Clone the current geometry into a new geometry
  40759. * @param id defines the unique ID of the new geometry
  40760. * @returns a new geometry object
  40761. */
  40762. Geometry.prototype.copy = function (id) {
  40763. var vertexData = new BABYLON.VertexData();
  40764. vertexData.indices = [];
  40765. var indices = this.getIndices();
  40766. if (indices) {
  40767. for (var index = 0; index < indices.length; index++) {
  40768. vertexData.indices.push(indices[index]);
  40769. }
  40770. }
  40771. var updatable = false;
  40772. var stopChecking = false;
  40773. var kind;
  40774. for (kind in this._vertexBuffers) {
  40775. // using slice() to make a copy of the array and not just reference it
  40776. var data = this.getVerticesData(kind);
  40777. if (data instanceof Float32Array) {
  40778. vertexData.set(new Float32Array(data), kind);
  40779. }
  40780. else {
  40781. vertexData.set(data.slice(0), kind);
  40782. }
  40783. if (!stopChecking) {
  40784. var vb = this.getVertexBuffer(kind);
  40785. if (vb) {
  40786. updatable = vb.isUpdatable();
  40787. stopChecking = !updatable;
  40788. }
  40789. }
  40790. }
  40791. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40792. geometry.delayLoadState = this.delayLoadState;
  40793. geometry.delayLoadingFile = this.delayLoadingFile;
  40794. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40795. for (kind in this._delayInfo) {
  40796. geometry._delayInfo = geometry._delayInfo || [];
  40797. geometry._delayInfo.push(kind);
  40798. }
  40799. // Bounding info
  40800. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40801. return geometry;
  40802. };
  40803. /**
  40804. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40805. * @return a JSON representation of the current geometry data (without the vertices data)
  40806. */
  40807. Geometry.prototype.serialize = function () {
  40808. var serializationObject = {};
  40809. serializationObject.id = this.id;
  40810. serializationObject.updatable = this._updatable;
  40811. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40812. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40813. }
  40814. return serializationObject;
  40815. };
  40816. Geometry.prototype.toNumberArray = function (origin) {
  40817. if (Array.isArray(origin)) {
  40818. return origin;
  40819. }
  40820. else {
  40821. return Array.prototype.slice.call(origin);
  40822. }
  40823. };
  40824. /**
  40825. * Serialize all vertices data into a JSON oject
  40826. * @returns a JSON representation of the current geometry data
  40827. */
  40828. Geometry.prototype.serializeVerticeData = function () {
  40829. var serializationObject = this.serialize();
  40830. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40831. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40832. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40833. serializationObject.positions._updatable = true;
  40834. }
  40835. }
  40836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40837. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40838. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40839. serializationObject.normals._updatable = true;
  40840. }
  40841. }
  40842. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40843. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40844. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40845. serializationObject.tangets._updatable = true;
  40846. }
  40847. }
  40848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40849. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40850. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40851. serializationObject.uvs._updatable = true;
  40852. }
  40853. }
  40854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40855. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40857. serializationObject.uv2s._updatable = true;
  40858. }
  40859. }
  40860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40861. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40863. serializationObject.uv3s._updatable = true;
  40864. }
  40865. }
  40866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40867. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40869. serializationObject.uv4s._updatable = true;
  40870. }
  40871. }
  40872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40873. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40874. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40875. serializationObject.uv5s._updatable = true;
  40876. }
  40877. }
  40878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40879. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40880. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40881. serializationObject.uv6s._updatable = true;
  40882. }
  40883. }
  40884. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40885. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40886. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40887. serializationObject.colors._updatable = true;
  40888. }
  40889. }
  40890. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40891. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40892. serializationObject.matricesIndices._isExpanded = true;
  40893. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40894. serializationObject.matricesIndices._updatable = true;
  40895. }
  40896. }
  40897. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40898. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40899. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40900. serializationObject.matricesWeights._updatable = true;
  40901. }
  40902. }
  40903. serializationObject.indices = this.toNumberArray(this.getIndices());
  40904. return serializationObject;
  40905. };
  40906. // Statics
  40907. /**
  40908. * Extracts a clone of a mesh geometry
  40909. * @param mesh defines the source mesh
  40910. * @param id defines the unique ID of the new geometry object
  40911. * @returns the new geometry object
  40912. */
  40913. Geometry.ExtractFromMesh = function (mesh, id) {
  40914. var geometry = mesh._geometry;
  40915. if (!geometry) {
  40916. return null;
  40917. }
  40918. return geometry.copy(id);
  40919. };
  40920. /**
  40921. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40922. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40923. * Be aware Math.random() could cause collisions, but:
  40924. * "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"
  40925. * @returns a string containing a new GUID
  40926. */
  40927. Geometry.RandomId = function () {
  40928. return BABYLON.Tools.RandomId();
  40929. };
  40930. /** @hidden */
  40931. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40932. var scene = mesh.getScene();
  40933. // Geometry
  40934. var geometryId = parsedGeometry.geometryId;
  40935. if (geometryId) {
  40936. var geometry = scene.getGeometryByID(geometryId);
  40937. if (geometry) {
  40938. geometry.applyToMesh(mesh);
  40939. }
  40940. }
  40941. else if (parsedGeometry instanceof ArrayBuffer) {
  40942. var binaryInfo = mesh._binaryInfo;
  40943. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40944. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40945. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40946. }
  40947. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40948. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40949. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40950. }
  40951. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40952. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40953. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40954. }
  40955. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40956. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40957. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40958. }
  40959. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40960. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40961. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40962. }
  40963. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40964. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40965. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40966. }
  40967. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40968. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40969. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40970. }
  40971. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40972. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40973. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40974. }
  40975. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40976. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40977. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40978. }
  40979. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40980. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40981. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40982. }
  40983. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40984. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40985. var floatIndices = [];
  40986. for (var i = 0; i < matricesIndicesData.length; i++) {
  40987. var index = matricesIndicesData[i];
  40988. floatIndices.push(index & 0x000000FF);
  40989. floatIndices.push((index & 0x0000FF00) >> 8);
  40990. floatIndices.push((index & 0x00FF0000) >> 16);
  40991. floatIndices.push(index >> 24);
  40992. }
  40993. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40994. }
  40995. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40996. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40997. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40998. }
  40999. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41000. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41001. mesh.setIndices(indicesData, null);
  41002. }
  41003. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41004. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41005. mesh.subMeshes = [];
  41006. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41007. var materialIndex = subMeshesData[(i * 5) + 0];
  41008. var verticesStart = subMeshesData[(i * 5) + 1];
  41009. var verticesCount = subMeshesData[(i * 5) + 2];
  41010. var indexStart = subMeshesData[(i * 5) + 3];
  41011. var indexCount = subMeshesData[(i * 5) + 4];
  41012. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41013. }
  41014. }
  41015. }
  41016. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41017. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41018. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41019. if (parsedGeometry.tangents) {
  41020. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41021. }
  41022. if (parsedGeometry.uvs) {
  41023. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41024. }
  41025. if (parsedGeometry.uvs2) {
  41026. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41027. }
  41028. if (parsedGeometry.uvs3) {
  41029. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41030. }
  41031. if (parsedGeometry.uvs4) {
  41032. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41033. }
  41034. if (parsedGeometry.uvs5) {
  41035. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41036. }
  41037. if (parsedGeometry.uvs6) {
  41038. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41039. }
  41040. if (parsedGeometry.colors) {
  41041. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41042. }
  41043. if (parsedGeometry.matricesIndices) {
  41044. if (!parsedGeometry.matricesIndices._isExpanded) {
  41045. var floatIndices = [];
  41046. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41047. var matricesIndex = parsedGeometry.matricesIndices[i];
  41048. floatIndices.push(matricesIndex & 0x000000FF);
  41049. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41050. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41051. floatIndices.push(matricesIndex >> 24);
  41052. }
  41053. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41054. }
  41055. else {
  41056. delete parsedGeometry.matricesIndices._isExpanded;
  41057. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41058. }
  41059. }
  41060. if (parsedGeometry.matricesIndicesExtra) {
  41061. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41062. var floatIndices = [];
  41063. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41064. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41065. floatIndices.push(matricesIndex & 0x000000FF);
  41066. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41067. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41068. floatIndices.push(matricesIndex >> 24);
  41069. }
  41070. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41071. }
  41072. else {
  41073. delete parsedGeometry.matricesIndices._isExpanded;
  41074. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41075. }
  41076. }
  41077. if (parsedGeometry.matricesWeights) {
  41078. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41079. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41080. }
  41081. if (parsedGeometry.matricesWeightsExtra) {
  41082. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41083. }
  41084. mesh.setIndices(parsedGeometry.indices, null);
  41085. }
  41086. // SubMeshes
  41087. if (parsedGeometry.subMeshes) {
  41088. mesh.subMeshes = [];
  41089. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41090. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41091. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41092. }
  41093. }
  41094. // Flat shading
  41095. if (mesh._shouldGenerateFlatShading) {
  41096. mesh.convertToFlatShadedMesh();
  41097. delete mesh._shouldGenerateFlatShading;
  41098. }
  41099. // Update
  41100. mesh.computeWorldMatrix(true);
  41101. scene.onMeshImportedObservable.notifyObservers(mesh);
  41102. };
  41103. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41104. var epsilon = 1e-3;
  41105. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41106. return;
  41107. }
  41108. var noInfluenceBoneIndex = 0.0;
  41109. if (parsedGeometry.skeletonId > -1) {
  41110. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41111. if (!skeleton) {
  41112. return;
  41113. }
  41114. noInfluenceBoneIndex = skeleton.bones.length;
  41115. }
  41116. else {
  41117. return;
  41118. }
  41119. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41120. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41121. var matricesWeights = parsedGeometry.matricesWeights;
  41122. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41123. var influencers = parsedGeometry.numBoneInfluencer;
  41124. var size = matricesWeights.length;
  41125. for (var i = 0; i < size; i += 4) {
  41126. var weight = 0.0;
  41127. var firstZeroWeight = -1;
  41128. for (var j = 0; j < 4; j++) {
  41129. var w = matricesWeights[i + j];
  41130. weight += w;
  41131. if (w < epsilon && firstZeroWeight < 0) {
  41132. firstZeroWeight = j;
  41133. }
  41134. }
  41135. if (matricesWeightsExtra) {
  41136. for (var j = 0; j < 4; j++) {
  41137. var w = matricesWeightsExtra[i + j];
  41138. weight += w;
  41139. if (w < epsilon && firstZeroWeight < 0) {
  41140. firstZeroWeight = j + 4;
  41141. }
  41142. }
  41143. }
  41144. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41145. firstZeroWeight = influencers - 1;
  41146. }
  41147. if (weight > epsilon) {
  41148. var mweight = 1.0 / weight;
  41149. for (var j = 0; j < 4; j++) {
  41150. matricesWeights[i + j] *= mweight;
  41151. }
  41152. if (matricesWeightsExtra) {
  41153. for (var j = 0; j < 4; j++) {
  41154. matricesWeightsExtra[i + j] *= mweight;
  41155. }
  41156. }
  41157. }
  41158. else {
  41159. if (firstZeroWeight >= 4) {
  41160. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41161. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41162. }
  41163. else {
  41164. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41165. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41166. }
  41167. }
  41168. }
  41169. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41170. if (parsedGeometry.matricesWeightsExtra) {
  41171. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41172. }
  41173. };
  41174. /**
  41175. * Create a new geometry from persisted data (Using .babylon file format)
  41176. * @param parsedVertexData defines the persisted data
  41177. * @param scene defines the hosting scene
  41178. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41179. * @returns the new geometry object
  41180. */
  41181. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41182. if (scene.getGeometryByID(parsedVertexData.id)) {
  41183. return null; // null since geometry could be something else than a box...
  41184. }
  41185. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41186. if (BABYLON.Tags) {
  41187. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41188. }
  41189. if (parsedVertexData.delayLoadingFile) {
  41190. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41191. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41192. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41193. geometry._delayInfo = [];
  41194. if (parsedVertexData.hasUVs) {
  41195. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41196. }
  41197. if (parsedVertexData.hasUVs2) {
  41198. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41199. }
  41200. if (parsedVertexData.hasUVs3) {
  41201. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41202. }
  41203. if (parsedVertexData.hasUVs4) {
  41204. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41205. }
  41206. if (parsedVertexData.hasUVs5) {
  41207. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41208. }
  41209. if (parsedVertexData.hasUVs6) {
  41210. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41211. }
  41212. if (parsedVertexData.hasColors) {
  41213. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41214. }
  41215. if (parsedVertexData.hasMatricesIndices) {
  41216. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41217. }
  41218. if (parsedVertexData.hasMatricesWeights) {
  41219. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41220. }
  41221. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41222. }
  41223. else {
  41224. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41225. }
  41226. scene.pushGeometry(geometry, true);
  41227. return geometry;
  41228. };
  41229. return Geometry;
  41230. }());
  41231. BABYLON.Geometry = Geometry;
  41232. // Primitives
  41233. /// Abstract class
  41234. /**
  41235. * Abstract class used to provide common services for all typed geometries
  41236. * @hidden
  41237. */
  41238. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41239. __extends(_PrimitiveGeometry, _super);
  41240. /**
  41241. * Creates a new typed geometry
  41242. * @param id defines the unique ID of the geometry
  41243. * @param scene defines the hosting scene
  41244. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41245. * @param mesh defines the hosting mesh (can be null)
  41246. */
  41247. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41248. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41249. if (mesh === void 0) { mesh = null; }
  41250. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41251. _this._canBeRegenerated = _canBeRegenerated;
  41252. _this._beingRegenerated = true;
  41253. _this.regenerate();
  41254. _this._beingRegenerated = false;
  41255. return _this;
  41256. }
  41257. /**
  41258. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41259. * @returns true if the geometry can be regenerated
  41260. */
  41261. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41262. return this._canBeRegenerated;
  41263. };
  41264. /**
  41265. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41266. */
  41267. _PrimitiveGeometry.prototype.regenerate = function () {
  41268. if (!this._canBeRegenerated) {
  41269. return;
  41270. }
  41271. this._beingRegenerated = true;
  41272. this.setAllVerticesData(this._regenerateVertexData(), false);
  41273. this._beingRegenerated = false;
  41274. };
  41275. /**
  41276. * Clone the geometry
  41277. * @param id defines the unique ID of the new geometry
  41278. * @returns the new geometry
  41279. */
  41280. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41281. return _super.prototype.copy.call(this, id);
  41282. };
  41283. // overrides
  41284. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41285. if (!this._beingRegenerated) {
  41286. return;
  41287. }
  41288. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41289. };
  41290. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41291. if (!this._beingRegenerated) {
  41292. return;
  41293. }
  41294. _super.prototype.setVerticesData.call(this, kind, data, false);
  41295. };
  41296. // to override
  41297. /** @hidden */
  41298. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41299. throw new Error("Abstract method");
  41300. };
  41301. _PrimitiveGeometry.prototype.copy = function (id) {
  41302. throw new Error("Must be overriden in sub-classes.");
  41303. };
  41304. _PrimitiveGeometry.prototype.serialize = function () {
  41305. var serializationObject = _super.prototype.serialize.call(this);
  41306. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41307. return serializationObject;
  41308. };
  41309. return _PrimitiveGeometry;
  41310. }(Geometry));
  41311. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41312. /**
  41313. * Creates a ribbon geometry
  41314. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41315. */
  41316. var RibbonGeometry = /** @class */ (function (_super) {
  41317. __extends(RibbonGeometry, _super);
  41318. /**
  41319. * Creates a ribbon geometry
  41320. * @param id defines the unique ID of the geometry
  41321. * @param scene defines the hosting scene
  41322. * @param pathArray defines the array of paths to use
  41323. * @param closeArray defines if the last path and the first path must be joined
  41324. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41325. * @param offset defines the offset between points
  41326. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41327. * @param mesh defines the hosting mesh (can be null)
  41328. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41329. */
  41330. function RibbonGeometry(id, scene,
  41331. /**
  41332. * Defines the array of paths to use
  41333. */
  41334. pathArray,
  41335. /**
  41336. * Defines if the last and first points of each path in your pathArray must be joined
  41337. */
  41338. closeArray,
  41339. /**
  41340. * Defines if the last and first points of each path in your pathArray must be joined
  41341. */
  41342. closePath,
  41343. /**
  41344. * Defines the offset between points
  41345. */
  41346. offset, canBeRegenerated, mesh,
  41347. /**
  41348. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41349. */
  41350. side) {
  41351. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41352. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41353. _this.pathArray = pathArray;
  41354. _this.closeArray = closeArray;
  41355. _this.closePath = closePath;
  41356. _this.offset = offset;
  41357. _this.side = side;
  41358. return _this;
  41359. }
  41360. /** @hidden */
  41361. RibbonGeometry.prototype._regenerateVertexData = function () {
  41362. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41363. };
  41364. RibbonGeometry.prototype.copy = function (id) {
  41365. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41366. };
  41367. return RibbonGeometry;
  41368. }(_PrimitiveGeometry));
  41369. BABYLON.RibbonGeometry = RibbonGeometry;
  41370. /**
  41371. * Creates a box geometry
  41372. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41373. */
  41374. var BoxGeometry = /** @class */ (function (_super) {
  41375. __extends(BoxGeometry, _super);
  41376. /**
  41377. * Creates a box geometry
  41378. * @param id defines the unique ID of the geometry
  41379. * @param scene defines the hosting scene
  41380. * @param size defines the zise of the box (width, height and depth are the same)
  41381. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41382. * @param mesh defines the hosting mesh (can be null)
  41383. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41384. */
  41385. function BoxGeometry(id, scene,
  41386. /**
  41387. * Defines the zise of the box (width, height and depth are the same)
  41388. */
  41389. size, canBeRegenerated, mesh,
  41390. /**
  41391. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41392. */
  41393. side) {
  41394. if (mesh === void 0) { mesh = null; }
  41395. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41396. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41397. _this.size = size;
  41398. _this.side = side;
  41399. return _this;
  41400. }
  41401. /** @hidden */
  41402. BoxGeometry.prototype._regenerateVertexData = function () {
  41403. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41404. };
  41405. BoxGeometry.prototype.copy = function (id) {
  41406. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41407. };
  41408. BoxGeometry.prototype.serialize = function () {
  41409. var serializationObject = _super.prototype.serialize.call(this);
  41410. serializationObject.size = this.size;
  41411. return serializationObject;
  41412. };
  41413. BoxGeometry.Parse = function (parsedBox, scene) {
  41414. if (scene.getGeometryByID(parsedBox.id)) {
  41415. return null; // null since geometry could be something else than a box...
  41416. }
  41417. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41418. if (BABYLON.Tags) {
  41419. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41420. }
  41421. scene.pushGeometry(box, true);
  41422. return box;
  41423. };
  41424. return BoxGeometry;
  41425. }(_PrimitiveGeometry));
  41426. BABYLON.BoxGeometry = BoxGeometry;
  41427. /**
  41428. * Creates a sphere geometry
  41429. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41430. */
  41431. var SphereGeometry = /** @class */ (function (_super) {
  41432. __extends(SphereGeometry, _super);
  41433. /**
  41434. * Create a new sphere geometry
  41435. * @param id defines the unique ID of the geometry
  41436. * @param scene defines the hosting scene
  41437. * @param segments defines the number of segments to use to create the sphere
  41438. * @param diameter defines the diameter of the sphere
  41439. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41440. * @param mesh defines the hosting mesh (can be null)
  41441. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41442. */
  41443. function SphereGeometry(id, scene,
  41444. /**
  41445. * Defines the number of segments to use to create the sphere
  41446. */
  41447. segments,
  41448. /**
  41449. * Defines the diameter of the sphere
  41450. */
  41451. diameter, canBeRegenerated, mesh,
  41452. /**
  41453. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41454. */
  41455. side) {
  41456. if (mesh === void 0) { mesh = null; }
  41457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41459. _this.segments = segments;
  41460. _this.diameter = diameter;
  41461. _this.side = side;
  41462. return _this;
  41463. }
  41464. /** @hidden */
  41465. SphereGeometry.prototype._regenerateVertexData = function () {
  41466. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41467. };
  41468. SphereGeometry.prototype.copy = function (id) {
  41469. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41470. };
  41471. SphereGeometry.prototype.serialize = function () {
  41472. var serializationObject = _super.prototype.serialize.call(this);
  41473. serializationObject.segments = this.segments;
  41474. serializationObject.diameter = this.diameter;
  41475. return serializationObject;
  41476. };
  41477. SphereGeometry.Parse = function (parsedSphere, scene) {
  41478. if (scene.getGeometryByID(parsedSphere.id)) {
  41479. return null; // null since geometry could be something else than a sphere...
  41480. }
  41481. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41482. if (BABYLON.Tags) {
  41483. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41484. }
  41485. scene.pushGeometry(sphere, true);
  41486. return sphere;
  41487. };
  41488. return SphereGeometry;
  41489. }(_PrimitiveGeometry));
  41490. BABYLON.SphereGeometry = SphereGeometry;
  41491. /**
  41492. * Creates a disc geometry
  41493. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41494. */
  41495. var DiscGeometry = /** @class */ (function (_super) {
  41496. __extends(DiscGeometry, _super);
  41497. /**
  41498. * Creates a new disc geometry
  41499. * @param id defines the unique ID of the geometry
  41500. * @param scene defines the hosting scene
  41501. * @param radius defines the radius of the disc
  41502. * @param tessellation defines the tesselation factor to apply to the disc
  41503. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41504. * @param mesh defines the hosting mesh (can be null)
  41505. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41506. */
  41507. function DiscGeometry(id, scene,
  41508. /**
  41509. * Defines the radius of the disc
  41510. */
  41511. radius,
  41512. /**
  41513. * Defines the tesselation factor to apply to the disc
  41514. */
  41515. tessellation, canBeRegenerated, mesh,
  41516. /**
  41517. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41518. */
  41519. side) {
  41520. if (mesh === void 0) { mesh = null; }
  41521. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41522. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41523. _this.radius = radius;
  41524. _this.tessellation = tessellation;
  41525. _this.side = side;
  41526. return _this;
  41527. }
  41528. /** @hidden */
  41529. DiscGeometry.prototype._regenerateVertexData = function () {
  41530. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41531. };
  41532. DiscGeometry.prototype.copy = function (id) {
  41533. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41534. };
  41535. return DiscGeometry;
  41536. }(_PrimitiveGeometry));
  41537. BABYLON.DiscGeometry = DiscGeometry;
  41538. /**
  41539. * Creates a new cylinder geometry
  41540. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41541. */
  41542. var CylinderGeometry = /** @class */ (function (_super) {
  41543. __extends(CylinderGeometry, _super);
  41544. /**
  41545. * Creates a new cylinder geometry
  41546. * @param id defines the unique ID of the geometry
  41547. * @param scene defines the hosting scene
  41548. * @param height defines the height of the cylinder
  41549. * @param diameterTop defines the diameter of the cylinder's top cap
  41550. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41551. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41552. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41553. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41554. * @param mesh defines the hosting mesh (can be null)
  41555. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41556. */
  41557. function CylinderGeometry(id, scene,
  41558. /**
  41559. * Defines the height of the cylinder
  41560. */
  41561. height,
  41562. /**
  41563. * Defines the diameter of the cylinder's top cap
  41564. */
  41565. diameterTop,
  41566. /**
  41567. * Defines the diameter of the cylinder's bottom cap
  41568. */
  41569. diameterBottom,
  41570. /**
  41571. * Defines the tessellation factor to apply to the cylinder
  41572. */
  41573. tessellation,
  41574. /**
  41575. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41576. */
  41577. subdivisions, canBeRegenerated, mesh,
  41578. /**
  41579. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41580. */
  41581. side) {
  41582. if (subdivisions === void 0) { subdivisions = 1; }
  41583. if (mesh === void 0) { mesh = null; }
  41584. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41585. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41586. _this.height = height;
  41587. _this.diameterTop = diameterTop;
  41588. _this.diameterBottom = diameterBottom;
  41589. _this.tessellation = tessellation;
  41590. _this.subdivisions = subdivisions;
  41591. _this.side = side;
  41592. return _this;
  41593. }
  41594. /** @hidden */
  41595. CylinderGeometry.prototype._regenerateVertexData = function () {
  41596. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41597. };
  41598. CylinderGeometry.prototype.copy = function (id) {
  41599. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41600. };
  41601. CylinderGeometry.prototype.serialize = function () {
  41602. var serializationObject = _super.prototype.serialize.call(this);
  41603. serializationObject.height = this.height;
  41604. serializationObject.diameterTop = this.diameterTop;
  41605. serializationObject.diameterBottom = this.diameterBottom;
  41606. serializationObject.tessellation = this.tessellation;
  41607. return serializationObject;
  41608. };
  41609. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41610. if (scene.getGeometryByID(parsedCylinder.id)) {
  41611. return null; // null since geometry could be something else than a cylinder...
  41612. }
  41613. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41614. if (BABYLON.Tags) {
  41615. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41616. }
  41617. scene.pushGeometry(cylinder, true);
  41618. return cylinder;
  41619. };
  41620. return CylinderGeometry;
  41621. }(_PrimitiveGeometry));
  41622. BABYLON.CylinderGeometry = CylinderGeometry;
  41623. /**
  41624. * Creates a new torus geometry
  41625. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41626. */
  41627. var TorusGeometry = /** @class */ (function (_super) {
  41628. __extends(TorusGeometry, _super);
  41629. /**
  41630. * Creates a new torus geometry
  41631. * @param id defines the unique ID of the geometry
  41632. * @param scene defines the hosting scene
  41633. * @param diameter defines the diameter of the torus
  41634. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41635. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41636. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41637. * @param mesh defines the hosting mesh (can be null)
  41638. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41639. */
  41640. function TorusGeometry(id, scene,
  41641. /**
  41642. * Defines the diameter of the torus
  41643. */
  41644. diameter,
  41645. /**
  41646. * Defines the thickness of the torus (ie. internal diameter)
  41647. */
  41648. thickness,
  41649. /**
  41650. * Defines the tesselation factor to apply to the torus
  41651. */
  41652. tessellation, canBeRegenerated, mesh,
  41653. /**
  41654. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41655. */
  41656. side) {
  41657. if (mesh === void 0) { mesh = null; }
  41658. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41659. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41660. _this.diameter = diameter;
  41661. _this.thickness = thickness;
  41662. _this.tessellation = tessellation;
  41663. _this.side = side;
  41664. return _this;
  41665. }
  41666. /** @hidden */
  41667. TorusGeometry.prototype._regenerateVertexData = function () {
  41668. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41669. };
  41670. TorusGeometry.prototype.copy = function (id) {
  41671. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41672. };
  41673. TorusGeometry.prototype.serialize = function () {
  41674. var serializationObject = _super.prototype.serialize.call(this);
  41675. serializationObject.diameter = this.diameter;
  41676. serializationObject.thickness = this.thickness;
  41677. serializationObject.tessellation = this.tessellation;
  41678. return serializationObject;
  41679. };
  41680. TorusGeometry.Parse = function (parsedTorus, scene) {
  41681. if (scene.getGeometryByID(parsedTorus.id)) {
  41682. return null; // null since geometry could be something else than a torus...
  41683. }
  41684. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41685. if (BABYLON.Tags) {
  41686. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41687. }
  41688. scene.pushGeometry(torus, true);
  41689. return torus;
  41690. };
  41691. return TorusGeometry;
  41692. }(_PrimitiveGeometry));
  41693. BABYLON.TorusGeometry = TorusGeometry;
  41694. /**
  41695. * Creates a new ground geometry
  41696. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41697. */
  41698. var GroundGeometry = /** @class */ (function (_super) {
  41699. __extends(GroundGeometry, _super);
  41700. /**
  41701. * Creates a new ground geometry
  41702. * @param id defines the unique ID of the geometry
  41703. * @param scene defines the hosting scene
  41704. * @param width defines the width of the ground
  41705. * @param height defines the height of the ground
  41706. * @param subdivisions defines the subdivisions to apply to the ground
  41707. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41708. * @param mesh defines the hosting mesh (can be null)
  41709. */
  41710. function GroundGeometry(id, scene,
  41711. /**
  41712. * Defines the width of the ground
  41713. */
  41714. width,
  41715. /**
  41716. * Defines the height of the ground
  41717. */
  41718. height,
  41719. /**
  41720. * Defines the subdivisions to apply to the ground
  41721. */
  41722. subdivisions, canBeRegenerated, mesh) {
  41723. if (mesh === void 0) { mesh = null; }
  41724. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41725. _this.width = width;
  41726. _this.height = height;
  41727. _this.subdivisions = subdivisions;
  41728. return _this;
  41729. }
  41730. /** @hidden */
  41731. GroundGeometry.prototype._regenerateVertexData = function () {
  41732. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41733. };
  41734. GroundGeometry.prototype.copy = function (id) {
  41735. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41736. };
  41737. GroundGeometry.prototype.serialize = function () {
  41738. var serializationObject = _super.prototype.serialize.call(this);
  41739. serializationObject.width = this.width;
  41740. serializationObject.height = this.height;
  41741. serializationObject.subdivisions = this.subdivisions;
  41742. return serializationObject;
  41743. };
  41744. GroundGeometry.Parse = function (parsedGround, scene) {
  41745. if (scene.getGeometryByID(parsedGround.id)) {
  41746. return null; // null since geometry could be something else than a ground...
  41747. }
  41748. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41749. if (BABYLON.Tags) {
  41750. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41751. }
  41752. scene.pushGeometry(ground, true);
  41753. return ground;
  41754. };
  41755. return GroundGeometry;
  41756. }(_PrimitiveGeometry));
  41757. BABYLON.GroundGeometry = GroundGeometry;
  41758. /**
  41759. * Creates a tiled ground geometry
  41760. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41761. */
  41762. var TiledGroundGeometry = /** @class */ (function (_super) {
  41763. __extends(TiledGroundGeometry, _super);
  41764. /**
  41765. * Creates a tiled ground geometry
  41766. * @param id defines the unique ID of the geometry
  41767. * @param scene defines the hosting scene
  41768. * @param xmin defines the minimum value on X axis
  41769. * @param zmin defines the minimum value on Z axis
  41770. * @param xmax defines the maximum value on X axis
  41771. * @param zmax defines the maximum value on Z axis
  41772. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41773. * @param precision defines the precision to use when computing the tiles
  41774. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41775. * @param mesh defines the hosting mesh (can be null)
  41776. */
  41777. function TiledGroundGeometry(id, scene,
  41778. /**
  41779. * Defines the minimum value on X axis
  41780. */
  41781. xmin,
  41782. /**
  41783. * Defines the minimum value on Z axis
  41784. */
  41785. zmin,
  41786. /**
  41787. * Defines the maximum value on X axis
  41788. */
  41789. xmax,
  41790. /**
  41791. * Defines the maximum value on Z axis
  41792. */
  41793. zmax,
  41794. /**
  41795. * Defines the subdivisions to apply to the ground
  41796. */
  41797. subdivisions,
  41798. /**
  41799. * Defines the precision to use when computing the tiles
  41800. */
  41801. precision, canBeRegenerated, mesh) {
  41802. if (mesh === void 0) { mesh = null; }
  41803. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41804. _this.xmin = xmin;
  41805. _this.zmin = zmin;
  41806. _this.xmax = xmax;
  41807. _this.zmax = zmax;
  41808. _this.subdivisions = subdivisions;
  41809. _this.precision = precision;
  41810. return _this;
  41811. }
  41812. /** @hidden */
  41813. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41814. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41815. };
  41816. TiledGroundGeometry.prototype.copy = function (id) {
  41817. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41818. };
  41819. return TiledGroundGeometry;
  41820. }(_PrimitiveGeometry));
  41821. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41822. /**
  41823. * Creates a plane geometry
  41824. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41825. */
  41826. var PlaneGeometry = /** @class */ (function (_super) {
  41827. __extends(PlaneGeometry, _super);
  41828. /**
  41829. * Creates a plane geometry
  41830. * @param id defines the unique ID of the geometry
  41831. * @param scene defines the hosting scene
  41832. * @param size defines the size of the plane (width === height)
  41833. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41834. * @param mesh defines the hosting mesh (can be null)
  41835. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41836. */
  41837. function PlaneGeometry(id, scene,
  41838. /**
  41839. * Defines the size of the plane (width === height)
  41840. */
  41841. size, canBeRegenerated, mesh,
  41842. /**
  41843. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41844. */
  41845. side) {
  41846. if (mesh === void 0) { mesh = null; }
  41847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41848. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41849. _this.size = size;
  41850. _this.side = side;
  41851. return _this;
  41852. }
  41853. /** @hidden */
  41854. PlaneGeometry.prototype._regenerateVertexData = function () {
  41855. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41856. };
  41857. PlaneGeometry.prototype.copy = function (id) {
  41858. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41859. };
  41860. PlaneGeometry.prototype.serialize = function () {
  41861. var serializationObject = _super.prototype.serialize.call(this);
  41862. serializationObject.size = this.size;
  41863. return serializationObject;
  41864. };
  41865. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41866. if (scene.getGeometryByID(parsedPlane.id)) {
  41867. return null; // null since geometry could be something else than a ground...
  41868. }
  41869. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41870. if (BABYLON.Tags) {
  41871. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41872. }
  41873. scene.pushGeometry(plane, true);
  41874. return plane;
  41875. };
  41876. return PlaneGeometry;
  41877. }(_PrimitiveGeometry));
  41878. BABYLON.PlaneGeometry = PlaneGeometry;
  41879. /**
  41880. * Creates a torus knot geometry
  41881. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41882. */
  41883. var TorusKnotGeometry = /** @class */ (function (_super) {
  41884. __extends(TorusKnotGeometry, _super);
  41885. /**
  41886. * Creates a torus knot geometry
  41887. * @param id defines the unique ID of the geometry
  41888. * @param scene defines the hosting scene
  41889. * @param radius defines the radius of the torus knot
  41890. * @param tube defines the thickness of the torus knot tube
  41891. * @param radialSegments defines the number of radial segments
  41892. * @param tubularSegments defines the number of tubular segments
  41893. * @param p defines the first number of windings
  41894. * @param q defines the second number of windings
  41895. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41896. * @param mesh defines the hosting mesh (can be null)
  41897. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41898. */
  41899. function TorusKnotGeometry(id, scene,
  41900. /**
  41901. * Defines the radius of the torus knot
  41902. */
  41903. radius,
  41904. /**
  41905. * Defines the thickness of the torus knot tube
  41906. */
  41907. tube,
  41908. /**
  41909. * Defines the number of radial segments
  41910. */
  41911. radialSegments,
  41912. /**
  41913. * Defines the number of tubular segments
  41914. */
  41915. tubularSegments,
  41916. /**
  41917. * Defines the first number of windings
  41918. */
  41919. p,
  41920. /**
  41921. * Defines the second number of windings
  41922. */
  41923. q, canBeRegenerated, mesh,
  41924. /**
  41925. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41926. */
  41927. side) {
  41928. if (mesh === void 0) { mesh = null; }
  41929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41931. _this.radius = radius;
  41932. _this.tube = tube;
  41933. _this.radialSegments = radialSegments;
  41934. _this.tubularSegments = tubularSegments;
  41935. _this.p = p;
  41936. _this.q = q;
  41937. _this.side = side;
  41938. return _this;
  41939. }
  41940. /** @hidden */
  41941. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41942. 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 });
  41943. };
  41944. TorusKnotGeometry.prototype.copy = function (id) {
  41945. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41946. };
  41947. TorusKnotGeometry.prototype.serialize = function () {
  41948. var serializationObject = _super.prototype.serialize.call(this);
  41949. serializationObject.radius = this.radius;
  41950. serializationObject.tube = this.tube;
  41951. serializationObject.radialSegments = this.radialSegments;
  41952. serializationObject.tubularSegments = this.tubularSegments;
  41953. serializationObject.p = this.p;
  41954. serializationObject.q = this.q;
  41955. return serializationObject;
  41956. };
  41957. ;
  41958. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41959. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41960. return null; // null since geometry could be something else than a ground...
  41961. }
  41962. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41963. if (BABYLON.Tags) {
  41964. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41965. }
  41966. scene.pushGeometry(torusKnot, true);
  41967. return torusKnot;
  41968. };
  41969. return TorusKnotGeometry;
  41970. }(_PrimitiveGeometry));
  41971. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41972. //}
  41973. })(BABYLON || (BABYLON = {}));
  41974. //# sourceMappingURL=babylon.geometry.js.map
  41975. var BABYLON;
  41976. (function (BABYLON) {
  41977. /**
  41978. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41979. */
  41980. var PerformanceMonitor = /** @class */ (function () {
  41981. /**
  41982. * constructor
  41983. * @param frameSampleSize The number of samples required to saturate the sliding window
  41984. */
  41985. function PerformanceMonitor(frameSampleSize) {
  41986. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41987. this._enabled = true;
  41988. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41989. }
  41990. /**
  41991. * Samples current frame
  41992. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41993. */
  41994. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41995. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41996. if (!this._enabled)
  41997. return;
  41998. if (this._lastFrameTimeMs != null) {
  41999. var dt = timeMs - this._lastFrameTimeMs;
  42000. this._rollingFrameTime.add(dt);
  42001. }
  42002. this._lastFrameTimeMs = timeMs;
  42003. };
  42004. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42005. /**
  42006. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42007. */
  42008. get: function () {
  42009. return this._rollingFrameTime.average;
  42010. },
  42011. enumerable: true,
  42012. configurable: true
  42013. });
  42014. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42015. /**
  42016. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42017. */
  42018. get: function () {
  42019. return this._rollingFrameTime.variance;
  42020. },
  42021. enumerable: true,
  42022. configurable: true
  42023. });
  42024. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42025. /**
  42026. * Returns the frame time of the most recent frame
  42027. */
  42028. get: function () {
  42029. return this._rollingFrameTime.history(0);
  42030. },
  42031. enumerable: true,
  42032. configurable: true
  42033. });
  42034. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42035. /**
  42036. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42037. */
  42038. get: function () {
  42039. return 1000.0 / this._rollingFrameTime.average;
  42040. },
  42041. enumerable: true,
  42042. configurable: true
  42043. });
  42044. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42045. /**
  42046. * Returns the average framerate in frames per second using the most recent frame time
  42047. */
  42048. get: function () {
  42049. var history = this._rollingFrameTime.history(0);
  42050. if (history === 0) {
  42051. return 0;
  42052. }
  42053. return 1000.0 / history;
  42054. },
  42055. enumerable: true,
  42056. configurable: true
  42057. });
  42058. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42059. /**
  42060. * Returns true if enough samples have been taken to completely fill the sliding window
  42061. */
  42062. get: function () {
  42063. return this._rollingFrameTime.isSaturated();
  42064. },
  42065. enumerable: true,
  42066. configurable: true
  42067. });
  42068. /**
  42069. * Enables contributions to the sliding window sample set
  42070. */
  42071. PerformanceMonitor.prototype.enable = function () {
  42072. this._enabled = true;
  42073. };
  42074. /**
  42075. * Disables contributions to the sliding window sample set
  42076. * Samples will not be interpolated over the disabled period
  42077. */
  42078. PerformanceMonitor.prototype.disable = function () {
  42079. this._enabled = false;
  42080. //clear last sample to avoid interpolating over the disabled period when next enabled
  42081. this._lastFrameTimeMs = null;
  42082. };
  42083. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42084. /**
  42085. * Returns true if sampling is enabled
  42086. */
  42087. get: function () {
  42088. return this._enabled;
  42089. },
  42090. enumerable: true,
  42091. configurable: true
  42092. });
  42093. /**
  42094. * Resets performance monitor
  42095. */
  42096. PerformanceMonitor.prototype.reset = function () {
  42097. //clear last sample to avoid interpolating over the disabled period when next enabled
  42098. this._lastFrameTimeMs = null;
  42099. //wipe record
  42100. this._rollingFrameTime.reset();
  42101. };
  42102. return PerformanceMonitor;
  42103. }());
  42104. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42105. /**
  42106. * RollingAverage
  42107. *
  42108. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42109. */
  42110. var RollingAverage = /** @class */ (function () {
  42111. /**
  42112. * constructor
  42113. * @param length The number of samples required to saturate the sliding window
  42114. */
  42115. function RollingAverage(length) {
  42116. this._samples = new Array(length);
  42117. this.reset();
  42118. }
  42119. /**
  42120. * Adds a sample to the sample set
  42121. * @param v The sample value
  42122. */
  42123. RollingAverage.prototype.add = function (v) {
  42124. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42125. var delta;
  42126. //we need to check if we've already wrapped round
  42127. if (this.isSaturated()) {
  42128. //remove bottom of stack from mean
  42129. var bottomValue = this._samples[this._pos];
  42130. delta = bottomValue - this.average;
  42131. this.average -= delta / (this._sampleCount - 1);
  42132. this._m2 -= delta * (bottomValue - this.average);
  42133. }
  42134. else {
  42135. this._sampleCount++;
  42136. }
  42137. //add new value to mean
  42138. delta = v - this.average;
  42139. this.average += delta / (this._sampleCount);
  42140. this._m2 += delta * (v - this.average);
  42141. //set the new variance
  42142. this.variance = this._m2 / (this._sampleCount - 1);
  42143. this._samples[this._pos] = v;
  42144. this._pos++;
  42145. this._pos %= this._samples.length; //positive wrap around
  42146. };
  42147. /**
  42148. * Returns previously added values or null if outside of history or outside the sliding window domain
  42149. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42150. * @return Value previously recorded with add() or null if outside of range
  42151. */
  42152. RollingAverage.prototype.history = function (i) {
  42153. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42154. return 0;
  42155. }
  42156. var i0 = this._wrapPosition(this._pos - 1.0);
  42157. return this._samples[this._wrapPosition(i0 - i)];
  42158. };
  42159. /**
  42160. * Returns true if enough samples have been taken to completely fill the sliding window
  42161. * @return true if sample-set saturated
  42162. */
  42163. RollingAverage.prototype.isSaturated = function () {
  42164. return this._sampleCount >= this._samples.length;
  42165. };
  42166. /**
  42167. * Resets the rolling average (equivalent to 0 samples taken so far)
  42168. */
  42169. RollingAverage.prototype.reset = function () {
  42170. this.average = 0;
  42171. this.variance = 0;
  42172. this._sampleCount = 0;
  42173. this._pos = 0;
  42174. this._m2 = 0;
  42175. };
  42176. /**
  42177. * Wraps a value around the sample range boundaries
  42178. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42179. * @return Wrapped position in sample range
  42180. */
  42181. RollingAverage.prototype._wrapPosition = function (i) {
  42182. var max = this._samples.length;
  42183. return ((i % max) + max) % max;
  42184. };
  42185. return RollingAverage;
  42186. }());
  42187. BABYLON.RollingAverage = RollingAverage;
  42188. })(BABYLON || (BABYLON = {}));
  42189. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42190. var BABYLON;
  42191. (function (BABYLON) {
  42192. /**
  42193. * "Static Class" containing the most commonly used helper while dealing with material for
  42194. * rendering purpose.
  42195. *
  42196. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42197. *
  42198. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42199. */
  42200. var MaterialHelper = /** @class */ (function () {
  42201. function MaterialHelper() {
  42202. }
  42203. /**
  42204. * Bind the current view position to an effect.
  42205. * @param effect The effect to be bound
  42206. * @param scene The scene the eyes position is used from
  42207. */
  42208. MaterialHelper.BindEyePosition = function (effect, scene) {
  42209. if (scene._forcedViewPosition) {
  42210. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42211. return;
  42212. }
  42213. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42214. };
  42215. /**
  42216. * Helps preparing the defines values about the UVs in used in the effect.
  42217. * UVs are shared as much as we can accross channels in the shaders.
  42218. * @param texture The texture we are preparing the UVs for
  42219. * @param defines The defines to update
  42220. * @param key The channel key "diffuse", "specular"... used in the shader
  42221. */
  42222. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42223. defines._needUVs = true;
  42224. defines[key] = true;
  42225. if (texture.getTextureMatrix().isIdentity(true)) {
  42226. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42227. if (texture.coordinatesIndex === 0) {
  42228. defines["MAINUV1"] = true;
  42229. }
  42230. else {
  42231. defines["MAINUV2"] = true;
  42232. }
  42233. }
  42234. else {
  42235. defines[key + "DIRECTUV"] = 0;
  42236. }
  42237. };
  42238. /**
  42239. * Binds a texture matrix value to its corrsponding uniform
  42240. * @param texture The texture to bind the matrix for
  42241. * @param uniformBuffer The uniform buffer receivin the data
  42242. * @param key The channel key "diffuse", "specular"... used in the shader
  42243. */
  42244. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42245. var matrix = texture.getTextureMatrix();
  42246. if (!matrix.isIdentity(true)) {
  42247. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42248. }
  42249. };
  42250. /**
  42251. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42252. * @param mesh defines the current mesh
  42253. * @param scene defines the current scene
  42254. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42255. * @param pointsCloud defines if point cloud rendering has to be turned on
  42256. * @param fogEnabled defines if fog has to be turned on
  42257. * @param alphaTest defines if alpha testing has to be turned on
  42258. * @param defines defines the current list of defines
  42259. */
  42260. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42261. if (defines._areMiscDirty) {
  42262. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42263. defines["POINTSIZE"] = pointsCloud;
  42264. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42265. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42266. defines["ALPHATEST"] = alphaTest;
  42267. }
  42268. };
  42269. /**
  42270. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42271. * @param scene defines the current scene
  42272. * @param engine defines the current engine
  42273. * @param defines specifies the list of active defines
  42274. * @param useInstances defines if instances have to be turned on
  42275. * @param useClipPlane defines if clip plane have to be turned on
  42276. */
  42277. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42278. if (useClipPlane === void 0) { useClipPlane = null; }
  42279. var changed = false;
  42280. var useClipPlane1 = false;
  42281. var useClipPlane2 = false;
  42282. var useClipPlane3 = false;
  42283. var useClipPlane4 = false;
  42284. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42285. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42286. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42287. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42288. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42289. defines["CLIPPLANE"] = useClipPlane1;
  42290. changed = true;
  42291. }
  42292. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42293. defines["CLIPPLANE2"] = useClipPlane2;
  42294. changed = true;
  42295. }
  42296. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42297. defines["CLIPPLANE3"] = useClipPlane3;
  42298. changed = true;
  42299. }
  42300. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42301. defines["CLIPPLANE4"] = useClipPlane4;
  42302. changed = true;
  42303. }
  42304. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42305. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42306. changed = true;
  42307. }
  42308. if (defines["INSTANCES"] !== useInstances) {
  42309. defines["INSTANCES"] = useInstances;
  42310. changed = true;
  42311. }
  42312. if (changed) {
  42313. defines.markAsUnprocessed();
  42314. }
  42315. };
  42316. /**
  42317. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42318. * @param mesh The mesh containing the geometry data we will draw
  42319. * @param defines The defines to update
  42320. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42321. * @param useBones Precise whether bones should be used or not (override mesh info)
  42322. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42323. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42324. * @returns false if defines are considered not dirty and have not been checked
  42325. */
  42326. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42327. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42328. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42329. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42330. return false;
  42331. }
  42332. defines._normals = defines._needNormals;
  42333. defines._uvs = defines._needUVs;
  42334. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42335. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42336. defines["TANGENT"] = true;
  42337. }
  42338. if (defines._needUVs) {
  42339. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42340. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42341. }
  42342. else {
  42343. defines["UV1"] = false;
  42344. defines["UV2"] = false;
  42345. }
  42346. if (useVertexColor) {
  42347. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42348. defines["VERTEXCOLOR"] = hasVertexColors;
  42349. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42350. }
  42351. if (useBones) {
  42352. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42353. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42354. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42355. }
  42356. else {
  42357. defines["NUM_BONE_INFLUENCERS"] = 0;
  42358. defines["BonesPerMesh"] = 0;
  42359. }
  42360. }
  42361. if (useMorphTargets) {
  42362. var manager = mesh.morphTargetManager;
  42363. if (manager) {
  42364. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42365. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42366. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42367. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42368. }
  42369. else {
  42370. defines["MORPHTARGETS_TANGENT"] = false;
  42371. defines["MORPHTARGETS_NORMAL"] = false;
  42372. defines["MORPHTARGETS"] = false;
  42373. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42374. }
  42375. }
  42376. return true;
  42377. };
  42378. /**
  42379. * Prepares the defines related to the light information passed in parameter
  42380. * @param scene The scene we are intending to draw
  42381. * @param mesh The mesh the effect is compiling for
  42382. * @param defines The defines to update
  42383. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42384. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42385. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42386. * @returns true if normals will be required for the rest of the effect
  42387. */
  42388. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42389. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42390. if (disableLighting === void 0) { disableLighting = false; }
  42391. if (!defines._areLightsDirty) {
  42392. return defines._needNormals;
  42393. }
  42394. var lightIndex = 0;
  42395. var needNormals = false;
  42396. var needRebuild = false;
  42397. var lightmapMode = false;
  42398. var shadowEnabled = false;
  42399. var specularEnabled = false;
  42400. if (scene.lightsEnabled && !disableLighting) {
  42401. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42402. var light = _a[_i];
  42403. needNormals = true;
  42404. if (defines["LIGHT" + lightIndex] === undefined) {
  42405. needRebuild = true;
  42406. }
  42407. defines["LIGHT" + lightIndex] = true;
  42408. defines["SPOTLIGHT" + lightIndex] = false;
  42409. defines["HEMILIGHT" + lightIndex] = false;
  42410. defines["POINTLIGHT" + lightIndex] = false;
  42411. defines["DIRLIGHT" + lightIndex] = false;
  42412. light.prepareLightSpecificDefines(defines, lightIndex);
  42413. // FallOff.
  42414. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42415. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42416. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42417. switch (light.falloffType) {
  42418. case BABYLON.Light.FALLOFF_GLTF:
  42419. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42420. break;
  42421. case BABYLON.Light.FALLOFF_PHYSICAL:
  42422. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42423. break;
  42424. case BABYLON.Light.FALLOFF_STANDARD:
  42425. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42426. break;
  42427. }
  42428. // Specular
  42429. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42430. specularEnabled = true;
  42431. }
  42432. // Shadows
  42433. defines["SHADOW" + lightIndex] = false;
  42434. defines["SHADOWPCF" + lightIndex] = false;
  42435. defines["SHADOWPCSS" + lightIndex] = false;
  42436. defines["SHADOWPOISSON" + lightIndex] = false;
  42437. defines["SHADOWESM" + lightIndex] = false;
  42438. defines["SHADOWCUBE" + lightIndex] = false;
  42439. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42440. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42441. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42442. var shadowGenerator = light.getShadowGenerator();
  42443. if (shadowGenerator) {
  42444. var shadowMap = shadowGenerator.getShadowMap();
  42445. if (shadowMap) {
  42446. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42447. shadowEnabled = true;
  42448. shadowGenerator.prepareDefines(defines, lightIndex);
  42449. }
  42450. }
  42451. }
  42452. }
  42453. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42454. lightmapMode = true;
  42455. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42456. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42457. }
  42458. else {
  42459. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42460. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42461. }
  42462. lightIndex++;
  42463. if (lightIndex === maxSimultaneousLights)
  42464. break;
  42465. }
  42466. }
  42467. defines["SPECULARTERM"] = specularEnabled;
  42468. defines["SHADOWS"] = shadowEnabled;
  42469. // Resetting all other lights if any
  42470. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42471. if (defines["LIGHT" + index] !== undefined) {
  42472. defines["LIGHT" + index] = false;
  42473. defines["HEMILIGHT" + lightIndex] = false;
  42474. defines["POINTLIGHT" + lightIndex] = false;
  42475. defines["DIRLIGHT" + lightIndex] = false;
  42476. defines["SPOTLIGHT" + lightIndex] = false;
  42477. defines["SHADOW" + lightIndex] = false;
  42478. }
  42479. }
  42480. var caps = scene.getEngine().getCaps();
  42481. if (defines["SHADOWFLOAT"] === undefined) {
  42482. needRebuild = true;
  42483. }
  42484. defines["SHADOWFLOAT"] = shadowEnabled &&
  42485. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42486. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42487. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42488. if (needRebuild) {
  42489. defines.rebuild();
  42490. }
  42491. return needNormals;
  42492. };
  42493. /**
  42494. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42495. * that won t be acctive due to defines being turned off.
  42496. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42497. * @param samplersList The samplers list
  42498. * @param defines The defines helping in the list generation
  42499. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42500. */
  42501. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42502. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42503. var uniformsList;
  42504. var uniformBuffersList = null;
  42505. if (uniformsListOrOptions.uniformsNames) {
  42506. var options = uniformsListOrOptions;
  42507. uniformsList = options.uniformsNames;
  42508. uniformBuffersList = options.uniformBuffersNames;
  42509. samplersList = options.samplers;
  42510. defines = options.defines;
  42511. maxSimultaneousLights = options.maxSimultaneousLights;
  42512. }
  42513. else {
  42514. uniformsList = uniformsListOrOptions;
  42515. if (!samplersList) {
  42516. samplersList = [];
  42517. }
  42518. }
  42519. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42520. if (!defines["LIGHT" + lightIndex]) {
  42521. break;
  42522. }
  42523. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42524. if (uniformBuffersList) {
  42525. uniformBuffersList.push("Light" + lightIndex);
  42526. }
  42527. samplersList.push("shadowSampler" + lightIndex);
  42528. samplersList.push("depthSampler" + lightIndex);
  42529. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42530. samplersList.push("projectionLightSampler" + lightIndex);
  42531. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42532. }
  42533. }
  42534. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42535. uniformsList.push("morphTargetInfluences");
  42536. }
  42537. };
  42538. /**
  42539. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42540. * @param defines The defines to update while falling back
  42541. * @param fallbacks The authorized effect fallbacks
  42542. * @param maxSimultaneousLights The maximum number of lights allowed
  42543. * @param rank the current rank of the Effect
  42544. * @returns The newly affected rank
  42545. */
  42546. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42547. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42548. if (rank === void 0) { rank = 0; }
  42549. var lightFallbackRank = 0;
  42550. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42551. if (!defines["LIGHT" + lightIndex]) {
  42552. break;
  42553. }
  42554. if (lightIndex > 0) {
  42555. lightFallbackRank = rank + lightIndex;
  42556. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42557. }
  42558. if (!defines["SHADOWS"]) {
  42559. if (defines["SHADOW" + lightIndex]) {
  42560. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42561. }
  42562. if (defines["SHADOWPCF" + lightIndex]) {
  42563. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42564. }
  42565. if (defines["SHADOWPCSS" + lightIndex]) {
  42566. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42567. }
  42568. if (defines["SHADOWPOISSON" + lightIndex]) {
  42569. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42570. }
  42571. if (defines["SHADOWESM" + lightIndex]) {
  42572. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42573. }
  42574. }
  42575. }
  42576. return lightFallbackRank++;
  42577. };
  42578. /**
  42579. * Prepares the list of attributes required for morph targets according to the effect defines.
  42580. * @param attribs The current list of supported attribs
  42581. * @param mesh The mesh to prepare the morph targets attributes for
  42582. * @param defines The current Defines of the effect
  42583. */
  42584. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42585. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42586. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42587. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42588. var manager = mesh.morphTargetManager;
  42589. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42590. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42591. for (var index = 0; index < influencers; index++) {
  42592. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42593. if (normal) {
  42594. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42595. }
  42596. if (tangent) {
  42597. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42598. }
  42599. if (attribs.length > maxAttributesCount) {
  42600. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42601. }
  42602. }
  42603. }
  42604. };
  42605. /**
  42606. * Prepares the list of attributes required for bones according to the effect defines.
  42607. * @param attribs The current list of supported attribs
  42608. * @param mesh The mesh to prepare the bones attributes for
  42609. * @param defines The current Defines of the effect
  42610. * @param fallbacks The current efffect fallback strategy
  42611. */
  42612. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42613. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42614. fallbacks.addCPUSkinningFallback(0, mesh);
  42615. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42616. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42617. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42620. }
  42621. }
  42622. };
  42623. /**
  42624. * Prepares the list of attributes required for instances according to the effect defines.
  42625. * @param attribs The current list of supported attribs
  42626. * @param defines The current Defines of the effect
  42627. */
  42628. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42629. if (defines["INSTANCES"]) {
  42630. attribs.push("world0");
  42631. attribs.push("world1");
  42632. attribs.push("world2");
  42633. attribs.push("world3");
  42634. }
  42635. };
  42636. /**
  42637. * Binds the light shadow information to the effect for the given mesh.
  42638. * @param light The light containing the generator
  42639. * @param scene The scene the lights belongs to
  42640. * @param mesh The mesh we are binding the information to render
  42641. * @param lightIndex The light index in the effect used to render the mesh
  42642. * @param effect The effect we are binding the data to
  42643. */
  42644. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42645. if (light.shadowEnabled && mesh.receiveShadows) {
  42646. var shadowGenerator = light.getShadowGenerator();
  42647. if (shadowGenerator) {
  42648. shadowGenerator.bindShadowLight(lightIndex, effect);
  42649. }
  42650. }
  42651. };
  42652. /**
  42653. * Binds the light information to the effect.
  42654. * @param light The light containing the generator
  42655. * @param effect The effect we are binding the data to
  42656. * @param lightIndex The light index in the effect used to render
  42657. */
  42658. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42659. light.transferToEffect(effect, lightIndex + "");
  42660. };
  42661. /**
  42662. * Binds the lights information from the scene to the effect for the given mesh.
  42663. * @param scene The scene the lights belongs to
  42664. * @param mesh The mesh we are binding the information to render
  42665. * @param effect The effect we are binding the data to
  42666. * @param defines The generated defines for the effect
  42667. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42668. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42669. */
  42670. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42671. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42672. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42673. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42674. for (var i = 0; i < len; i++) {
  42675. var light = mesh._lightSources[i];
  42676. var iAsString = i.toString();
  42677. var scaledIntensity = light.getScaledIntensity();
  42678. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42679. MaterialHelper.BindLightProperties(light, effect, i);
  42680. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42681. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42682. if (defines["SPECULARTERM"]) {
  42683. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42684. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42685. }
  42686. // Shadows
  42687. if (scene.shadowsEnabled) {
  42688. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42689. }
  42690. light._uniformBuffer.update();
  42691. }
  42692. };
  42693. /**
  42694. * Binds the fog information from the scene to the effect for the given mesh.
  42695. * @param scene The scene the lights belongs to
  42696. * @param mesh The mesh we are binding the information to render
  42697. * @param effect The effect we are binding the data to
  42698. * @param linearSpace Defines if the fog effect is applied in linear space
  42699. */
  42700. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42701. if (linearSpace === void 0) { linearSpace = false; }
  42702. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42703. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42704. // Convert fog color to linear space if used in a linear space computed shader.
  42705. if (linearSpace) {
  42706. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42707. effect.setColor3("vFogColor", this._tempFogColor);
  42708. }
  42709. else {
  42710. effect.setColor3("vFogColor", scene.fogColor);
  42711. }
  42712. }
  42713. };
  42714. /**
  42715. * Binds the bones information from the mesh to the effect.
  42716. * @param mesh The mesh we are binding the information to render
  42717. * @param effect The effect we are binding the data to
  42718. */
  42719. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42720. if (!effect || !mesh) {
  42721. return;
  42722. }
  42723. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42724. mesh.computeBonesUsingShaders = false;
  42725. }
  42726. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42727. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42728. if (matrices) {
  42729. effect.setMatrices("mBones", matrices);
  42730. }
  42731. }
  42732. };
  42733. /**
  42734. * Binds the morph targets information from the mesh to the effect.
  42735. * @param abstractMesh The mesh we are binding the information to render
  42736. * @param effect The effect we are binding the data to
  42737. */
  42738. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42739. var manager = abstractMesh.morphTargetManager;
  42740. if (!abstractMesh || !manager) {
  42741. return;
  42742. }
  42743. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42744. };
  42745. /**
  42746. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42747. * @param defines The generated defines used in the effect
  42748. * @param effect The effect we are binding the data to
  42749. * @param scene The scene we are willing to render with logarithmic scale for
  42750. */
  42751. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42752. if (defines["LOGARITHMICDEPTH"]) {
  42753. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42754. }
  42755. };
  42756. /**
  42757. * Binds the clip plane information from the scene to the effect.
  42758. * @param scene The scene the clip plane information are extracted from
  42759. * @param effect The effect we are binding the data to
  42760. */
  42761. MaterialHelper.BindClipPlane = function (effect, scene) {
  42762. if (scene.clipPlane) {
  42763. var clipPlane = scene.clipPlane;
  42764. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42765. }
  42766. if (scene.clipPlane2) {
  42767. var clipPlane = scene.clipPlane2;
  42768. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42769. }
  42770. if (scene.clipPlane3) {
  42771. var clipPlane = scene.clipPlane3;
  42772. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42773. }
  42774. if (scene.clipPlane4) {
  42775. var clipPlane = scene.clipPlane4;
  42776. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42777. }
  42778. };
  42779. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42780. return MaterialHelper;
  42781. }());
  42782. BABYLON.MaterialHelper = MaterialHelper;
  42783. })(BABYLON || (BABYLON = {}));
  42784. //# sourceMappingURL=babylon.materialHelper.js.map
  42785. var BABYLON;
  42786. (function (BABYLON) {
  42787. /**
  42788. * Base class of materials working in push mode in babylon JS
  42789. * @hidden
  42790. */
  42791. var PushMaterial = /** @class */ (function (_super) {
  42792. __extends(PushMaterial, _super);
  42793. function PushMaterial(name, scene) {
  42794. var _this = _super.call(this, name, scene) || this;
  42795. _this._normalMatrix = new BABYLON.Matrix();
  42796. _this.storeEffectOnSubMeshes = true;
  42797. return _this;
  42798. }
  42799. PushMaterial.prototype.getEffect = function () {
  42800. return this._activeEffect;
  42801. };
  42802. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42803. if (!mesh) {
  42804. return false;
  42805. }
  42806. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42807. return true;
  42808. }
  42809. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42810. };
  42811. /**
  42812. * Binds the given world matrix to the active effect
  42813. *
  42814. * @param world the matrix to bind
  42815. */
  42816. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42817. this._activeEffect.setMatrix("world", world);
  42818. };
  42819. /**
  42820. * Binds the given normal matrix to the active effect
  42821. *
  42822. * @param normalMatrix the matrix to bind
  42823. */
  42824. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42825. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42826. };
  42827. PushMaterial.prototype.bind = function (world, mesh) {
  42828. if (!mesh) {
  42829. return;
  42830. }
  42831. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42832. };
  42833. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42834. if (effect === void 0) { effect = null; }
  42835. _super.prototype._afterBind.call(this, mesh);
  42836. this.getScene()._cachedEffect = effect;
  42837. };
  42838. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42839. if (visibility === void 0) { visibility = 1; }
  42840. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42841. };
  42842. return PushMaterial;
  42843. }(BABYLON.Material));
  42844. BABYLON.PushMaterial = PushMaterial;
  42845. })(BABYLON || (BABYLON = {}));
  42846. //# sourceMappingURL=babylon.pushMaterial.js.map
  42847. var BABYLON;
  42848. (function (BABYLON) {
  42849. /** @hidden */
  42850. var StandardMaterialDefines = /** @class */ (function (_super) {
  42851. __extends(StandardMaterialDefines, _super);
  42852. function StandardMaterialDefines() {
  42853. var _this = _super.call(this) || this;
  42854. _this.MAINUV1 = false;
  42855. _this.MAINUV2 = false;
  42856. _this.DIFFUSE = false;
  42857. _this.DIFFUSEDIRECTUV = 0;
  42858. _this.AMBIENT = false;
  42859. _this.AMBIENTDIRECTUV = 0;
  42860. _this.OPACITY = false;
  42861. _this.OPACITYDIRECTUV = 0;
  42862. _this.OPACITYRGB = false;
  42863. _this.REFLECTION = false;
  42864. _this.EMISSIVE = false;
  42865. _this.EMISSIVEDIRECTUV = 0;
  42866. _this.SPECULAR = false;
  42867. _this.SPECULARDIRECTUV = 0;
  42868. _this.BUMP = false;
  42869. _this.BUMPDIRECTUV = 0;
  42870. _this.PARALLAX = false;
  42871. _this.PARALLAXOCCLUSION = false;
  42872. _this.SPECULAROVERALPHA = false;
  42873. _this.CLIPPLANE = false;
  42874. _this.CLIPPLANE2 = false;
  42875. _this.CLIPPLANE3 = false;
  42876. _this.CLIPPLANE4 = false;
  42877. _this.ALPHATEST = false;
  42878. _this.DEPTHPREPASS = false;
  42879. _this.ALPHAFROMDIFFUSE = false;
  42880. _this.POINTSIZE = false;
  42881. _this.FOG = false;
  42882. _this.SPECULARTERM = false;
  42883. _this.DIFFUSEFRESNEL = false;
  42884. _this.OPACITYFRESNEL = false;
  42885. _this.REFLECTIONFRESNEL = false;
  42886. _this.REFRACTIONFRESNEL = false;
  42887. _this.EMISSIVEFRESNEL = false;
  42888. _this.FRESNEL = false;
  42889. _this.NORMAL = false;
  42890. _this.UV1 = false;
  42891. _this.UV2 = false;
  42892. _this.VERTEXCOLOR = false;
  42893. _this.VERTEXALPHA = false;
  42894. _this.NUM_BONE_INFLUENCERS = 0;
  42895. _this.BonesPerMesh = 0;
  42896. _this.INSTANCES = false;
  42897. _this.GLOSSINESS = false;
  42898. _this.ROUGHNESS = false;
  42899. _this.EMISSIVEASILLUMINATION = false;
  42900. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42901. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42902. _this.LIGHTMAP = false;
  42903. _this.LIGHTMAPDIRECTUV = 0;
  42904. _this.OBJECTSPACE_NORMALMAP = false;
  42905. _this.USELIGHTMAPASSHADOWMAP = false;
  42906. _this.REFLECTIONMAP_3D = false;
  42907. _this.REFLECTIONMAP_SPHERICAL = false;
  42908. _this.REFLECTIONMAP_PLANAR = false;
  42909. _this.REFLECTIONMAP_CUBIC = false;
  42910. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42911. _this.REFLECTIONMAP_PROJECTION = false;
  42912. _this.REFLECTIONMAP_SKYBOX = false;
  42913. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42914. _this.REFLECTIONMAP_EXPLICIT = false;
  42915. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42916. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42917. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42918. _this.INVERTCUBICMAP = false;
  42919. _this.LOGARITHMICDEPTH = false;
  42920. _this.REFRACTION = false;
  42921. _this.REFRACTIONMAP_3D = false;
  42922. _this.REFLECTIONOVERALPHA = false;
  42923. _this.TWOSIDEDLIGHTING = false;
  42924. _this.SHADOWFLOAT = false;
  42925. _this.MORPHTARGETS = false;
  42926. _this.MORPHTARGETS_NORMAL = false;
  42927. _this.MORPHTARGETS_TANGENT = false;
  42928. _this.NUM_MORPH_INFLUENCERS = 0;
  42929. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42930. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42931. _this.IMAGEPROCESSING = false;
  42932. _this.VIGNETTE = false;
  42933. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42934. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42935. _this.TONEMAPPING = false;
  42936. _this.TONEMAPPING_ACES = false;
  42937. _this.CONTRAST = false;
  42938. _this.COLORCURVES = false;
  42939. _this.COLORGRADING = false;
  42940. _this.COLORGRADING3D = false;
  42941. _this.SAMPLER3DGREENDEPTH = false;
  42942. _this.SAMPLER3DBGRMAP = false;
  42943. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42944. /**
  42945. * If the reflection texture on this material is in linear color space
  42946. * @hidden
  42947. */
  42948. _this.IS_REFLECTION_LINEAR = false;
  42949. /**
  42950. * If the refraction texture on this material is in linear color space
  42951. * @hidden
  42952. */
  42953. _this.IS_REFRACTION_LINEAR = false;
  42954. _this.EXPOSURE = false;
  42955. _this.rebuild();
  42956. return _this;
  42957. }
  42958. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42959. var modes = [
  42960. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42961. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42962. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42963. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42964. ];
  42965. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42966. var mode = modes_1[_i];
  42967. this[mode] = (mode === modeToEnable);
  42968. }
  42969. };
  42970. return StandardMaterialDefines;
  42971. }(BABYLON.MaterialDefines));
  42972. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42973. /**
  42974. * This is the default material used in Babylon. It is the best trade off between quality
  42975. * and performances.
  42976. * @see http://doc.babylonjs.com/babylon101/materials
  42977. */
  42978. var StandardMaterial = /** @class */ (function (_super) {
  42979. __extends(StandardMaterial, _super);
  42980. /**
  42981. * Instantiates a new standard material.
  42982. * This is the default material used in Babylon. It is the best trade off between quality
  42983. * and performances.
  42984. * @see http://doc.babylonjs.com/babylon101/materials
  42985. * @param name Define the name of the material in the scene
  42986. * @param scene Define the scene the material belong to
  42987. */
  42988. function StandardMaterial(name, scene) {
  42989. var _this = _super.call(this, name, scene) || this;
  42990. /**
  42991. * The color of the material lit by the environmental background lighting.
  42992. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  42993. */
  42994. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42995. /**
  42996. * The basic color of the material as viewed under a light.
  42997. */
  42998. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42999. /**
  43000. * Define how the color and intensity of the highlight given by the light in the material.
  43001. */
  43002. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43003. /**
  43004. * Define the color of the material as if self lit.
  43005. * This will be mixed in the final result even in the absence of light.
  43006. */
  43007. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43008. /**
  43009. * Defines how sharp are the highlights in the material.
  43010. * The bigger the value the sharper giving a more glossy feeling to the result.
  43011. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43012. */
  43013. _this.specularPower = 64;
  43014. _this._useAlphaFromDiffuseTexture = false;
  43015. _this._useEmissiveAsIllumination = false;
  43016. _this._linkEmissiveWithDiffuse = false;
  43017. _this._useSpecularOverAlpha = false;
  43018. _this._useReflectionOverAlpha = false;
  43019. _this._disableLighting = false;
  43020. _this._useObjectSpaceNormalMap = false;
  43021. _this._useParallax = false;
  43022. _this._useParallaxOcclusion = false;
  43023. /**
  43024. * 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.
  43025. */
  43026. _this.parallaxScaleBias = 0.05;
  43027. _this._roughness = 0;
  43028. /**
  43029. * In case of refraction, define the value of the indice of refraction.
  43030. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43031. */
  43032. _this.indexOfRefraction = 0.98;
  43033. /**
  43034. * Invert the refraction texture alongside the y axis.
  43035. * It can be usefull with procedural textures or probe for instance.
  43036. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43037. */
  43038. _this.invertRefractionY = true;
  43039. /**
  43040. * Defines the alpha limits in alpha test mode.
  43041. */
  43042. _this.alphaCutOff = 0.4;
  43043. _this._useLightmapAsShadowmap = false;
  43044. _this._useReflectionFresnelFromSpecular = false;
  43045. _this._useGlossinessFromSpecularMapAlpha = false;
  43046. _this._maxSimultaneousLights = 4;
  43047. _this._invertNormalMapX = false;
  43048. _this._invertNormalMapY = false;
  43049. _this._twoSidedLighting = false;
  43050. _this._renderTargets = new BABYLON.SmartArray(16);
  43051. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43052. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43053. // Setup the default processing configuration to the scene.
  43054. _this._attachImageProcessingConfiguration(null);
  43055. _this.getRenderTargetTextures = function () {
  43056. _this._renderTargets.reset();
  43057. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43058. _this._renderTargets.push(_this._reflectionTexture);
  43059. }
  43060. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43061. _this._renderTargets.push(_this._refractionTexture);
  43062. }
  43063. return _this._renderTargets;
  43064. };
  43065. return _this;
  43066. }
  43067. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43068. /**
  43069. * Gets the image processing configuration used either in this material.
  43070. */
  43071. get: function () {
  43072. return this._imageProcessingConfiguration;
  43073. },
  43074. /**
  43075. * Sets the Default image processing configuration used either in the this material.
  43076. *
  43077. * If sets to null, the scene one is in use.
  43078. */
  43079. set: function (value) {
  43080. this._attachImageProcessingConfiguration(value);
  43081. // Ensure the effect will be rebuilt.
  43082. this._markAllSubMeshesAsTexturesDirty();
  43083. },
  43084. enumerable: true,
  43085. configurable: true
  43086. });
  43087. /**
  43088. * Attaches a new image processing configuration to the Standard Material.
  43089. * @param configuration
  43090. */
  43091. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43092. var _this = this;
  43093. if (configuration === this._imageProcessingConfiguration) {
  43094. return;
  43095. }
  43096. // Detaches observer.
  43097. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43098. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43099. }
  43100. // Pick the scene configuration if needed.
  43101. if (!configuration) {
  43102. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43103. }
  43104. else {
  43105. this._imageProcessingConfiguration = configuration;
  43106. }
  43107. // Attaches observer.
  43108. if (this._imageProcessingConfiguration) {
  43109. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43110. _this._markAllSubMeshesAsImageProcessingDirty();
  43111. });
  43112. }
  43113. };
  43114. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43115. /**
  43116. * Gets wether the color curves effect is enabled.
  43117. */
  43118. get: function () {
  43119. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43120. },
  43121. /**
  43122. * Sets wether the color curves effect is enabled.
  43123. */
  43124. set: function (value) {
  43125. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43126. },
  43127. enumerable: true,
  43128. configurable: true
  43129. });
  43130. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43131. /**
  43132. * Gets wether the color grading effect is enabled.
  43133. */
  43134. get: function () {
  43135. return this.imageProcessingConfiguration.colorGradingEnabled;
  43136. },
  43137. /**
  43138. * Gets wether the color grading effect is enabled.
  43139. */
  43140. set: function (value) {
  43141. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43142. },
  43143. enumerable: true,
  43144. configurable: true
  43145. });
  43146. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43147. /**
  43148. * Gets wether tonemapping is enabled or not.
  43149. */
  43150. get: function () {
  43151. return this._imageProcessingConfiguration.toneMappingEnabled;
  43152. },
  43153. /**
  43154. * Sets wether tonemapping is enabled or not
  43155. */
  43156. set: function (value) {
  43157. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43158. },
  43159. enumerable: true,
  43160. configurable: true
  43161. });
  43162. ;
  43163. ;
  43164. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43165. /**
  43166. * The camera exposure used on this material.
  43167. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43168. * This corresponds to a photographic exposure.
  43169. */
  43170. get: function () {
  43171. return this._imageProcessingConfiguration.exposure;
  43172. },
  43173. /**
  43174. * The camera exposure used on this material.
  43175. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43176. * This corresponds to a photographic exposure.
  43177. */
  43178. set: function (value) {
  43179. this._imageProcessingConfiguration.exposure = value;
  43180. },
  43181. enumerable: true,
  43182. configurable: true
  43183. });
  43184. ;
  43185. ;
  43186. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43187. /**
  43188. * Gets The camera contrast used on this material.
  43189. */
  43190. get: function () {
  43191. return this._imageProcessingConfiguration.contrast;
  43192. },
  43193. /**
  43194. * Sets The camera contrast used on this material.
  43195. */
  43196. set: function (value) {
  43197. this._imageProcessingConfiguration.contrast = value;
  43198. },
  43199. enumerable: true,
  43200. configurable: true
  43201. });
  43202. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43203. /**
  43204. * Gets the Color Grading 2D Lookup Texture.
  43205. */
  43206. get: function () {
  43207. return this._imageProcessingConfiguration.colorGradingTexture;
  43208. },
  43209. /**
  43210. * Sets the Color Grading 2D Lookup Texture.
  43211. */
  43212. set: function (value) {
  43213. this._imageProcessingConfiguration.colorGradingTexture = value;
  43214. },
  43215. enumerable: true,
  43216. configurable: true
  43217. });
  43218. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43219. /**
  43220. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43221. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43222. * 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;
  43223. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43224. */
  43225. get: function () {
  43226. return this._imageProcessingConfiguration.colorCurves;
  43227. },
  43228. /**
  43229. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43230. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43231. * 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;
  43232. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43233. */
  43234. set: function (value) {
  43235. this._imageProcessingConfiguration.colorCurves = value;
  43236. },
  43237. enumerable: true,
  43238. configurable: true
  43239. });
  43240. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43241. /**
  43242. * Gets a boolean indicating that current material needs to register RTT
  43243. */
  43244. get: function () {
  43245. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43246. return true;
  43247. }
  43248. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43249. return true;
  43250. }
  43251. return false;
  43252. },
  43253. enumerable: true,
  43254. configurable: true
  43255. });
  43256. /**
  43257. * Gets the current class name of the material e.g. "StandardMaterial"
  43258. * Mainly use in serialization.
  43259. * @returns the class name
  43260. */
  43261. StandardMaterial.prototype.getClassName = function () {
  43262. return "StandardMaterial";
  43263. };
  43264. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43265. /**
  43266. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43267. * You can try switching to logarithmic depth.
  43268. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43269. */
  43270. get: function () {
  43271. return this._useLogarithmicDepth;
  43272. },
  43273. set: function (value) {
  43274. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43275. this._markAllSubMeshesAsMiscDirty();
  43276. },
  43277. enumerable: true,
  43278. configurable: true
  43279. });
  43280. /**
  43281. * Specifies if the material will require alpha blending
  43282. * @returns a boolean specifying if alpha blending is needed
  43283. */
  43284. StandardMaterial.prototype.needAlphaBlending = function () {
  43285. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43286. };
  43287. /**
  43288. * Specifies if this material should be rendered in alpha test mode
  43289. * @returns a boolean specifying if an alpha test is needed.
  43290. */
  43291. StandardMaterial.prototype.needAlphaTesting = function () {
  43292. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43293. };
  43294. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43295. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43296. };
  43297. /**
  43298. * Get the texture used for alpha test purpose.
  43299. * @returns the diffuse texture in case of the standard material.
  43300. */
  43301. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43302. return this._diffuseTexture;
  43303. };
  43304. /**
  43305. * Get if the submesh is ready to be used and all its information available.
  43306. * Child classes can use it to update shaders
  43307. * @param mesh defines the mesh to check
  43308. * @param subMesh defines which submesh to check
  43309. * @param useInstances specifies that instances should be used
  43310. * @returns a boolean indicating that the submesh is ready or not
  43311. */
  43312. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43313. if (useInstances === void 0) { useInstances = false; }
  43314. if (subMesh.effect && this.isFrozen) {
  43315. if (this._wasPreviouslyReady) {
  43316. return true;
  43317. }
  43318. }
  43319. if (!subMesh._materialDefines) {
  43320. subMesh._materialDefines = new StandardMaterialDefines();
  43321. }
  43322. var scene = this.getScene();
  43323. var defines = subMesh._materialDefines;
  43324. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43325. if (defines._renderId === scene.getRenderId()) {
  43326. return true;
  43327. }
  43328. }
  43329. var engine = scene.getEngine();
  43330. // Lights
  43331. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43332. // Textures
  43333. if (defines._areTexturesDirty) {
  43334. defines._needUVs = false;
  43335. defines.MAINUV1 = false;
  43336. defines.MAINUV2 = false;
  43337. if (scene.texturesEnabled) {
  43338. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43339. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43340. return false;
  43341. }
  43342. else {
  43343. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43344. }
  43345. }
  43346. else {
  43347. defines.DIFFUSE = false;
  43348. }
  43349. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43350. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43351. return false;
  43352. }
  43353. else {
  43354. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43355. }
  43356. }
  43357. else {
  43358. defines.AMBIENT = false;
  43359. }
  43360. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43361. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43362. return false;
  43363. }
  43364. else {
  43365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43366. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43367. }
  43368. }
  43369. else {
  43370. defines.OPACITY = false;
  43371. }
  43372. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43373. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43374. return false;
  43375. }
  43376. else {
  43377. defines._needNormals = true;
  43378. defines.REFLECTION = true;
  43379. defines.ROUGHNESS = (this._roughness > 0);
  43380. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43381. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43382. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43383. switch (this._reflectionTexture.coordinatesMode) {
  43384. case BABYLON.Texture.EXPLICIT_MODE:
  43385. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43386. break;
  43387. case BABYLON.Texture.PLANAR_MODE:
  43388. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43389. break;
  43390. case BABYLON.Texture.PROJECTION_MODE:
  43391. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43392. break;
  43393. case BABYLON.Texture.SKYBOX_MODE:
  43394. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43395. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43396. break;
  43397. case BABYLON.Texture.SPHERICAL_MODE:
  43398. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43399. break;
  43400. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43401. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43402. break;
  43403. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43404. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43405. break;
  43406. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43407. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43408. break;
  43409. case BABYLON.Texture.CUBIC_MODE:
  43410. case BABYLON.Texture.INVCUBIC_MODE:
  43411. default:
  43412. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43413. break;
  43414. }
  43415. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43416. }
  43417. }
  43418. else {
  43419. defines.REFLECTION = false;
  43420. }
  43421. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43422. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43423. return false;
  43424. }
  43425. else {
  43426. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43427. }
  43428. }
  43429. else {
  43430. defines.EMISSIVE = false;
  43431. }
  43432. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43433. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43434. return false;
  43435. }
  43436. else {
  43437. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43438. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43439. }
  43440. }
  43441. else {
  43442. defines.LIGHTMAP = false;
  43443. }
  43444. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43445. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43446. return false;
  43447. }
  43448. else {
  43449. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43450. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43451. }
  43452. }
  43453. else {
  43454. defines.SPECULAR = false;
  43455. }
  43456. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43457. // Bump texure can not be not blocking.
  43458. if (!this._bumpTexture.isReady()) {
  43459. return false;
  43460. }
  43461. else {
  43462. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43463. defines.PARALLAX = this._useParallax;
  43464. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43465. }
  43466. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43467. }
  43468. else {
  43469. defines.BUMP = false;
  43470. }
  43471. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43472. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43473. return false;
  43474. }
  43475. else {
  43476. defines._needUVs = true;
  43477. defines.REFRACTION = true;
  43478. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43479. }
  43480. }
  43481. else {
  43482. defines.REFRACTION = false;
  43483. }
  43484. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43485. }
  43486. else {
  43487. defines.DIFFUSE = false;
  43488. defines.AMBIENT = false;
  43489. defines.OPACITY = false;
  43490. defines.REFLECTION = false;
  43491. defines.EMISSIVE = false;
  43492. defines.LIGHTMAP = false;
  43493. defines.BUMP = false;
  43494. defines.REFRACTION = false;
  43495. }
  43496. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43497. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43498. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43499. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43500. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43501. }
  43502. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43503. if (!this._imageProcessingConfiguration.isReady()) {
  43504. return false;
  43505. }
  43506. this._imageProcessingConfiguration.prepareDefines(defines);
  43507. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43508. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43509. }
  43510. if (defines._areFresnelDirty) {
  43511. if (StandardMaterial.FresnelEnabled) {
  43512. // Fresnel
  43513. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43514. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43515. this._reflectionFresnelParameters) {
  43516. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43517. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43518. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43519. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43520. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43521. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43522. defines._needNormals = true;
  43523. defines.FRESNEL = true;
  43524. }
  43525. }
  43526. else {
  43527. defines.FRESNEL = false;
  43528. }
  43529. }
  43530. // Misc.
  43531. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43532. // Attribs
  43533. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43534. // Values that need to be evaluated on every frame
  43535. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43536. // Get correct effect
  43537. if (defines.isDirty) {
  43538. defines.markAsProcessed();
  43539. scene.resetCachedMaterial();
  43540. // Fallbacks
  43541. var fallbacks = new BABYLON.EffectFallbacks();
  43542. if (defines.REFLECTION) {
  43543. fallbacks.addFallback(0, "REFLECTION");
  43544. }
  43545. if (defines.SPECULAR) {
  43546. fallbacks.addFallback(0, "SPECULAR");
  43547. }
  43548. if (defines.BUMP) {
  43549. fallbacks.addFallback(0, "BUMP");
  43550. }
  43551. if (defines.PARALLAX) {
  43552. fallbacks.addFallback(1, "PARALLAX");
  43553. }
  43554. if (defines.PARALLAXOCCLUSION) {
  43555. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43556. }
  43557. if (defines.SPECULAROVERALPHA) {
  43558. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43559. }
  43560. if (defines.FOG) {
  43561. fallbacks.addFallback(1, "FOG");
  43562. }
  43563. if (defines.POINTSIZE) {
  43564. fallbacks.addFallback(0, "POINTSIZE");
  43565. }
  43566. if (defines.LOGARITHMICDEPTH) {
  43567. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43568. }
  43569. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43570. if (defines.SPECULARTERM) {
  43571. fallbacks.addFallback(0, "SPECULARTERM");
  43572. }
  43573. if (defines.DIFFUSEFRESNEL) {
  43574. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43575. }
  43576. if (defines.OPACITYFRESNEL) {
  43577. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43578. }
  43579. if (defines.REFLECTIONFRESNEL) {
  43580. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43581. }
  43582. if (defines.EMISSIVEFRESNEL) {
  43583. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43584. }
  43585. if (defines.FRESNEL) {
  43586. fallbacks.addFallback(4, "FRESNEL");
  43587. }
  43588. //Attributes
  43589. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43590. if (defines.NORMAL) {
  43591. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43592. }
  43593. if (defines.UV1) {
  43594. attribs.push(BABYLON.VertexBuffer.UVKind);
  43595. }
  43596. if (defines.UV2) {
  43597. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43598. }
  43599. if (defines.VERTEXCOLOR) {
  43600. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43601. }
  43602. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43603. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43604. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43605. var shaderName = "default";
  43606. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43607. "vFogInfos", "vFogColor", "pointSize",
  43608. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43609. "mBones",
  43610. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43611. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43612. "vReflectionPosition", "vReflectionSize",
  43613. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43614. ];
  43615. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43616. var uniformBuffers = ["Material", "Scene"];
  43617. if (BABYLON.ImageProcessingConfiguration) {
  43618. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43619. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43620. }
  43621. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43622. uniformsNames: uniforms,
  43623. uniformBuffersNames: uniformBuffers,
  43624. samplers: samplers,
  43625. defines: defines,
  43626. maxSimultaneousLights: this._maxSimultaneousLights
  43627. });
  43628. if (this.customShaderNameResolve) {
  43629. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43630. }
  43631. var join = defines.toString();
  43632. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43633. attributes: attribs,
  43634. uniformsNames: uniforms,
  43635. uniformBuffersNames: uniformBuffers,
  43636. samplers: samplers,
  43637. defines: join,
  43638. fallbacks: fallbacks,
  43639. onCompiled: this.onCompiled,
  43640. onError: this.onError,
  43641. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43642. }, engine), defines);
  43643. this.buildUniformLayout();
  43644. }
  43645. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43646. return false;
  43647. }
  43648. defines._renderId = scene.getRenderId();
  43649. this._wasPreviouslyReady = true;
  43650. return true;
  43651. };
  43652. /**
  43653. * Builds the material UBO layouts.
  43654. * Used internally during the effect preparation.
  43655. */
  43656. StandardMaterial.prototype.buildUniformLayout = function () {
  43657. // Order is important !
  43658. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43659. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43660. this._uniformBuffer.addUniform("opacityParts", 4);
  43661. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43662. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43663. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43664. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43665. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43666. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43667. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43668. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43669. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43670. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43671. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43672. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43673. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43674. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43675. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43676. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43677. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43678. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43679. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43680. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43681. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43682. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43683. this._uniformBuffer.addUniform("specularMatrix", 16);
  43684. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43685. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43686. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43687. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43688. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43689. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43690. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43691. this._uniformBuffer.addUniform("pointSize", 1);
  43692. this._uniformBuffer.create();
  43693. };
  43694. /**
  43695. * Unbinds the material from the mesh
  43696. */
  43697. StandardMaterial.prototype.unbind = function () {
  43698. if (this._activeEffect) {
  43699. var needFlag = false;
  43700. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43701. this._activeEffect.setTexture("reflection2DSampler", null);
  43702. needFlag = true;
  43703. }
  43704. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43705. this._activeEffect.setTexture("refraction2DSampler", null);
  43706. needFlag = true;
  43707. }
  43708. if (needFlag) {
  43709. this._markAllSubMeshesAsTexturesDirty();
  43710. }
  43711. }
  43712. _super.prototype.unbind.call(this);
  43713. };
  43714. /**
  43715. * Binds the submesh to this material by preparing the effect and shader to draw
  43716. * @param world defines the world transformation matrix
  43717. * @param mesh defines the mesh containing the submesh
  43718. * @param subMesh defines the submesh to bind the material to
  43719. */
  43720. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43721. var scene = this.getScene();
  43722. var defines = subMesh._materialDefines;
  43723. if (!defines) {
  43724. return;
  43725. }
  43726. var effect = subMesh.effect;
  43727. if (!effect) {
  43728. return;
  43729. }
  43730. this._activeEffect = effect;
  43731. // Matrices
  43732. this.bindOnlyWorldMatrix(world);
  43733. // Normal Matrix
  43734. if (defines.OBJECTSPACE_NORMALMAP) {
  43735. world.toNormalMatrix(this._normalMatrix);
  43736. this.bindOnlyNormalMatrix(this._normalMatrix);
  43737. }
  43738. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43739. // Bones
  43740. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43741. if (mustRebind) {
  43742. this._uniformBuffer.bindToEffect(effect, "Material");
  43743. this.bindViewProjection(effect);
  43744. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43745. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43746. // Fresnel
  43747. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43748. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43749. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43750. }
  43751. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43752. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43753. }
  43754. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43755. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43756. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43757. }
  43758. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43759. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43760. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43761. }
  43762. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43763. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43764. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43765. }
  43766. }
  43767. // Textures
  43768. if (scene.texturesEnabled) {
  43769. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43770. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43771. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43772. if (this._diffuseTexture.hasAlpha) {
  43773. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43774. }
  43775. }
  43776. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43777. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43778. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43779. }
  43780. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43781. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43782. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43783. }
  43784. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43785. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43786. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43787. if (this._reflectionTexture.boundingBoxSize) {
  43788. var cubeTexture = this._reflectionTexture;
  43789. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43790. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43791. }
  43792. }
  43793. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43794. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43795. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43796. }
  43797. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43798. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43799. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43800. }
  43801. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43802. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43803. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43804. }
  43805. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43806. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43807. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43808. if (scene._mirroredCameraPosition) {
  43809. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43810. }
  43811. else {
  43812. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43813. }
  43814. }
  43815. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43816. var depth = 1.0;
  43817. if (!this._refractionTexture.isCube) {
  43818. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43819. if (this._refractionTexture.depth) {
  43820. depth = this._refractionTexture.depth;
  43821. }
  43822. }
  43823. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43824. }
  43825. }
  43826. // Point size
  43827. if (this.pointsCloud) {
  43828. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43829. }
  43830. if (defines.SPECULARTERM) {
  43831. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43832. }
  43833. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43834. // Diffuse
  43835. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43836. }
  43837. // Textures
  43838. if (scene.texturesEnabled) {
  43839. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43840. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43841. }
  43842. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43843. effect.setTexture("ambientSampler", this._ambientTexture);
  43844. }
  43845. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43846. effect.setTexture("opacitySampler", this._opacityTexture);
  43847. }
  43848. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43849. if (this._reflectionTexture.isCube) {
  43850. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43851. }
  43852. else {
  43853. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43854. }
  43855. }
  43856. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43857. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43858. }
  43859. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43860. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43861. }
  43862. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43863. effect.setTexture("specularSampler", this._specularTexture);
  43864. }
  43865. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43866. effect.setTexture("bumpSampler", this._bumpTexture);
  43867. }
  43868. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43869. var depth = 1.0;
  43870. if (this._refractionTexture.isCube) {
  43871. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43872. }
  43873. else {
  43874. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43875. }
  43876. }
  43877. }
  43878. // Clip plane
  43879. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43880. // Colors
  43881. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43882. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43883. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43884. }
  43885. if (mustRebind || !this.isFrozen) {
  43886. // Lights
  43887. if (scene.lightsEnabled && !this._disableLighting) {
  43888. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43889. }
  43890. // View
  43891. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43892. this.bindView(effect);
  43893. }
  43894. // Fog
  43895. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43896. // Morph targets
  43897. if (defines.NUM_MORPH_INFLUENCERS) {
  43898. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43899. }
  43900. // Log. depth
  43901. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43902. // image processing
  43903. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43904. this._imageProcessingConfiguration.bind(this._activeEffect);
  43905. }
  43906. }
  43907. this._uniformBuffer.update();
  43908. this._afterBind(mesh, this._activeEffect);
  43909. };
  43910. /**
  43911. * Get the list of animatables in the material.
  43912. * @returns the list of animatables object used in the material
  43913. */
  43914. StandardMaterial.prototype.getAnimatables = function () {
  43915. var results = [];
  43916. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43917. results.push(this._diffuseTexture);
  43918. }
  43919. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43920. results.push(this._ambientTexture);
  43921. }
  43922. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43923. results.push(this._opacityTexture);
  43924. }
  43925. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43926. results.push(this._reflectionTexture);
  43927. }
  43928. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43929. results.push(this._emissiveTexture);
  43930. }
  43931. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43932. results.push(this._specularTexture);
  43933. }
  43934. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43935. results.push(this._bumpTexture);
  43936. }
  43937. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43938. results.push(this._lightmapTexture);
  43939. }
  43940. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43941. results.push(this._refractionTexture);
  43942. }
  43943. return results;
  43944. };
  43945. /**
  43946. * Gets the active textures from the material
  43947. * @returns an array of textures
  43948. */
  43949. StandardMaterial.prototype.getActiveTextures = function () {
  43950. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43951. if (this._diffuseTexture) {
  43952. activeTextures.push(this._diffuseTexture);
  43953. }
  43954. if (this._ambientTexture) {
  43955. activeTextures.push(this._ambientTexture);
  43956. }
  43957. if (this._opacityTexture) {
  43958. activeTextures.push(this._opacityTexture);
  43959. }
  43960. if (this._reflectionTexture) {
  43961. activeTextures.push(this._reflectionTexture);
  43962. }
  43963. if (this._emissiveTexture) {
  43964. activeTextures.push(this._emissiveTexture);
  43965. }
  43966. if (this._specularTexture) {
  43967. activeTextures.push(this._specularTexture);
  43968. }
  43969. if (this._bumpTexture) {
  43970. activeTextures.push(this._bumpTexture);
  43971. }
  43972. if (this._lightmapTexture) {
  43973. activeTextures.push(this._lightmapTexture);
  43974. }
  43975. if (this._refractionTexture) {
  43976. activeTextures.push(this._refractionTexture);
  43977. }
  43978. return activeTextures;
  43979. };
  43980. /**
  43981. * Specifies if the material uses a texture
  43982. * @param texture defines the texture to check against the material
  43983. * @returns a boolean specifying if the material uses the texture
  43984. */
  43985. StandardMaterial.prototype.hasTexture = function (texture) {
  43986. if (_super.prototype.hasTexture.call(this, texture)) {
  43987. return true;
  43988. }
  43989. if (this._diffuseTexture === texture) {
  43990. return true;
  43991. }
  43992. if (this._ambientTexture === texture) {
  43993. return true;
  43994. }
  43995. if (this._opacityTexture === texture) {
  43996. return true;
  43997. }
  43998. if (this._reflectionTexture === texture) {
  43999. return true;
  44000. }
  44001. if (this._emissiveTexture === texture) {
  44002. return true;
  44003. }
  44004. if (this._specularTexture === texture) {
  44005. return true;
  44006. }
  44007. if (this._bumpTexture === texture) {
  44008. return true;
  44009. }
  44010. if (this._lightmapTexture === texture) {
  44011. return true;
  44012. }
  44013. if (this._refractionTexture === texture) {
  44014. return true;
  44015. }
  44016. return false;
  44017. };
  44018. /**
  44019. * Disposes the material
  44020. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44021. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44022. */
  44023. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44024. if (forceDisposeTextures) {
  44025. if (this._diffuseTexture) {
  44026. this._diffuseTexture.dispose();
  44027. }
  44028. if (this._ambientTexture) {
  44029. this._ambientTexture.dispose();
  44030. }
  44031. if (this._opacityTexture) {
  44032. this._opacityTexture.dispose();
  44033. }
  44034. if (this._reflectionTexture) {
  44035. this._reflectionTexture.dispose();
  44036. }
  44037. if (this._emissiveTexture) {
  44038. this._emissiveTexture.dispose();
  44039. }
  44040. if (this._specularTexture) {
  44041. this._specularTexture.dispose();
  44042. }
  44043. if (this._bumpTexture) {
  44044. this._bumpTexture.dispose();
  44045. }
  44046. if (this._lightmapTexture) {
  44047. this._lightmapTexture.dispose();
  44048. }
  44049. if (this._refractionTexture) {
  44050. this._refractionTexture.dispose();
  44051. }
  44052. }
  44053. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44054. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44055. }
  44056. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44057. };
  44058. /**
  44059. * Makes a duplicate of the material, and gives it a new name
  44060. * @param name defines the new name for the duplicated material
  44061. * @returns the cloned material
  44062. */
  44063. StandardMaterial.prototype.clone = function (name) {
  44064. var _this = this;
  44065. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44066. result.name = name;
  44067. result.id = name;
  44068. return result;
  44069. };
  44070. /**
  44071. * Serializes this material in a JSON representation
  44072. * @returns the serialized material object
  44073. */
  44074. StandardMaterial.prototype.serialize = function () {
  44075. return BABYLON.SerializationHelper.Serialize(this);
  44076. };
  44077. /**
  44078. * Creates a standard material from parsed material data
  44079. * @param source defines the JSON represnetation of the material
  44080. * @param scene defines the hosting scene
  44081. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44082. * @returns a new material
  44083. */
  44084. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44085. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44086. };
  44087. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44088. /**
  44089. * Are diffuse textures enabled in the application.
  44090. */
  44091. get: function () {
  44092. return StandardMaterial._DiffuseTextureEnabled;
  44093. },
  44094. set: function (value) {
  44095. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44096. return;
  44097. }
  44098. StandardMaterial._DiffuseTextureEnabled = value;
  44099. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44100. },
  44101. enumerable: true,
  44102. configurable: true
  44103. });
  44104. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44105. /**
  44106. * Are ambient textures enabled in the application.
  44107. */
  44108. get: function () {
  44109. return StandardMaterial._AmbientTextureEnabled;
  44110. },
  44111. set: function (value) {
  44112. if (StandardMaterial._AmbientTextureEnabled === value) {
  44113. return;
  44114. }
  44115. StandardMaterial._AmbientTextureEnabled = value;
  44116. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44122. /**
  44123. * Are opacity textures enabled in the application.
  44124. */
  44125. get: function () {
  44126. return StandardMaterial._OpacityTextureEnabled;
  44127. },
  44128. set: function (value) {
  44129. if (StandardMaterial._OpacityTextureEnabled === value) {
  44130. return;
  44131. }
  44132. StandardMaterial._OpacityTextureEnabled = value;
  44133. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44134. },
  44135. enumerable: true,
  44136. configurable: true
  44137. });
  44138. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44139. /**
  44140. * Are reflection textures enabled in the application.
  44141. */
  44142. get: function () {
  44143. return StandardMaterial._ReflectionTextureEnabled;
  44144. },
  44145. set: function (value) {
  44146. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44147. return;
  44148. }
  44149. StandardMaterial._ReflectionTextureEnabled = value;
  44150. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44151. },
  44152. enumerable: true,
  44153. configurable: true
  44154. });
  44155. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44156. /**
  44157. * Are emissive textures enabled in the application.
  44158. */
  44159. get: function () {
  44160. return StandardMaterial._EmissiveTextureEnabled;
  44161. },
  44162. set: function (value) {
  44163. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44164. return;
  44165. }
  44166. StandardMaterial._EmissiveTextureEnabled = value;
  44167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44168. },
  44169. enumerable: true,
  44170. configurable: true
  44171. });
  44172. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44173. /**
  44174. * Are specular textures enabled in the application.
  44175. */
  44176. get: function () {
  44177. return StandardMaterial._SpecularTextureEnabled;
  44178. },
  44179. set: function (value) {
  44180. if (StandardMaterial._SpecularTextureEnabled === value) {
  44181. return;
  44182. }
  44183. StandardMaterial._SpecularTextureEnabled = value;
  44184. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44185. },
  44186. enumerable: true,
  44187. configurable: true
  44188. });
  44189. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44190. /**
  44191. * Are bump textures enabled in the application.
  44192. */
  44193. get: function () {
  44194. return StandardMaterial._BumpTextureEnabled;
  44195. },
  44196. set: function (value) {
  44197. if (StandardMaterial._BumpTextureEnabled === value) {
  44198. return;
  44199. }
  44200. StandardMaterial._BumpTextureEnabled = value;
  44201. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44202. },
  44203. enumerable: true,
  44204. configurable: true
  44205. });
  44206. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44207. /**
  44208. * Are lightmap textures enabled in the application.
  44209. */
  44210. get: function () {
  44211. return StandardMaterial._LightmapTextureEnabled;
  44212. },
  44213. set: function (value) {
  44214. if (StandardMaterial._LightmapTextureEnabled === value) {
  44215. return;
  44216. }
  44217. StandardMaterial._LightmapTextureEnabled = value;
  44218. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44219. },
  44220. enumerable: true,
  44221. configurable: true
  44222. });
  44223. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44224. /**
  44225. * Are refraction textures enabled in the application.
  44226. */
  44227. get: function () {
  44228. return StandardMaterial._RefractionTextureEnabled;
  44229. },
  44230. set: function (value) {
  44231. if (StandardMaterial._RefractionTextureEnabled === value) {
  44232. return;
  44233. }
  44234. StandardMaterial._RefractionTextureEnabled = value;
  44235. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44236. },
  44237. enumerable: true,
  44238. configurable: true
  44239. });
  44240. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44241. /**
  44242. * Are color grading textures enabled in the application.
  44243. */
  44244. get: function () {
  44245. return StandardMaterial._ColorGradingTextureEnabled;
  44246. },
  44247. set: function (value) {
  44248. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44249. return;
  44250. }
  44251. StandardMaterial._ColorGradingTextureEnabled = value;
  44252. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44253. },
  44254. enumerable: true,
  44255. configurable: true
  44256. });
  44257. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44258. /**
  44259. * Are fresnels enabled in the application.
  44260. */
  44261. get: function () {
  44262. return StandardMaterial._FresnelEnabled;
  44263. },
  44264. set: function (value) {
  44265. if (StandardMaterial._FresnelEnabled === value) {
  44266. return;
  44267. }
  44268. StandardMaterial._FresnelEnabled = value;
  44269. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44270. },
  44271. enumerable: true,
  44272. configurable: true
  44273. });
  44274. // Flags used to enable or disable a type of texture for all Standard Materials
  44275. StandardMaterial._DiffuseTextureEnabled = true;
  44276. StandardMaterial._AmbientTextureEnabled = true;
  44277. StandardMaterial._OpacityTextureEnabled = true;
  44278. StandardMaterial._ReflectionTextureEnabled = true;
  44279. StandardMaterial._EmissiveTextureEnabled = true;
  44280. StandardMaterial._SpecularTextureEnabled = true;
  44281. StandardMaterial._BumpTextureEnabled = true;
  44282. StandardMaterial._LightmapTextureEnabled = true;
  44283. StandardMaterial._RefractionTextureEnabled = true;
  44284. StandardMaterial._ColorGradingTextureEnabled = true;
  44285. StandardMaterial._FresnelEnabled = true;
  44286. __decorate([
  44287. BABYLON.serializeAsTexture("diffuseTexture")
  44288. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44289. __decorate([
  44290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44291. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44292. __decorate([
  44293. BABYLON.serializeAsTexture("ambientTexture")
  44294. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44295. __decorate([
  44296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44297. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44298. __decorate([
  44299. BABYLON.serializeAsTexture("opacityTexture")
  44300. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44301. __decorate([
  44302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44303. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44304. __decorate([
  44305. BABYLON.serializeAsTexture("reflectionTexture")
  44306. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44307. __decorate([
  44308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44309. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44310. __decorate([
  44311. BABYLON.serializeAsTexture("emissiveTexture")
  44312. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44313. __decorate([
  44314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44315. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44316. __decorate([
  44317. BABYLON.serializeAsTexture("specularTexture")
  44318. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44319. __decorate([
  44320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44321. ], StandardMaterial.prototype, "specularTexture", void 0);
  44322. __decorate([
  44323. BABYLON.serializeAsTexture("bumpTexture")
  44324. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44325. __decorate([
  44326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44327. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44328. __decorate([
  44329. BABYLON.serializeAsTexture("lightmapTexture")
  44330. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44331. __decorate([
  44332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44333. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44334. __decorate([
  44335. BABYLON.serializeAsTexture("refractionTexture")
  44336. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44337. __decorate([
  44338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44339. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44340. __decorate([
  44341. BABYLON.serializeAsColor3("ambient")
  44342. ], StandardMaterial.prototype, "ambientColor", void 0);
  44343. __decorate([
  44344. BABYLON.serializeAsColor3("diffuse")
  44345. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44346. __decorate([
  44347. BABYLON.serializeAsColor3("specular")
  44348. ], StandardMaterial.prototype, "specularColor", void 0);
  44349. __decorate([
  44350. BABYLON.serializeAsColor3("emissive")
  44351. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44352. __decorate([
  44353. BABYLON.serialize()
  44354. ], StandardMaterial.prototype, "specularPower", void 0);
  44355. __decorate([
  44356. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44357. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44358. __decorate([
  44359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44360. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44361. __decorate([
  44362. BABYLON.serialize("useEmissiveAsIllumination")
  44363. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44364. __decorate([
  44365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44366. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44367. __decorate([
  44368. BABYLON.serialize("linkEmissiveWithDiffuse")
  44369. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44370. __decorate([
  44371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44372. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44373. __decorate([
  44374. BABYLON.serialize("useSpecularOverAlpha")
  44375. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44376. __decorate([
  44377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44378. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44379. __decorate([
  44380. BABYLON.serialize("useReflectionOverAlpha")
  44381. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44382. __decorate([
  44383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44384. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44385. __decorate([
  44386. BABYLON.serialize("disableLighting")
  44387. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44388. __decorate([
  44389. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44390. ], StandardMaterial.prototype, "disableLighting", void 0);
  44391. __decorate([
  44392. BABYLON.serialize("useObjectSpaceNormalMap")
  44393. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44394. __decorate([
  44395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44396. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44397. __decorate([
  44398. BABYLON.serialize("useParallax")
  44399. ], StandardMaterial.prototype, "_useParallax", void 0);
  44400. __decorate([
  44401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44402. ], StandardMaterial.prototype, "useParallax", void 0);
  44403. __decorate([
  44404. BABYLON.serialize("useParallaxOcclusion")
  44405. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44406. __decorate([
  44407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44408. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44409. __decorate([
  44410. BABYLON.serialize()
  44411. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44412. __decorate([
  44413. BABYLON.serialize("roughness")
  44414. ], StandardMaterial.prototype, "_roughness", void 0);
  44415. __decorate([
  44416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44417. ], StandardMaterial.prototype, "roughness", void 0);
  44418. __decorate([
  44419. BABYLON.serialize()
  44420. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44421. __decorate([
  44422. BABYLON.serialize()
  44423. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44424. __decorate([
  44425. BABYLON.serialize()
  44426. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44427. __decorate([
  44428. BABYLON.serialize("useLightmapAsShadowmap")
  44429. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44430. __decorate([
  44431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44432. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44433. __decorate([
  44434. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44435. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44436. __decorate([
  44437. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44438. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44439. __decorate([
  44440. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44441. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44444. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44445. __decorate([
  44446. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44447. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44448. __decorate([
  44449. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44450. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44451. __decorate([
  44452. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44453. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44454. __decorate([
  44455. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44456. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44457. __decorate([
  44458. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44459. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44460. __decorate([
  44461. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44462. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44463. __decorate([
  44464. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44465. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44466. __decorate([
  44467. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44468. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44469. __decorate([
  44470. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44471. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44472. __decorate([
  44473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44474. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44475. __decorate([
  44476. BABYLON.serialize("maxSimultaneousLights")
  44477. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44478. __decorate([
  44479. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44480. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44481. __decorate([
  44482. BABYLON.serialize("invertNormalMapX")
  44483. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44484. __decorate([
  44485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44486. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44487. __decorate([
  44488. BABYLON.serialize("invertNormalMapY")
  44489. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44490. __decorate([
  44491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44492. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44493. __decorate([
  44494. BABYLON.serialize("twoSidedLighting")
  44495. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44496. __decorate([
  44497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44498. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44499. __decorate([
  44500. BABYLON.serialize()
  44501. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44502. return StandardMaterial;
  44503. }(BABYLON.PushMaterial));
  44504. BABYLON.StandardMaterial = StandardMaterial;
  44505. })(BABYLON || (BABYLON = {}));
  44506. //# sourceMappingURL=babylon.standardMaterial.js.map
  44507. var BABYLON;
  44508. (function (BABYLON) {
  44509. /**
  44510. * Class representing spherical polynomial coefficients to the 3rd degree
  44511. */
  44512. var SphericalPolynomial = /** @class */ (function () {
  44513. function SphericalPolynomial() {
  44514. /**
  44515. * The x coefficients of the spherical polynomial
  44516. */
  44517. this.x = BABYLON.Vector3.Zero();
  44518. /**
  44519. * The y coefficients of the spherical polynomial
  44520. */
  44521. this.y = BABYLON.Vector3.Zero();
  44522. /**
  44523. * The z coefficients of the spherical polynomial
  44524. */
  44525. this.z = BABYLON.Vector3.Zero();
  44526. /**
  44527. * The xx coefficients of the spherical polynomial
  44528. */
  44529. this.xx = BABYLON.Vector3.Zero();
  44530. /**
  44531. * The yy coefficients of the spherical polynomial
  44532. */
  44533. this.yy = BABYLON.Vector3.Zero();
  44534. /**
  44535. * The zz coefficients of the spherical polynomial
  44536. */
  44537. this.zz = BABYLON.Vector3.Zero();
  44538. /**
  44539. * The xy coefficients of the spherical polynomial
  44540. */
  44541. this.xy = BABYLON.Vector3.Zero();
  44542. /**
  44543. * The yz coefficients of the spherical polynomial
  44544. */
  44545. this.yz = BABYLON.Vector3.Zero();
  44546. /**
  44547. * The zx coefficients of the spherical polynomial
  44548. */
  44549. this.zx = BABYLON.Vector3.Zero();
  44550. }
  44551. /**
  44552. * Adds an ambient color to the spherical polynomial
  44553. * @param color the color to add
  44554. */
  44555. SphericalPolynomial.prototype.addAmbient = function (color) {
  44556. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44557. this.xx = this.xx.add(colorVector);
  44558. this.yy = this.yy.add(colorVector);
  44559. this.zz = this.zz.add(colorVector);
  44560. };
  44561. /**
  44562. * Scales the spherical polynomial by the given amount
  44563. * @param scale the amount to scale
  44564. */
  44565. SphericalPolynomial.prototype.scale = function (scale) {
  44566. this.x = this.x.scale(scale);
  44567. this.y = this.y.scale(scale);
  44568. this.z = this.z.scale(scale);
  44569. this.xx = this.xx.scale(scale);
  44570. this.yy = this.yy.scale(scale);
  44571. this.zz = this.zz.scale(scale);
  44572. this.yz = this.yz.scale(scale);
  44573. this.zx = this.zx.scale(scale);
  44574. this.xy = this.xy.scale(scale);
  44575. };
  44576. /**
  44577. * Gets the spherical polynomial from harmonics
  44578. * @param harmonics the spherical harmonics
  44579. * @returns the spherical polynomial
  44580. */
  44581. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44582. var result = new SphericalPolynomial();
  44583. result.x = harmonics.l11.scale(1.02333);
  44584. result.y = harmonics.l1_1.scale(1.02333);
  44585. result.z = harmonics.l10.scale(1.02333);
  44586. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44587. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44588. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44589. result.yz = harmonics.l2_1.scale(0.858086);
  44590. result.zx = harmonics.l21.scale(0.858086);
  44591. result.xy = harmonics.l2_2.scale(0.858086);
  44592. result.scale(1.0 / Math.PI);
  44593. return result;
  44594. };
  44595. /**
  44596. * Constructs a spherical polynomial from an array.
  44597. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44598. * @returns the spherical polynomial
  44599. */
  44600. SphericalPolynomial.FromArray = function (data) {
  44601. var sp = new SphericalPolynomial();
  44602. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44603. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44604. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44605. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44606. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44607. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44608. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44609. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44610. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44611. return sp;
  44612. };
  44613. return SphericalPolynomial;
  44614. }());
  44615. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44616. /**
  44617. * Class representing spherical harmonics coefficients to the 3rd degree
  44618. */
  44619. var SphericalHarmonics = /** @class */ (function () {
  44620. function SphericalHarmonics() {
  44621. /**
  44622. * The l0,0 coefficients of the spherical harmonics
  44623. */
  44624. this.l00 = BABYLON.Vector3.Zero();
  44625. /**
  44626. * The l1,-1 coefficients of the spherical harmonics
  44627. */
  44628. this.l1_1 = BABYLON.Vector3.Zero();
  44629. /**
  44630. * The l1,0 coefficients of the spherical harmonics
  44631. */
  44632. this.l10 = BABYLON.Vector3.Zero();
  44633. /**
  44634. * The l1,1 coefficients of the spherical harmonics
  44635. */
  44636. this.l11 = BABYLON.Vector3.Zero();
  44637. /**
  44638. * The l2,-2 coefficients of the spherical harmonics
  44639. */
  44640. this.l2_2 = BABYLON.Vector3.Zero();
  44641. /**
  44642. * The l2,-1 coefficients of the spherical harmonics
  44643. */
  44644. this.l2_1 = BABYLON.Vector3.Zero();
  44645. /**
  44646. * The l2,0 coefficients of the spherical harmonics
  44647. */
  44648. this.l20 = BABYLON.Vector3.Zero();
  44649. /**
  44650. * The l2,1 coefficients of the spherical harmonics
  44651. */
  44652. this.l21 = BABYLON.Vector3.Zero();
  44653. /**
  44654. * The l2,2 coefficients of the spherical harmonics
  44655. */
  44656. this.lL22 = BABYLON.Vector3.Zero();
  44657. }
  44658. /**
  44659. * Adds a light to the spherical harmonics
  44660. * @param direction the direction of the light
  44661. * @param color the color of the light
  44662. * @param deltaSolidAngle the delta solid angle of the light
  44663. */
  44664. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44665. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44666. var c = colorVector.scale(deltaSolidAngle);
  44667. this.l00 = this.l00.add(c.scale(0.282095));
  44668. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44669. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44670. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44671. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44672. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44673. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44674. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44675. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44676. };
  44677. /**
  44678. * Scales the spherical harmonics by the given amount
  44679. * @param scale the amount to scale
  44680. */
  44681. SphericalHarmonics.prototype.scale = function (scale) {
  44682. this.l00 = this.l00.scale(scale);
  44683. this.l1_1 = this.l1_1.scale(scale);
  44684. this.l10 = this.l10.scale(scale);
  44685. this.l11 = this.l11.scale(scale);
  44686. this.l2_2 = this.l2_2.scale(scale);
  44687. this.l2_1 = this.l2_1.scale(scale);
  44688. this.l20 = this.l20.scale(scale);
  44689. this.l21 = this.l21.scale(scale);
  44690. this.lL22 = this.lL22.scale(scale);
  44691. };
  44692. /**
  44693. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44694. *
  44695. * ```
  44696. * E_lm = A_l * L_lm
  44697. * ```
  44698. *
  44699. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44700. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44701. * the scaling factors are given in equation 9.
  44702. */
  44703. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44704. // Constant (Band 0)
  44705. this.l00 = this.l00.scale(3.141593);
  44706. // Linear (Band 1)
  44707. this.l1_1 = this.l1_1.scale(2.094395);
  44708. this.l10 = this.l10.scale(2.094395);
  44709. this.l11 = this.l11.scale(2.094395);
  44710. // Quadratic (Band 2)
  44711. this.l2_2 = this.l2_2.scale(0.785398);
  44712. this.l2_1 = this.l2_1.scale(0.785398);
  44713. this.l20 = this.l20.scale(0.785398);
  44714. this.l21 = this.l21.scale(0.785398);
  44715. this.lL22 = this.lL22.scale(0.785398);
  44716. };
  44717. /**
  44718. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44719. *
  44720. * ```
  44721. * L = (1/pi) * E * rho
  44722. * ```
  44723. *
  44724. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44725. */
  44726. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44727. this.scale(1.0 / Math.PI);
  44728. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44729. // (The pixel shader must apply albedo after texture fetches, etc).
  44730. };
  44731. /**
  44732. * Gets the spherical harmonics from polynomial
  44733. * @param polynomial the spherical polynomial
  44734. * @returns the spherical harmonics
  44735. */
  44736. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44737. var result = new SphericalHarmonics();
  44738. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44739. result.l1_1 = polynomial.y.scale(0.977204);
  44740. result.l10 = polynomial.z.scale(0.977204);
  44741. result.l11 = polynomial.x.scale(0.977204);
  44742. result.l2_2 = polynomial.xy.scale(1.16538);
  44743. result.l2_1 = polynomial.yz.scale(1.16538);
  44744. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44745. result.l21 = polynomial.zx.scale(1.16538);
  44746. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44747. result.scale(Math.PI);
  44748. return result;
  44749. };
  44750. /**
  44751. * Constructs a spherical harmonics from an array.
  44752. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44753. * @returns the spherical harmonics
  44754. */
  44755. SphericalHarmonics.FromArray = function (data) {
  44756. var sh = new SphericalHarmonics();
  44757. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44758. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44759. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44760. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44761. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44762. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44763. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44764. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44765. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44766. return sh;
  44767. };
  44768. return SphericalHarmonics;
  44769. }());
  44770. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44771. })(BABYLON || (BABYLON = {}));
  44772. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44773. var BABYLON;
  44774. (function (BABYLON) {
  44775. var FileFaceOrientation = /** @class */ (function () {
  44776. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44777. this.name = name;
  44778. this.worldAxisForNormal = worldAxisForNormal;
  44779. this.worldAxisForFileX = worldAxisForFileX;
  44780. this.worldAxisForFileY = worldAxisForFileY;
  44781. }
  44782. return FileFaceOrientation;
  44783. }());
  44784. ;
  44785. /**
  44786. * Helper class dealing with the extraction of spherical polynomial dataArray
  44787. * from a cube map.
  44788. */
  44789. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44790. function CubeMapToSphericalPolynomialTools() {
  44791. }
  44792. /**
  44793. * Converts a texture to the according Spherical Polynomial data.
  44794. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44795. *
  44796. * @param texture The texture to extract the information from.
  44797. * @return The Spherical Polynomial data.
  44798. */
  44799. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44800. if (!texture.isCube) {
  44801. // Only supports cube Textures currently.
  44802. return null;
  44803. }
  44804. var size = texture.getSize().width;
  44805. var right = texture.readPixels(0);
  44806. var left = texture.readPixels(1);
  44807. var up;
  44808. var down;
  44809. if (texture.isRenderTarget) {
  44810. up = texture.readPixels(3);
  44811. down = texture.readPixels(2);
  44812. }
  44813. else {
  44814. up = texture.readPixels(2);
  44815. down = texture.readPixels(3);
  44816. }
  44817. var front = texture.readPixels(4);
  44818. var back = texture.readPixels(5);
  44819. var gammaSpace = texture.gammaSpace;
  44820. // Always read as RGBA.
  44821. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44822. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44823. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44824. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44825. }
  44826. var cubeInfo = {
  44827. size: size,
  44828. right: right,
  44829. left: left,
  44830. up: up,
  44831. down: down,
  44832. front: front,
  44833. back: back,
  44834. format: format,
  44835. type: type,
  44836. gammaSpace: gammaSpace,
  44837. };
  44838. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44839. };
  44840. /**
  44841. * Converts a cubemap to the according Spherical Polynomial data.
  44842. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44843. *
  44844. * @param cubeInfo The Cube map to extract the information from.
  44845. * @return The Spherical Polynomial data.
  44846. */
  44847. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44848. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44849. var totalSolidAngle = 0.0;
  44850. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44851. var du = 2.0 / cubeInfo.size;
  44852. var dv = du;
  44853. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44854. var minUV = du * 0.5 - 1.0;
  44855. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44856. var fileFace = this.FileFaces[faceIndex];
  44857. var dataArray = cubeInfo[fileFace.name];
  44858. var v = minUV;
  44859. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44860. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44861. // Because SP is still linear, so summation is fine in that basis.
  44862. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44863. for (var y = 0; y < cubeInfo.size; y++) {
  44864. var u = minUV;
  44865. for (var x = 0; x < cubeInfo.size; x++) {
  44866. // World direction (not normalised)
  44867. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44868. worldDirection.normalize();
  44869. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44870. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44871. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44872. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44873. // Handle Integer types.
  44874. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44875. r /= 255;
  44876. g /= 255;
  44877. b /= 255;
  44878. }
  44879. // Handle Gamma space textures.
  44880. if (cubeInfo.gammaSpace) {
  44881. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44882. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44883. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44884. }
  44885. var color = new BABYLON.Color3(r, g, b);
  44886. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44887. totalSolidAngle += deltaSolidAngle;
  44888. u += du;
  44889. }
  44890. v += dv;
  44891. }
  44892. }
  44893. // Solid angle for entire sphere is 4*pi
  44894. var sphereSolidAngle = 4.0 * Math.PI;
  44895. // Adjust the solid angle to allow for how many faces we processed.
  44896. var facesProcessed = 6.0;
  44897. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44898. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44899. // This is needed because the numerical integration over the cube uses a
  44900. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44901. // and also to compensate for accumulative error due to float precision in the summation.
  44902. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44903. sphericalHarmonics.scale(correctionFactor);
  44904. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44905. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44906. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44907. };
  44908. CubeMapToSphericalPolynomialTools.FileFaces = [
  44909. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44910. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44911. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44912. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44913. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44914. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44915. ];
  44916. return CubeMapToSphericalPolynomialTools;
  44917. }());
  44918. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44919. })(BABYLON || (BABYLON = {}));
  44920. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44921. var BABYLON;
  44922. (function (BABYLON) {
  44923. /**
  44924. * Manages the defines for the PBR Material.
  44925. * @hiddenChildren
  44926. */
  44927. var PBRMaterialDefines = /** @class */ (function (_super) {
  44928. __extends(PBRMaterialDefines, _super);
  44929. /**
  44930. * Initializes the PBR Material defines.
  44931. */
  44932. function PBRMaterialDefines() {
  44933. var _this = _super.call(this) || this;
  44934. _this.PBR = true;
  44935. _this.MAINUV1 = false;
  44936. _this.MAINUV2 = false;
  44937. _this.UV1 = false;
  44938. _this.UV2 = false;
  44939. _this.ALBEDO = false;
  44940. _this.ALBEDODIRECTUV = 0;
  44941. _this.VERTEXCOLOR = false;
  44942. _this.AMBIENT = false;
  44943. _this.AMBIENTDIRECTUV = 0;
  44944. _this.AMBIENTINGRAYSCALE = false;
  44945. _this.OPACITY = false;
  44946. _this.VERTEXALPHA = false;
  44947. _this.OPACITYDIRECTUV = 0;
  44948. _this.OPACITYRGB = false;
  44949. _this.ALPHATEST = false;
  44950. _this.DEPTHPREPASS = false;
  44951. _this.ALPHABLEND = false;
  44952. _this.ALPHAFROMALBEDO = false;
  44953. _this.ALPHATESTVALUE = "0.5";
  44954. _this.SPECULAROVERALPHA = false;
  44955. _this.RADIANCEOVERALPHA = false;
  44956. _this.ALPHAFRESNEL = false;
  44957. _this.LINEARALPHAFRESNEL = false;
  44958. _this.PREMULTIPLYALPHA = false;
  44959. _this.EMISSIVE = false;
  44960. _this.EMISSIVEDIRECTUV = 0;
  44961. _this.REFLECTIVITY = false;
  44962. _this.REFLECTIVITYDIRECTUV = 0;
  44963. _this.SPECULARTERM = false;
  44964. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44965. _this.MICROSURFACEAUTOMATIC = false;
  44966. _this.LODBASEDMICROSFURACE = false;
  44967. _this.MICROSURFACEMAP = false;
  44968. _this.MICROSURFACEMAPDIRECTUV = 0;
  44969. _this.METALLICWORKFLOW = false;
  44970. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44971. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44972. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44973. _this.AOSTOREINMETALMAPRED = false;
  44974. _this.ENVIRONMENTBRDF = false;
  44975. _this.NORMAL = false;
  44976. _this.TANGENT = false;
  44977. _this.BUMP = false;
  44978. _this.BUMPDIRECTUV = 0;
  44979. _this.OBJECTSPACE_NORMALMAP = false;
  44980. _this.PARALLAX = false;
  44981. _this.PARALLAXOCCLUSION = false;
  44982. _this.NORMALXYSCALE = true;
  44983. _this.LIGHTMAP = false;
  44984. _this.LIGHTMAPDIRECTUV = 0;
  44985. _this.USELIGHTMAPASSHADOWMAP = false;
  44986. _this.GAMMALIGHTMAP = false;
  44987. _this.REFLECTION = false;
  44988. _this.REFLECTIONMAP_3D = false;
  44989. _this.REFLECTIONMAP_SPHERICAL = false;
  44990. _this.REFLECTIONMAP_PLANAR = false;
  44991. _this.REFLECTIONMAP_CUBIC = false;
  44992. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44993. _this.REFLECTIONMAP_PROJECTION = false;
  44994. _this.REFLECTIONMAP_SKYBOX = false;
  44995. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  44996. _this.REFLECTIONMAP_EXPLICIT = false;
  44997. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44998. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44999. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45000. _this.INVERTCUBICMAP = false;
  45001. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45002. _this.USESPHERICALINVERTEX = false;
  45003. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45004. _this.LODINREFLECTIONALPHA = false;
  45005. _this.GAMMAREFLECTION = false;
  45006. _this.RGBDREFLECTION = false;
  45007. _this.RADIANCEOCCLUSION = false;
  45008. _this.HORIZONOCCLUSION = false;
  45009. _this.REFRACTION = false;
  45010. _this.REFRACTIONMAP_3D = false;
  45011. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45012. _this.LODINREFRACTIONALPHA = false;
  45013. _this.GAMMAREFRACTION = false;
  45014. _this.RGBDREFRACTION = false;
  45015. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45016. _this.INSTANCES = false;
  45017. _this.NUM_BONE_INFLUENCERS = 0;
  45018. _this.BonesPerMesh = 0;
  45019. _this.NONUNIFORMSCALING = false;
  45020. _this.MORPHTARGETS = false;
  45021. _this.MORPHTARGETS_NORMAL = false;
  45022. _this.MORPHTARGETS_TANGENT = false;
  45023. _this.NUM_MORPH_INFLUENCERS = 0;
  45024. _this.IMAGEPROCESSING = false;
  45025. _this.VIGNETTE = false;
  45026. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45027. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45028. _this.TONEMAPPING = false;
  45029. _this.TONEMAPPING_ACES = false;
  45030. _this.CONTRAST = false;
  45031. _this.COLORCURVES = false;
  45032. _this.COLORGRADING = false;
  45033. _this.COLORGRADING3D = false;
  45034. _this.SAMPLER3DGREENDEPTH = false;
  45035. _this.SAMPLER3DBGRMAP = false;
  45036. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45037. _this.EXPOSURE = false;
  45038. _this.USEPHYSICALLIGHTFALLOFF = false;
  45039. _this.USEGLTFLIGHTFALLOFF = false;
  45040. _this.TWOSIDEDLIGHTING = false;
  45041. _this.SHADOWFLOAT = false;
  45042. _this.CLIPPLANE = false;
  45043. _this.CLIPPLANE2 = false;
  45044. _this.CLIPPLANE3 = false;
  45045. _this.CLIPPLANE4 = false;
  45046. _this.POINTSIZE = false;
  45047. _this.FOG = false;
  45048. _this.LOGARITHMICDEPTH = false;
  45049. _this.FORCENORMALFORWARD = false;
  45050. _this.SPECULARAA = false;
  45051. _this.UNLIT = false;
  45052. _this.rebuild();
  45053. return _this;
  45054. }
  45055. /**
  45056. * Resets the PBR Material defines.
  45057. */
  45058. PBRMaterialDefines.prototype.reset = function () {
  45059. _super.prototype.reset.call(this);
  45060. this.ALPHATESTVALUE = "0.5";
  45061. this.PBR = true;
  45062. };
  45063. return PBRMaterialDefines;
  45064. }(BABYLON.MaterialDefines));
  45065. /**
  45066. * The Physically based material base class of BJS.
  45067. *
  45068. * This offers the main features of a standard PBR material.
  45069. * For more information, please refer to the documentation :
  45070. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45071. */
  45072. var PBRBaseMaterial = /** @class */ (function (_super) {
  45073. __extends(PBRBaseMaterial, _super);
  45074. /**
  45075. * Instantiates a new PBRMaterial instance.
  45076. *
  45077. * @param name The material name
  45078. * @param scene The scene the material will be use in.
  45079. */
  45080. function PBRBaseMaterial(name, scene) {
  45081. var _this = _super.call(this, name, scene) || this;
  45082. /**
  45083. * Intensity of the direct lights e.g. the four lights available in your scene.
  45084. * This impacts both the direct diffuse and specular highlights.
  45085. */
  45086. _this._directIntensity = 1.0;
  45087. /**
  45088. * Intensity of the emissive part of the material.
  45089. * This helps controlling the emissive effect without modifying the emissive color.
  45090. */
  45091. _this._emissiveIntensity = 1.0;
  45092. /**
  45093. * Intensity of the environment e.g. how much the environment will light the object
  45094. * either through harmonics for rough material or through the refelction for shiny ones.
  45095. */
  45096. _this._environmentIntensity = 1.0;
  45097. /**
  45098. * This is a special control allowing the reduction of the specular highlights coming from the
  45099. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45100. */
  45101. _this._specularIntensity = 1.0;
  45102. /**
  45103. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45104. */
  45105. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45106. /**
  45107. * Debug Control allowing disabling the bump map on this material.
  45108. */
  45109. _this._disableBumpMap = false;
  45110. /**
  45111. * AKA Occlusion Texture Intensity in other nomenclature.
  45112. */
  45113. _this._ambientTextureStrength = 1.0;
  45114. /**
  45115. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45116. * 1 means it completely occludes it
  45117. * 0 mean it has no impact
  45118. */
  45119. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45120. /**
  45121. * The color of a material in ambient lighting.
  45122. */
  45123. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45124. /**
  45125. * AKA Diffuse Color in other nomenclature.
  45126. */
  45127. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45128. /**
  45129. * AKA Specular Color in other nomenclature.
  45130. */
  45131. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45132. /**
  45133. * The color applied when light is reflected from a material.
  45134. */
  45135. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45136. /**
  45137. * The color applied when light is emitted from a material.
  45138. */
  45139. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45140. /**
  45141. * AKA Glossiness in other nomenclature.
  45142. */
  45143. _this._microSurface = 0.9;
  45144. /**
  45145. * source material index of refraction (IOR)' / 'destination material IOR.
  45146. */
  45147. _this._indexOfRefraction = 0.66;
  45148. /**
  45149. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45150. */
  45151. _this._invertRefractionY = false;
  45152. /**
  45153. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45154. * Materials half opaque for instance using refraction could benefit from this control.
  45155. */
  45156. _this._linkRefractionWithTransparency = false;
  45157. /**
  45158. * Specifies that the material will use the light map as a show map.
  45159. */
  45160. _this._useLightmapAsShadowmap = false;
  45161. /**
  45162. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45163. * makes the reflect vector face the model (under horizon).
  45164. */
  45165. _this._useHorizonOcclusion = true;
  45166. /**
  45167. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45168. * too much the area relying on ambient texture to define their ambient occlusion.
  45169. */
  45170. _this._useRadianceOcclusion = true;
  45171. /**
  45172. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45173. */
  45174. _this._useAlphaFromAlbedoTexture = false;
  45175. /**
  45176. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45177. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45178. */
  45179. _this._useSpecularOverAlpha = true;
  45180. /**
  45181. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45182. */
  45183. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45184. /**
  45185. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45186. */
  45187. _this._useRoughnessFromMetallicTextureAlpha = true;
  45188. /**
  45189. * Specifies if the metallic texture contains the roughness information in its green channel.
  45190. */
  45191. _this._useRoughnessFromMetallicTextureGreen = false;
  45192. /**
  45193. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45194. */
  45195. _this._useMetallnessFromMetallicTextureBlue = false;
  45196. /**
  45197. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45198. */
  45199. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45200. /**
  45201. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45202. */
  45203. _this._useAmbientInGrayScale = false;
  45204. /**
  45205. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45206. * The material will try to infer what glossiness each pixel should be.
  45207. */
  45208. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45209. /**
  45210. * Defines the falloff type used in this material.
  45211. * It by default is Physical.
  45212. */
  45213. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45214. /**
  45215. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45216. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45217. */
  45218. _this._useRadianceOverAlpha = true;
  45219. /**
  45220. * Allows using an object space normal map (instead of tangent space).
  45221. */
  45222. _this._useObjectSpaceNormalMap = false;
  45223. /**
  45224. * Allows using the bump map in parallax mode.
  45225. */
  45226. _this._useParallax = false;
  45227. /**
  45228. * Allows using the bump map in parallax occlusion mode.
  45229. */
  45230. _this._useParallaxOcclusion = false;
  45231. /**
  45232. * Controls the scale bias of the parallax mode.
  45233. */
  45234. _this._parallaxScaleBias = 0.05;
  45235. /**
  45236. * If sets to true, disables all the lights affecting the material.
  45237. */
  45238. _this._disableLighting = false;
  45239. /**
  45240. * Number of Simultaneous lights allowed on the material.
  45241. */
  45242. _this._maxSimultaneousLights = 4;
  45243. /**
  45244. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45245. */
  45246. _this._invertNormalMapX = false;
  45247. /**
  45248. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45249. */
  45250. _this._invertNormalMapY = false;
  45251. /**
  45252. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45253. */
  45254. _this._twoSidedLighting = false;
  45255. /**
  45256. * Defines the alpha limits in alpha test mode.
  45257. */
  45258. _this._alphaCutOff = 0.4;
  45259. /**
  45260. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45261. */
  45262. _this._forceAlphaTest = false;
  45263. /**
  45264. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45265. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45266. */
  45267. _this._useAlphaFresnel = false;
  45268. /**
  45269. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45270. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45271. */
  45272. _this._useLinearAlphaFresnel = false;
  45273. /**
  45274. * The transparency mode of the material.
  45275. */
  45276. _this._transparencyMode = null;
  45277. /**
  45278. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45279. * from cos thetav and roughness:
  45280. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45281. */
  45282. _this._environmentBRDFTexture = null;
  45283. /**
  45284. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45285. */
  45286. _this._forceIrradianceInFragment = false;
  45287. /**
  45288. * Force normal to face away from face.
  45289. */
  45290. _this._forceNormalForward = false;
  45291. /**
  45292. * Enables specular anti aliasing in the PBR shader.
  45293. * It will both interacts on the Geometry for analytical and IBL lighting.
  45294. * It also prefilter the roughness map based on the bump values.
  45295. */
  45296. _this._enableSpecularAntiAliasing = false;
  45297. /**
  45298. * Stores the available render targets.
  45299. */
  45300. _this._renderTargets = new BABYLON.SmartArray(16);
  45301. /**
  45302. * Sets the global ambient color for the material used in lighting calculations.
  45303. */
  45304. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45305. /**
  45306. * If set to true, no lighting calculations will be applied.
  45307. */
  45308. _this._unlit = false;
  45309. // Setup the default processing configuration to the scene.
  45310. _this._attachImageProcessingConfiguration(null);
  45311. _this.getRenderTargetTextures = function () {
  45312. _this._renderTargets.reset();
  45313. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45314. _this._renderTargets.push(_this._reflectionTexture);
  45315. }
  45316. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45317. _this._renderTargets.push(_this._refractionTexture);
  45318. }
  45319. return _this._renderTargets;
  45320. };
  45321. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45322. return _this;
  45323. }
  45324. /**
  45325. * Attaches a new image processing configuration to the PBR Material.
  45326. * @param configuration
  45327. */
  45328. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45329. var _this = this;
  45330. if (configuration === this._imageProcessingConfiguration) {
  45331. return;
  45332. }
  45333. // Detaches observer.
  45334. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45335. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45336. }
  45337. // Pick the scene configuration if needed.
  45338. if (!configuration) {
  45339. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45340. }
  45341. else {
  45342. this._imageProcessingConfiguration = configuration;
  45343. }
  45344. // Attaches observer.
  45345. if (this._imageProcessingConfiguration) {
  45346. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45347. _this._markAllSubMeshesAsImageProcessingDirty();
  45348. });
  45349. }
  45350. };
  45351. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45352. /**
  45353. * Gets a boolean indicating that current material needs to register RTT
  45354. */
  45355. get: function () {
  45356. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45357. return true;
  45358. }
  45359. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45360. return true;
  45361. }
  45362. return false;
  45363. },
  45364. enumerable: true,
  45365. configurable: true
  45366. });
  45367. /**
  45368. * Gets the name of the material class.
  45369. */
  45370. PBRBaseMaterial.prototype.getClassName = function () {
  45371. return "PBRBaseMaterial";
  45372. };
  45373. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45374. /**
  45375. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45376. */
  45377. get: function () {
  45378. return this._useLogarithmicDepth;
  45379. },
  45380. /**
  45381. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45382. */
  45383. set: function (value) {
  45384. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45385. },
  45386. enumerable: true,
  45387. configurable: true
  45388. });
  45389. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45390. /**
  45391. * Gets the current transparency mode.
  45392. */
  45393. get: function () {
  45394. return this._transparencyMode;
  45395. },
  45396. /**
  45397. * Sets the transparency mode of the material.
  45398. *
  45399. * | Value | Type | Description |
  45400. * | ----- | ----------------------------------- | ----------- |
  45401. * | 0 | OPAQUE | |
  45402. * | 1 | ALPHATEST | |
  45403. * | 2 | ALPHABLEND | |
  45404. * | 3 | ALPHATESTANDBLEND | |
  45405. *
  45406. */
  45407. set: function (value) {
  45408. if (this._transparencyMode === value) {
  45409. return;
  45410. }
  45411. this._transparencyMode = value;
  45412. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45413. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45414. },
  45415. enumerable: true,
  45416. configurable: true
  45417. });
  45418. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45419. /**
  45420. * Returns true if alpha blending should be disabled.
  45421. */
  45422. get: function () {
  45423. return (this._linkRefractionWithTransparency ||
  45424. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45425. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. /**
  45431. * Specifies whether or not this material should be rendered in alpha blend mode.
  45432. */
  45433. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45434. if (this._disableAlphaBlending) {
  45435. return false;
  45436. }
  45437. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45438. };
  45439. /**
  45440. * Specifies if the mesh will require alpha blending.
  45441. * @param mesh - BJS mesh.
  45442. */
  45443. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45444. if (this._disableAlphaBlending) {
  45445. return false;
  45446. }
  45447. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45448. };
  45449. /**
  45450. * Specifies whether or not this material should be rendered in alpha test mode.
  45451. */
  45452. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45453. if (this._forceAlphaTest) {
  45454. return true;
  45455. }
  45456. if (this._linkRefractionWithTransparency) {
  45457. return false;
  45458. }
  45459. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45460. };
  45461. /**
  45462. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45463. */
  45464. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45465. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45466. };
  45467. /**
  45468. * Gets the texture used for the alpha test.
  45469. */
  45470. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45471. return this._albedoTexture;
  45472. };
  45473. /**
  45474. * Specifies that the submesh is ready to be used.
  45475. * @param mesh - BJS mesh.
  45476. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45477. * @param useInstances - Specifies that instances should be used.
  45478. * @returns - boolean indicating that the submesh is ready or not.
  45479. */
  45480. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45481. if (subMesh.effect && this.isFrozen) {
  45482. if (this._wasPreviouslyReady) {
  45483. return true;
  45484. }
  45485. }
  45486. if (!subMesh._materialDefines) {
  45487. subMesh._materialDefines = new PBRMaterialDefines();
  45488. }
  45489. var defines = subMesh._materialDefines;
  45490. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45491. if (defines._renderId === this.getScene().getRenderId()) {
  45492. return true;
  45493. }
  45494. }
  45495. var scene = this.getScene();
  45496. var engine = scene.getEngine();
  45497. if (defines._areTexturesDirty) {
  45498. if (scene.texturesEnabled) {
  45499. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45500. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45501. return false;
  45502. }
  45503. }
  45504. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45505. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45506. return false;
  45507. }
  45508. }
  45509. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45510. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45511. return false;
  45512. }
  45513. }
  45514. var reflectionTexture = this._getReflectionTexture();
  45515. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45516. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45517. return false;
  45518. }
  45519. }
  45520. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45521. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45522. return false;
  45523. }
  45524. }
  45525. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45526. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45527. return false;
  45528. }
  45529. }
  45530. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45531. if (this._metallicTexture) {
  45532. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45533. return false;
  45534. }
  45535. }
  45536. else if (this._reflectivityTexture) {
  45537. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45538. return false;
  45539. }
  45540. }
  45541. if (this._microSurfaceTexture) {
  45542. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45543. return false;
  45544. }
  45545. }
  45546. }
  45547. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45548. // Bump texture cannot be not blocking.
  45549. if (!this._bumpTexture.isReady()) {
  45550. return false;
  45551. }
  45552. }
  45553. var refractionTexture = this._getRefractionTexture();
  45554. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45555. if (!refractionTexture.isReadyOrNotBlocking()) {
  45556. return false;
  45557. }
  45558. }
  45559. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45560. // This is blocking.
  45561. if (!this._environmentBRDFTexture.isReady()) {
  45562. return false;
  45563. }
  45564. }
  45565. }
  45566. }
  45567. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45568. if (!this._imageProcessingConfiguration.isReady()) {
  45569. return false;
  45570. }
  45571. }
  45572. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45573. mesh.createNormals(true);
  45574. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45575. }
  45576. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45577. if (effect) {
  45578. scene.resetCachedMaterial();
  45579. subMesh.setEffect(effect, defines);
  45580. this.buildUniformLayout();
  45581. }
  45582. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45583. return false;
  45584. }
  45585. defines._renderId = scene.getRenderId();
  45586. this._wasPreviouslyReady = true;
  45587. return true;
  45588. };
  45589. /**
  45590. * Specifies if the material uses metallic roughness workflow.
  45591. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45592. */
  45593. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45594. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45595. return true;
  45596. }
  45597. return false;
  45598. };
  45599. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45600. if (onCompiled === void 0) { onCompiled = null; }
  45601. if (onError === void 0) { onError = null; }
  45602. if (useInstances === void 0) { useInstances = null; }
  45603. if (useClipPlane === void 0) { useClipPlane = null; }
  45604. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45605. if (!defines.isDirty) {
  45606. return null;
  45607. }
  45608. defines.markAsProcessed();
  45609. var scene = this.getScene();
  45610. var engine = scene.getEngine();
  45611. // Fallbacks
  45612. var fallbacks = new BABYLON.EffectFallbacks();
  45613. var fallbackRank = 0;
  45614. if (defines.USESPHERICALINVERTEX) {
  45615. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45616. }
  45617. if (defines.FOG) {
  45618. fallbacks.addFallback(fallbackRank, "FOG");
  45619. }
  45620. if (defines.SPECULARAA) {
  45621. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45622. }
  45623. if (defines.POINTSIZE) {
  45624. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45625. }
  45626. if (defines.LOGARITHMICDEPTH) {
  45627. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45628. }
  45629. if (defines.PARALLAX) {
  45630. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45631. }
  45632. if (defines.PARALLAXOCCLUSION) {
  45633. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45634. }
  45635. if (defines.ENVIRONMENTBRDF) {
  45636. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45637. }
  45638. if (defines.TANGENT) {
  45639. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45640. }
  45641. if (defines.BUMP) {
  45642. fallbacks.addFallback(fallbackRank++, "BUMP");
  45643. }
  45644. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45645. if (defines.SPECULARTERM) {
  45646. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45647. }
  45648. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45649. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45650. }
  45651. if (defines.LIGHTMAP) {
  45652. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45653. }
  45654. if (defines.NORMAL) {
  45655. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45656. }
  45657. if (defines.AMBIENT) {
  45658. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45659. }
  45660. if (defines.EMISSIVE) {
  45661. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45662. }
  45663. if (defines.VERTEXCOLOR) {
  45664. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45665. }
  45666. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45667. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45668. }
  45669. if (defines.MORPHTARGETS) {
  45670. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45671. }
  45672. //Attributes
  45673. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45674. if (defines.NORMAL) {
  45675. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45676. }
  45677. if (defines.TANGENT) {
  45678. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45679. }
  45680. if (defines.UV1) {
  45681. attribs.push(BABYLON.VertexBuffer.UVKind);
  45682. }
  45683. if (defines.UV2) {
  45684. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45685. }
  45686. if (defines.VERTEXCOLOR) {
  45687. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45688. }
  45689. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45690. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45691. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45692. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45693. "vFogInfos", "vFogColor", "pointSize",
  45694. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45695. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45696. "mBones",
  45697. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45698. "vLightingIntensity",
  45699. "logarithmicDepthConstant",
  45700. "vSphericalX", "vSphericalY", "vSphericalZ",
  45701. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45702. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45703. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45704. "vTangentSpaceParams"
  45705. ];
  45706. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45707. "bumpSampler", "lightmapSampler", "opacitySampler",
  45708. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45709. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45710. "microSurfaceSampler", "environmentBrdfSampler"];
  45711. var uniformBuffers = ["Material", "Scene"];
  45712. if (BABYLON.ImageProcessingConfiguration) {
  45713. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45714. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45715. }
  45716. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45717. uniformsNames: uniforms,
  45718. uniformBuffersNames: uniformBuffers,
  45719. samplers: samplers,
  45720. defines: defines,
  45721. maxSimultaneousLights: this._maxSimultaneousLights
  45722. });
  45723. var join = defines.toString();
  45724. return engine.createEffect("pbr", {
  45725. attributes: attribs,
  45726. uniformsNames: uniforms,
  45727. uniformBuffersNames: uniformBuffers,
  45728. samplers: samplers,
  45729. defines: join,
  45730. fallbacks: fallbacks,
  45731. onCompiled: onCompiled,
  45732. onError: onError,
  45733. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45734. }, engine);
  45735. };
  45736. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45737. if (useInstances === void 0) { useInstances = null; }
  45738. if (useClipPlane === void 0) { useClipPlane = null; }
  45739. var scene = this.getScene();
  45740. var engine = scene.getEngine();
  45741. // Lights
  45742. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45743. defines._needNormals = true;
  45744. // Textures
  45745. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45746. if (defines._areTexturesDirty) {
  45747. defines._needUVs = false;
  45748. if (scene.texturesEnabled) {
  45749. if (scene.getEngine().getCaps().textureLOD) {
  45750. defines.LODBASEDMICROSFURACE = true;
  45751. }
  45752. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45754. }
  45755. else {
  45756. defines.ALBEDO = false;
  45757. }
  45758. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45759. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45760. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45761. }
  45762. else {
  45763. defines.AMBIENT = false;
  45764. }
  45765. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45766. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45767. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45768. }
  45769. else {
  45770. defines.OPACITY = false;
  45771. }
  45772. var reflectionTexture = this._getReflectionTexture();
  45773. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45774. defines.REFLECTION = true;
  45775. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45776. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45777. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45778. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45779. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45780. defines.INVERTCUBICMAP = true;
  45781. }
  45782. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45783. switch (reflectionTexture.coordinatesMode) {
  45784. case BABYLON.Texture.EXPLICIT_MODE:
  45785. defines.REFLECTIONMAP_EXPLICIT = true;
  45786. break;
  45787. case BABYLON.Texture.PLANAR_MODE:
  45788. defines.REFLECTIONMAP_PLANAR = true;
  45789. break;
  45790. case BABYLON.Texture.PROJECTION_MODE:
  45791. defines.REFLECTIONMAP_PROJECTION = true;
  45792. break;
  45793. case BABYLON.Texture.SKYBOX_MODE:
  45794. defines.REFLECTIONMAP_SKYBOX = true;
  45795. break;
  45796. case BABYLON.Texture.SPHERICAL_MODE:
  45797. defines.REFLECTIONMAP_SPHERICAL = true;
  45798. break;
  45799. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45800. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45801. break;
  45802. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45803. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45804. break;
  45805. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45806. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45807. break;
  45808. case BABYLON.Texture.CUBIC_MODE:
  45809. case BABYLON.Texture.INVCUBIC_MODE:
  45810. default:
  45811. defines.REFLECTIONMAP_CUBIC = true;
  45812. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45813. break;
  45814. }
  45815. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45816. if (reflectionTexture.sphericalPolynomial) {
  45817. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45818. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45819. defines.USESPHERICALINVERTEX = false;
  45820. }
  45821. else {
  45822. defines.USESPHERICALINVERTEX = true;
  45823. }
  45824. }
  45825. }
  45826. else {
  45827. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45828. }
  45829. }
  45830. else {
  45831. defines.REFLECTION = false;
  45832. defines.REFLECTIONMAP_3D = false;
  45833. defines.REFLECTIONMAP_SPHERICAL = false;
  45834. defines.REFLECTIONMAP_PLANAR = false;
  45835. defines.REFLECTIONMAP_CUBIC = false;
  45836. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45837. defines.REFLECTIONMAP_PROJECTION = false;
  45838. defines.REFLECTIONMAP_SKYBOX = false;
  45839. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45840. defines.REFLECTIONMAP_EXPLICIT = false;
  45841. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45842. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45843. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45844. defines.INVERTCUBICMAP = false;
  45845. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45846. defines.USESPHERICALINVERTEX = false;
  45847. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45848. defines.LODINREFLECTIONALPHA = false;
  45849. defines.GAMMAREFLECTION = false;
  45850. defines.RGBDREFLECTION = false;
  45851. }
  45852. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45853. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45854. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45855. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45856. }
  45857. else {
  45858. defines.LIGHTMAP = false;
  45859. }
  45860. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45861. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45862. }
  45863. else {
  45864. defines.EMISSIVE = false;
  45865. }
  45866. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45867. if (this._metallicTexture) {
  45868. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45869. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45870. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45871. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45872. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45873. }
  45874. else if (this._reflectivityTexture) {
  45875. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45876. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45877. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45878. }
  45879. else {
  45880. defines.REFLECTIVITY = false;
  45881. }
  45882. if (this._microSurfaceTexture) {
  45883. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45884. }
  45885. else {
  45886. defines.MICROSURFACEMAP = false;
  45887. }
  45888. }
  45889. else {
  45890. defines.REFLECTIVITY = false;
  45891. defines.MICROSURFACEMAP = false;
  45892. }
  45893. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45894. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45895. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45896. defines.PARALLAX = true;
  45897. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45898. }
  45899. else {
  45900. defines.PARALLAX = false;
  45901. }
  45902. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45903. }
  45904. else {
  45905. defines.BUMP = false;
  45906. }
  45907. var refractionTexture = this._getRefractionTexture();
  45908. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45909. defines.REFRACTION = true;
  45910. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45911. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45912. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45913. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45914. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45915. if (this._linkRefractionWithTransparency) {
  45916. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45917. }
  45918. }
  45919. else {
  45920. defines.REFRACTION = false;
  45921. }
  45922. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45923. defines.ENVIRONMENTBRDF = true;
  45924. }
  45925. else {
  45926. defines.ENVIRONMENTBRDF = false;
  45927. }
  45928. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45929. defines.ALPHAFROMALBEDO = true;
  45930. }
  45931. else {
  45932. defines.ALPHAFROMALBEDO = false;
  45933. }
  45934. }
  45935. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45936. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45937. defines.USEPHYSICALLIGHTFALLOFF = false;
  45938. defines.USEGLTFLIGHTFALLOFF = false;
  45939. }
  45940. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45941. defines.USEPHYSICALLIGHTFALLOFF = false;
  45942. defines.USEGLTFLIGHTFALLOFF = true;
  45943. }
  45944. else {
  45945. defines.USEPHYSICALLIGHTFALLOFF = true;
  45946. defines.USEGLTFLIGHTFALLOFF = false;
  45947. }
  45948. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45949. if (!this.backFaceCulling && this._twoSidedLighting) {
  45950. defines.TWOSIDEDLIGHTING = true;
  45951. }
  45952. else {
  45953. defines.TWOSIDEDLIGHTING = false;
  45954. }
  45955. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45956. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45957. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45958. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45959. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45960. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45961. }
  45962. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45963. this._imageProcessingConfiguration.prepareDefines(defines);
  45964. }
  45965. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45966. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45967. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45968. // Misc.
  45969. if (defines._areMiscDirty) {
  45970. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45971. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45972. }
  45973. // Values that need to be evaluated on every frame
  45974. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45975. // Attribs
  45976. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45977. };
  45978. /**
  45979. * Force shader compilation
  45980. */
  45981. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45982. var _this = this;
  45983. var localOptions = __assign({ clipPlane: false }, options);
  45984. var defines = new PBRMaterialDefines();
  45985. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45986. if (effect.isReady()) {
  45987. if (onCompiled) {
  45988. onCompiled(this);
  45989. }
  45990. }
  45991. else {
  45992. effect.onCompileObservable.add(function () {
  45993. if (onCompiled) {
  45994. onCompiled(_this);
  45995. }
  45996. });
  45997. }
  45998. };
  45999. /**
  46000. * Initializes the uniform buffer layout for the shader.
  46001. */
  46002. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46003. // Order is important !
  46004. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46005. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46006. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46007. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46008. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46009. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46010. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46011. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46012. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46013. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46014. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46015. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46016. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46017. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46018. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46019. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46020. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46021. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46022. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46023. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46024. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46025. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46026. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46027. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46028. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46029. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46030. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46031. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46032. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46033. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46034. this._uniformBuffer.addUniform("pointSize", 1);
  46035. this._uniformBuffer.create();
  46036. };
  46037. /**
  46038. * Unbinds the textures.
  46039. */
  46040. PBRBaseMaterial.prototype.unbind = function () {
  46041. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46042. this._uniformBuffer.setTexture("reflectionSampler", null);
  46043. }
  46044. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46045. this._uniformBuffer.setTexture("refractionSampler", null);
  46046. }
  46047. _super.prototype.unbind.call(this);
  46048. };
  46049. /**
  46050. * Binds the submesh data.
  46051. * @param world - The world matrix.
  46052. * @param mesh - The BJS mesh.
  46053. * @param subMesh - A submesh of the BJS mesh.
  46054. */
  46055. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46056. var scene = this.getScene();
  46057. var defines = subMesh._materialDefines;
  46058. if (!defines) {
  46059. return;
  46060. }
  46061. var effect = subMesh.effect;
  46062. if (!effect) {
  46063. return;
  46064. }
  46065. this._activeEffect = effect;
  46066. // Matrices
  46067. this.bindOnlyWorldMatrix(world);
  46068. // Normal Matrix
  46069. if (defines.OBJECTSPACE_NORMALMAP) {
  46070. world.toNormalMatrix(this._normalMatrix);
  46071. this.bindOnlyNormalMatrix(this._normalMatrix);
  46072. }
  46073. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46074. // Bones
  46075. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46076. var reflectionTexture = null;
  46077. if (mustRebind) {
  46078. this._uniformBuffer.bindToEffect(effect, "Material");
  46079. this.bindViewProjection(effect);
  46080. reflectionTexture = this._getReflectionTexture();
  46081. var refractionTexture = this._getRefractionTexture();
  46082. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46083. // Texture uniforms
  46084. if (scene.texturesEnabled) {
  46085. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46086. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46087. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46088. }
  46089. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46090. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46091. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46092. }
  46093. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46094. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46095. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46096. }
  46097. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46098. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46099. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46100. if (reflectionTexture.boundingBoxSize) {
  46101. var cubeTexture = reflectionTexture;
  46102. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46103. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46104. }
  46105. var polynomials = reflectionTexture.sphericalPolynomial;
  46106. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46107. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46108. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46109. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46110. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46111. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46112. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46113. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46114. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46115. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46116. }
  46117. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46118. }
  46119. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46120. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46121. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46122. }
  46123. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46124. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46125. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46126. }
  46127. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46128. if (this._metallicTexture) {
  46129. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46130. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46131. }
  46132. else if (this._reflectivityTexture) {
  46133. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46134. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46135. }
  46136. if (this._microSurfaceTexture) {
  46137. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46138. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46139. }
  46140. }
  46141. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46142. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46143. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46144. if (scene._mirroredCameraPosition) {
  46145. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46146. }
  46147. else {
  46148. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46149. }
  46150. }
  46151. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46152. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46153. var depth = 1.0;
  46154. if (!refractionTexture.isCube) {
  46155. if (refractionTexture.depth) {
  46156. depth = refractionTexture.depth;
  46157. }
  46158. }
  46159. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46160. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46161. }
  46162. }
  46163. // Point size
  46164. if (this.pointsCloud) {
  46165. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46166. }
  46167. // Colors
  46168. if (defines.METALLICWORKFLOW) {
  46169. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46170. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46171. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46172. }
  46173. else {
  46174. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46175. }
  46176. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46177. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46178. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46179. // Misc
  46180. this._lightingInfos.x = this._directIntensity;
  46181. this._lightingInfos.y = this._emissiveIntensity;
  46182. this._lightingInfos.z = this._environmentIntensity;
  46183. this._lightingInfos.w = this._specularIntensity;
  46184. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46185. }
  46186. // Textures
  46187. if (scene.texturesEnabled) {
  46188. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46189. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46190. }
  46191. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46192. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46193. }
  46194. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46195. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46196. }
  46197. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46198. if (defines.LODBASEDMICROSFURACE) {
  46199. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46200. }
  46201. else {
  46202. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46203. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46204. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46205. }
  46206. }
  46207. if (defines.ENVIRONMENTBRDF) {
  46208. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46209. }
  46210. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46211. if (defines.LODBASEDMICROSFURACE) {
  46212. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46213. }
  46214. else {
  46215. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46216. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46217. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46218. }
  46219. }
  46220. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46221. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46222. }
  46223. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46224. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46225. }
  46226. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46227. if (this._metallicTexture) {
  46228. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46229. }
  46230. else if (this._reflectivityTexture) {
  46231. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46232. }
  46233. if (this._microSurfaceTexture) {
  46234. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46235. }
  46236. }
  46237. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46238. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46239. }
  46240. }
  46241. // Clip plane
  46242. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46243. // Colors
  46244. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46245. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46246. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46247. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46248. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46249. }
  46250. if (mustRebind || !this.isFrozen) {
  46251. // Lights
  46252. if (scene.lightsEnabled && !this._disableLighting) {
  46253. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46254. }
  46255. // View
  46256. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46257. this.bindView(effect);
  46258. }
  46259. // Fog
  46260. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46261. // Morph targets
  46262. if (defines.NUM_MORPH_INFLUENCERS) {
  46263. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46264. }
  46265. // image processing
  46266. this._imageProcessingConfiguration.bind(this._activeEffect);
  46267. // Log. depth
  46268. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46269. }
  46270. this._uniformBuffer.update();
  46271. this._afterBind(mesh, this._activeEffect);
  46272. };
  46273. /**
  46274. * Returns the animatable textures.
  46275. * @returns - Array of animatable textures.
  46276. */
  46277. PBRBaseMaterial.prototype.getAnimatables = function () {
  46278. var results = [];
  46279. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46280. results.push(this._albedoTexture);
  46281. }
  46282. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46283. results.push(this._ambientTexture);
  46284. }
  46285. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46286. results.push(this._opacityTexture);
  46287. }
  46288. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46289. results.push(this._reflectionTexture);
  46290. }
  46291. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46292. results.push(this._emissiveTexture);
  46293. }
  46294. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46295. results.push(this._metallicTexture);
  46296. }
  46297. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46298. results.push(this._reflectivityTexture);
  46299. }
  46300. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46301. results.push(this._bumpTexture);
  46302. }
  46303. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46304. results.push(this._lightmapTexture);
  46305. }
  46306. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46307. results.push(this._refractionTexture);
  46308. }
  46309. return results;
  46310. };
  46311. /**
  46312. * Returns the texture used for reflections.
  46313. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46314. */
  46315. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46316. if (this._reflectionTexture) {
  46317. return this._reflectionTexture;
  46318. }
  46319. return this.getScene().environmentTexture;
  46320. };
  46321. /**
  46322. * Returns the texture used for refraction or null if none is used.
  46323. * @returns - Refection texture if present. If no refraction texture and refraction
  46324. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46325. */
  46326. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46327. if (this._refractionTexture) {
  46328. return this._refractionTexture;
  46329. }
  46330. if (this._linkRefractionWithTransparency) {
  46331. return this.getScene().environmentTexture;
  46332. }
  46333. return null;
  46334. };
  46335. /**
  46336. * Disposes the resources of the material.
  46337. * @param forceDisposeEffect - Forces the disposal of effects.
  46338. * @param forceDisposeTextures - Forces the disposal of all textures.
  46339. */
  46340. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46341. if (forceDisposeTextures) {
  46342. if (this._albedoTexture) {
  46343. this._albedoTexture.dispose();
  46344. }
  46345. if (this._ambientTexture) {
  46346. this._ambientTexture.dispose();
  46347. }
  46348. if (this._opacityTexture) {
  46349. this._opacityTexture.dispose();
  46350. }
  46351. if (this._reflectionTexture) {
  46352. this._reflectionTexture.dispose();
  46353. }
  46354. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46355. this._environmentBRDFTexture.dispose();
  46356. }
  46357. if (this._emissiveTexture) {
  46358. this._emissiveTexture.dispose();
  46359. }
  46360. if (this._metallicTexture) {
  46361. this._metallicTexture.dispose();
  46362. }
  46363. if (this._reflectivityTexture) {
  46364. this._reflectivityTexture.dispose();
  46365. }
  46366. if (this._bumpTexture) {
  46367. this._bumpTexture.dispose();
  46368. }
  46369. if (this._lightmapTexture) {
  46370. this._lightmapTexture.dispose();
  46371. }
  46372. if (this._refractionTexture) {
  46373. this._refractionTexture.dispose();
  46374. }
  46375. }
  46376. this._renderTargets.dispose();
  46377. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46378. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46379. }
  46380. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46381. };
  46382. /**
  46383. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46384. */
  46385. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46386. /**
  46387. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46388. * to enhance interoperability with other engines.
  46389. */
  46390. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46391. /**
  46392. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46393. * to enhance interoperability with other materials.
  46394. */
  46395. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46396. /**
  46397. * Stores the reflectivity values based on metallic roughness workflow.
  46398. */
  46399. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46400. __decorate([
  46401. BABYLON.serializeAsImageProcessingConfiguration()
  46402. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46403. __decorate([
  46404. BABYLON.serialize()
  46405. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46406. __decorate([
  46407. BABYLON.serialize()
  46408. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46409. return PBRBaseMaterial;
  46410. }(BABYLON.PushMaterial));
  46411. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46412. })(BABYLON || (BABYLON = {}));
  46413. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46414. var BABYLON;
  46415. (function (BABYLON) {
  46416. /**
  46417. * The Physically based simple base material of BJS.
  46418. *
  46419. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46420. * It is used as the base class for both the specGloss and metalRough conventions.
  46421. */
  46422. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46423. __extends(PBRBaseSimpleMaterial, _super);
  46424. /**
  46425. * Instantiates a new PBRMaterial instance.
  46426. *
  46427. * @param name The material name
  46428. * @param scene The scene the material will be use in.
  46429. */
  46430. function PBRBaseSimpleMaterial(name, scene) {
  46431. var _this = _super.call(this, name, scene) || this;
  46432. /**
  46433. * Number of Simultaneous lights allowed on the material.
  46434. */
  46435. _this.maxSimultaneousLights = 4;
  46436. /**
  46437. * If sets to true, disables all the lights affecting the material.
  46438. */
  46439. _this.disableLighting = false;
  46440. /**
  46441. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46442. */
  46443. _this.invertNormalMapX = false;
  46444. /**
  46445. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46446. */
  46447. _this.invertNormalMapY = false;
  46448. /**
  46449. * Emissivie color used to self-illuminate the model.
  46450. */
  46451. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46452. /**
  46453. * Occlusion Channel Strenght.
  46454. */
  46455. _this.occlusionStrength = 1.0;
  46456. /**
  46457. * If true, the light map contains occlusion information instead of lighting info.
  46458. */
  46459. _this.useLightmapAsShadowmap = false;
  46460. _this._useAlphaFromAlbedoTexture = true;
  46461. _this._useAmbientInGrayScale = true;
  46462. return _this;
  46463. }
  46464. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46465. /**
  46466. * Gets the current double sided mode.
  46467. */
  46468. get: function () {
  46469. return this._twoSidedLighting;
  46470. },
  46471. /**
  46472. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46473. */
  46474. set: function (value) {
  46475. if (this._twoSidedLighting === value) {
  46476. return;
  46477. }
  46478. this._twoSidedLighting = value;
  46479. this.backFaceCulling = !value;
  46480. this._markAllSubMeshesAsTexturesDirty();
  46481. },
  46482. enumerable: true,
  46483. configurable: true
  46484. });
  46485. /**
  46486. * Return the active textures of the material.
  46487. */
  46488. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46489. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46490. if (this.environmentTexture) {
  46491. activeTextures.push(this.environmentTexture);
  46492. }
  46493. if (this.normalTexture) {
  46494. activeTextures.push(this.normalTexture);
  46495. }
  46496. if (this.emissiveTexture) {
  46497. activeTextures.push(this.emissiveTexture);
  46498. }
  46499. if (this.occlusionTexture) {
  46500. activeTextures.push(this.occlusionTexture);
  46501. }
  46502. if (this.lightmapTexture) {
  46503. activeTextures.push(this.lightmapTexture);
  46504. }
  46505. return activeTextures;
  46506. };
  46507. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46508. if (_super.prototype.hasTexture.call(this, texture)) {
  46509. return true;
  46510. }
  46511. if (this.lightmapTexture === texture) {
  46512. return true;
  46513. }
  46514. return false;
  46515. };
  46516. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46517. return "PBRBaseSimpleMaterial";
  46518. };
  46519. __decorate([
  46520. BABYLON.serialize(),
  46521. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46522. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46523. __decorate([
  46524. BABYLON.serialize(),
  46525. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46526. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46527. __decorate([
  46528. BABYLON.serializeAsTexture(),
  46529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46530. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46531. __decorate([
  46532. BABYLON.serialize(),
  46533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46534. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46535. __decorate([
  46536. BABYLON.serialize(),
  46537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46538. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46539. __decorate([
  46540. BABYLON.serializeAsTexture(),
  46541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46542. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46543. __decorate([
  46544. BABYLON.serializeAsColor3("emissive"),
  46545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46546. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46547. __decorate([
  46548. BABYLON.serializeAsTexture(),
  46549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46550. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46551. __decorate([
  46552. BABYLON.serialize(),
  46553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46554. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46555. __decorate([
  46556. BABYLON.serializeAsTexture(),
  46557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46558. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46559. __decorate([
  46560. BABYLON.serialize(),
  46561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46562. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46563. __decorate([
  46564. BABYLON.serialize()
  46565. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46566. __decorate([
  46567. BABYLON.serializeAsTexture(),
  46568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46569. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46570. __decorate([
  46571. BABYLON.serialize(),
  46572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46573. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46574. return PBRBaseSimpleMaterial;
  46575. }(BABYLON.PBRBaseMaterial));
  46576. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46577. })(BABYLON || (BABYLON = {}));
  46578. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46579. var BABYLON;
  46580. (function (BABYLON) {
  46581. /**
  46582. * The Physically based material of BJS.
  46583. *
  46584. * This offers the main features of a standard PBR material.
  46585. * For more information, please refer to the documentation :
  46586. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46587. */
  46588. var PBRMaterial = /** @class */ (function (_super) {
  46589. __extends(PBRMaterial, _super);
  46590. /**
  46591. * Instantiates a new PBRMaterial instance.
  46592. *
  46593. * @param name The material name
  46594. * @param scene The scene the material will be use in.
  46595. */
  46596. function PBRMaterial(name, scene) {
  46597. var _this = _super.call(this, name, scene) || this;
  46598. /**
  46599. * Intensity of the direct lights e.g. the four lights available in your scene.
  46600. * This impacts both the direct diffuse and specular highlights.
  46601. */
  46602. _this.directIntensity = 1.0;
  46603. /**
  46604. * Intensity of the emissive part of the material.
  46605. * This helps controlling the emissive effect without modifying the emissive color.
  46606. */
  46607. _this.emissiveIntensity = 1.0;
  46608. /**
  46609. * Intensity of the environment e.g. how much the environment will light the object
  46610. * either through harmonics for rough material or through the refelction for shiny ones.
  46611. */
  46612. _this.environmentIntensity = 1.0;
  46613. /**
  46614. * This is a special control allowing the reduction of the specular highlights coming from the
  46615. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46616. */
  46617. _this.specularIntensity = 1.0;
  46618. /**
  46619. * Debug Control allowing disabling the bump map on this material.
  46620. */
  46621. _this.disableBumpMap = false;
  46622. /**
  46623. * AKA Occlusion Texture Intensity in other nomenclature.
  46624. */
  46625. _this.ambientTextureStrength = 1.0;
  46626. /**
  46627. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46628. * 1 means it completely occludes it
  46629. * 0 mean it has no impact
  46630. */
  46631. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46632. /**
  46633. * The color of a material in ambient lighting.
  46634. */
  46635. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46636. /**
  46637. * AKA Diffuse Color in other nomenclature.
  46638. */
  46639. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46640. /**
  46641. * AKA Specular Color in other nomenclature.
  46642. */
  46643. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46644. /**
  46645. * The color reflected from the material.
  46646. */
  46647. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46648. /**
  46649. * The color emitted from the material.
  46650. */
  46651. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46652. /**
  46653. * AKA Glossiness in other nomenclature.
  46654. */
  46655. _this.microSurface = 1.0;
  46656. /**
  46657. * source material index of refraction (IOR)' / 'destination material IOR.
  46658. */
  46659. _this.indexOfRefraction = 0.66;
  46660. /**
  46661. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46662. */
  46663. _this.invertRefractionY = false;
  46664. /**
  46665. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46666. * Materials half opaque for instance using refraction could benefit from this control.
  46667. */
  46668. _this.linkRefractionWithTransparency = false;
  46669. /**
  46670. * If true, the light map contains occlusion information instead of lighting info.
  46671. */
  46672. _this.useLightmapAsShadowmap = false;
  46673. /**
  46674. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46675. */
  46676. _this.useAlphaFromAlbedoTexture = false;
  46677. /**
  46678. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46679. */
  46680. _this.forceAlphaTest = false;
  46681. /**
  46682. * Defines the alpha limits in alpha test mode.
  46683. */
  46684. _this.alphaCutOff = 0.4;
  46685. /**
  46686. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46687. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46688. */
  46689. _this.useSpecularOverAlpha = true;
  46690. /**
  46691. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46692. */
  46693. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46694. /**
  46695. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46696. */
  46697. _this.useRoughnessFromMetallicTextureAlpha = true;
  46698. /**
  46699. * Specifies if the metallic texture contains the roughness information in its green channel.
  46700. */
  46701. _this.useRoughnessFromMetallicTextureGreen = false;
  46702. /**
  46703. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46704. */
  46705. _this.useMetallnessFromMetallicTextureBlue = false;
  46706. /**
  46707. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46708. */
  46709. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46710. /**
  46711. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46712. */
  46713. _this.useAmbientInGrayScale = false;
  46714. /**
  46715. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46716. * The material will try to infer what glossiness each pixel should be.
  46717. */
  46718. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46719. /**
  46720. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46721. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46722. */
  46723. _this.useRadianceOverAlpha = true;
  46724. /**
  46725. * Allows using an object space normal map (instead of tangent space).
  46726. */
  46727. _this.useObjectSpaceNormalMap = false;
  46728. /**
  46729. * Allows using the bump map in parallax mode.
  46730. */
  46731. _this.useParallax = false;
  46732. /**
  46733. * Allows using the bump map in parallax occlusion mode.
  46734. */
  46735. _this.useParallaxOcclusion = false;
  46736. /**
  46737. * Controls the scale bias of the parallax mode.
  46738. */
  46739. _this.parallaxScaleBias = 0.05;
  46740. /**
  46741. * If sets to true, disables all the lights affecting the material.
  46742. */
  46743. _this.disableLighting = false;
  46744. /**
  46745. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46746. */
  46747. _this.forceIrradianceInFragment = false;
  46748. /**
  46749. * Number of Simultaneous lights allowed on the material.
  46750. */
  46751. _this.maxSimultaneousLights = 4;
  46752. /**
  46753. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46754. */
  46755. _this.invertNormalMapX = false;
  46756. /**
  46757. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46758. */
  46759. _this.invertNormalMapY = false;
  46760. /**
  46761. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46762. */
  46763. _this.twoSidedLighting = false;
  46764. /**
  46765. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46766. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46767. */
  46768. _this.useAlphaFresnel = false;
  46769. /**
  46770. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46771. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46772. */
  46773. _this.useLinearAlphaFresnel = false;
  46774. /**
  46775. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46776. * And/Or occlude the blended part.
  46777. */
  46778. _this.environmentBRDFTexture = null;
  46779. /**
  46780. * Force normal to face away from face.
  46781. */
  46782. _this.forceNormalForward = false;
  46783. /**
  46784. * Enables specular anti aliasing in the PBR shader.
  46785. * It will both interacts on the Geometry for analytical and IBL lighting.
  46786. * It also prefilter the roughness map based on the bump values.
  46787. */
  46788. _this.enableSpecularAntiAliasing = false;
  46789. /**
  46790. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46791. * makes the reflect vector face the model (under horizon).
  46792. */
  46793. _this.useHorizonOcclusion = true;
  46794. /**
  46795. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46796. * too much the area relying on ambient texture to define their ambient occlusion.
  46797. */
  46798. _this.useRadianceOcclusion = true;
  46799. /**
  46800. * If set to true, no lighting calculations will be applied.
  46801. */
  46802. _this.unlit = false;
  46803. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46804. return _this;
  46805. }
  46806. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46807. /**
  46808. * BJS is using an harcoded light falloff based on a manually sets up range.
  46809. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46810. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46811. */
  46812. get: function () {
  46813. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46814. },
  46815. /**
  46816. * BJS is using an harcoded light falloff based on a manually sets up range.
  46817. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46818. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46819. */
  46820. set: function (value) {
  46821. if (value !== this.usePhysicalLightFalloff) {
  46822. // Ensure the effect will be rebuilt.
  46823. this._markAllSubMeshesAsTexturesDirty();
  46824. if (value) {
  46825. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46826. }
  46827. else {
  46828. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46829. }
  46830. }
  46831. },
  46832. enumerable: true,
  46833. configurable: true
  46834. });
  46835. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46836. /**
  46837. * In order to support the falloff compatibility with gltf, a special mode has been added
  46838. * to reproduce the gltf light falloff.
  46839. */
  46840. get: function () {
  46841. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46842. },
  46843. /**
  46844. * In order to support the falloff compatibility with gltf, a special mode has been added
  46845. * to reproduce the gltf light falloff.
  46846. */
  46847. set: function (value) {
  46848. if (value !== this.useGLTFLightFalloff) {
  46849. // Ensure the effect will be rebuilt.
  46850. this._markAllSubMeshesAsTexturesDirty();
  46851. if (value) {
  46852. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46853. }
  46854. else {
  46855. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46856. }
  46857. }
  46858. },
  46859. enumerable: true,
  46860. configurable: true
  46861. });
  46862. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46863. /**
  46864. * Gets the image processing configuration used either in this material.
  46865. */
  46866. get: function () {
  46867. return this._imageProcessingConfiguration;
  46868. },
  46869. /**
  46870. * Sets the Default image processing configuration used either in the this material.
  46871. *
  46872. * If sets to null, the scene one is in use.
  46873. */
  46874. set: function (value) {
  46875. this._attachImageProcessingConfiguration(value);
  46876. // Ensure the effect will be rebuilt.
  46877. this._markAllSubMeshesAsTexturesDirty();
  46878. },
  46879. enumerable: true,
  46880. configurable: true
  46881. });
  46882. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46883. /**
  46884. * Gets wether the color curves effect is enabled.
  46885. */
  46886. get: function () {
  46887. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46888. },
  46889. /**
  46890. * Sets wether the color curves effect is enabled.
  46891. */
  46892. set: function (value) {
  46893. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46894. },
  46895. enumerable: true,
  46896. configurable: true
  46897. });
  46898. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46899. /**
  46900. * Gets wether the color grading effect is enabled.
  46901. */
  46902. get: function () {
  46903. return this.imageProcessingConfiguration.colorGradingEnabled;
  46904. },
  46905. /**
  46906. * Gets wether the color grading effect is enabled.
  46907. */
  46908. set: function (value) {
  46909. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46910. },
  46911. enumerable: true,
  46912. configurable: true
  46913. });
  46914. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46915. /**
  46916. * Gets wether tonemapping is enabled or not.
  46917. */
  46918. get: function () {
  46919. return this._imageProcessingConfiguration.toneMappingEnabled;
  46920. },
  46921. /**
  46922. * Sets wether tonemapping is enabled or not
  46923. */
  46924. set: function (value) {
  46925. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46926. },
  46927. enumerable: true,
  46928. configurable: true
  46929. });
  46930. ;
  46931. ;
  46932. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46933. /**
  46934. * The camera exposure used on this material.
  46935. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46936. * This corresponds to a photographic exposure.
  46937. */
  46938. get: function () {
  46939. return this._imageProcessingConfiguration.exposure;
  46940. },
  46941. /**
  46942. * The camera exposure used on this material.
  46943. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46944. * This corresponds to a photographic exposure.
  46945. */
  46946. set: function (value) {
  46947. this._imageProcessingConfiguration.exposure = value;
  46948. },
  46949. enumerable: true,
  46950. configurable: true
  46951. });
  46952. ;
  46953. ;
  46954. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46955. /**
  46956. * Gets The camera contrast used on this material.
  46957. */
  46958. get: function () {
  46959. return this._imageProcessingConfiguration.contrast;
  46960. },
  46961. /**
  46962. * Sets The camera contrast used on this material.
  46963. */
  46964. set: function (value) {
  46965. this._imageProcessingConfiguration.contrast = value;
  46966. },
  46967. enumerable: true,
  46968. configurable: true
  46969. });
  46970. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46971. /**
  46972. * Gets the Color Grading 2D Lookup Texture.
  46973. */
  46974. get: function () {
  46975. return this._imageProcessingConfiguration.colorGradingTexture;
  46976. },
  46977. /**
  46978. * Sets the Color Grading 2D Lookup Texture.
  46979. */
  46980. set: function (value) {
  46981. this._imageProcessingConfiguration.colorGradingTexture = value;
  46982. },
  46983. enumerable: true,
  46984. configurable: true
  46985. });
  46986. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46987. /**
  46988. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46989. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46990. * 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;
  46991. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46992. */
  46993. get: function () {
  46994. return this._imageProcessingConfiguration.colorCurves;
  46995. },
  46996. /**
  46997. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46998. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46999. * 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;
  47000. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47001. */
  47002. set: function (value) {
  47003. this._imageProcessingConfiguration.colorCurves = value;
  47004. },
  47005. enumerable: true,
  47006. configurable: true
  47007. });
  47008. /**
  47009. * Returns the name of this material class.
  47010. */
  47011. PBRMaterial.prototype.getClassName = function () {
  47012. return "PBRMaterial";
  47013. };
  47014. /**
  47015. * Returns an array of the actively used textures.
  47016. * @returns - Array of BaseTextures
  47017. */
  47018. PBRMaterial.prototype.getActiveTextures = function () {
  47019. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47020. if (this._albedoTexture) {
  47021. activeTextures.push(this._albedoTexture);
  47022. }
  47023. if (this._ambientTexture) {
  47024. activeTextures.push(this._ambientTexture);
  47025. }
  47026. if (this._opacityTexture) {
  47027. activeTextures.push(this._opacityTexture);
  47028. }
  47029. if (this._reflectionTexture) {
  47030. activeTextures.push(this._reflectionTexture);
  47031. }
  47032. if (this._emissiveTexture) {
  47033. activeTextures.push(this._emissiveTexture);
  47034. }
  47035. if (this._reflectivityTexture) {
  47036. activeTextures.push(this._reflectivityTexture);
  47037. }
  47038. if (this._metallicTexture) {
  47039. activeTextures.push(this._metallicTexture);
  47040. }
  47041. if (this._microSurfaceTexture) {
  47042. activeTextures.push(this._microSurfaceTexture);
  47043. }
  47044. if (this._bumpTexture) {
  47045. activeTextures.push(this._bumpTexture);
  47046. }
  47047. if (this._lightmapTexture) {
  47048. activeTextures.push(this._lightmapTexture);
  47049. }
  47050. if (this._refractionTexture) {
  47051. activeTextures.push(this._refractionTexture);
  47052. }
  47053. return activeTextures;
  47054. };
  47055. /**
  47056. * Checks to see if a texture is used in the material.
  47057. * @param texture - Base texture to use.
  47058. * @returns - Boolean specifying if a texture is used in the material.
  47059. */
  47060. PBRMaterial.prototype.hasTexture = function (texture) {
  47061. if (_super.prototype.hasTexture.call(this, texture)) {
  47062. return true;
  47063. }
  47064. if (this._albedoTexture === texture) {
  47065. return true;
  47066. }
  47067. if (this._ambientTexture === texture) {
  47068. return true;
  47069. }
  47070. if (this._opacityTexture === texture) {
  47071. return true;
  47072. }
  47073. if (this._reflectionTexture === texture) {
  47074. return true;
  47075. }
  47076. if (this._reflectivityTexture === texture) {
  47077. return true;
  47078. }
  47079. if (this._metallicTexture === texture) {
  47080. return true;
  47081. }
  47082. if (this._microSurfaceTexture === texture) {
  47083. return true;
  47084. }
  47085. if (this._bumpTexture === texture) {
  47086. return true;
  47087. }
  47088. if (this._lightmapTexture === texture) {
  47089. return true;
  47090. }
  47091. if (this._refractionTexture === texture) {
  47092. return true;
  47093. }
  47094. return false;
  47095. };
  47096. /**
  47097. * Makes a duplicate of the current material.
  47098. * @param name - name to use for the new material.
  47099. */
  47100. PBRMaterial.prototype.clone = function (name) {
  47101. var _this = this;
  47102. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47103. clone.id = name;
  47104. clone.name = name;
  47105. return clone;
  47106. };
  47107. /**
  47108. * Serializes this PBR Material.
  47109. * @returns - An object with the serialized material.
  47110. */
  47111. PBRMaterial.prototype.serialize = function () {
  47112. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47113. serializationObject.customType = "BABYLON.PBRMaterial";
  47114. return serializationObject;
  47115. };
  47116. // Statics
  47117. /**
  47118. * Parses a PBR Material from a serialized object.
  47119. * @param source - Serialized object.
  47120. * @param scene - BJS scene instance.
  47121. * @param rootUrl - url for the scene object
  47122. * @returns - PBRMaterial
  47123. */
  47124. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47125. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47126. };
  47127. /**
  47128. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47129. */
  47130. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47131. /**
  47132. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47133. */
  47134. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47135. /**
  47136. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47137. */
  47138. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47139. /**
  47140. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47141. * They are also discarded below the alpha cutoff threshold to improve performances.
  47142. */
  47143. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47144. /**
  47145. * Defines the default value of how much AO map is occluding the analytical lights
  47146. * (point spot...).
  47147. */
  47148. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47149. __decorate([
  47150. BABYLON.serialize(),
  47151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47152. ], PBRMaterial.prototype, "directIntensity", void 0);
  47153. __decorate([
  47154. BABYLON.serialize(),
  47155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47156. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47157. __decorate([
  47158. BABYLON.serialize(),
  47159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47160. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47161. __decorate([
  47162. BABYLON.serialize(),
  47163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47164. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47165. __decorate([
  47166. BABYLON.serialize(),
  47167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47168. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47169. __decorate([
  47170. BABYLON.serializeAsTexture(),
  47171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47172. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47173. __decorate([
  47174. BABYLON.serializeAsTexture(),
  47175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47176. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47177. __decorate([
  47178. BABYLON.serialize(),
  47179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47180. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47181. __decorate([
  47182. BABYLON.serialize(),
  47183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47184. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47185. __decorate([
  47186. BABYLON.serializeAsTexture(),
  47187. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47188. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47189. __decorate([
  47190. BABYLON.serializeAsTexture(),
  47191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47192. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47193. __decorate([
  47194. BABYLON.serializeAsTexture(),
  47195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47196. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47197. __decorate([
  47198. BABYLON.serializeAsTexture(),
  47199. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47200. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47201. __decorate([
  47202. BABYLON.serializeAsTexture(),
  47203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47204. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47205. __decorate([
  47206. BABYLON.serialize(),
  47207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47208. ], PBRMaterial.prototype, "metallic", void 0);
  47209. __decorate([
  47210. BABYLON.serialize(),
  47211. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47212. ], PBRMaterial.prototype, "roughness", void 0);
  47213. __decorate([
  47214. BABYLON.serializeAsTexture(),
  47215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47216. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47217. __decorate([
  47218. BABYLON.serializeAsTexture(),
  47219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47220. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47221. __decorate([
  47222. BABYLON.serializeAsTexture(),
  47223. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47224. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47225. __decorate([
  47226. BABYLON.serializeAsTexture(),
  47227. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47228. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47229. __decorate([
  47230. BABYLON.serializeAsColor3("ambient"),
  47231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47232. ], PBRMaterial.prototype, "ambientColor", void 0);
  47233. __decorate([
  47234. BABYLON.serializeAsColor3("albedo"),
  47235. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47236. ], PBRMaterial.prototype, "albedoColor", void 0);
  47237. __decorate([
  47238. BABYLON.serializeAsColor3("reflectivity"),
  47239. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47240. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47241. __decorate([
  47242. BABYLON.serializeAsColor3("reflection"),
  47243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47244. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47245. __decorate([
  47246. BABYLON.serializeAsColor3("emissive"),
  47247. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47248. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47249. __decorate([
  47250. BABYLON.serialize(),
  47251. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47252. ], PBRMaterial.prototype, "microSurface", void 0);
  47253. __decorate([
  47254. BABYLON.serialize(),
  47255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47256. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47257. __decorate([
  47258. BABYLON.serialize(),
  47259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47260. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47261. __decorate([
  47262. BABYLON.serialize(),
  47263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47264. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47265. __decorate([
  47266. BABYLON.serialize(),
  47267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47268. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47269. __decorate([
  47270. BABYLON.serialize(),
  47271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47272. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47273. __decorate([
  47274. BABYLON.serialize(),
  47275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47276. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47277. __decorate([
  47278. BABYLON.serialize(),
  47279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47280. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47281. __decorate([
  47282. BABYLON.serialize(),
  47283. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47284. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47285. __decorate([
  47286. BABYLON.serialize(),
  47287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47288. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47289. __decorate([
  47290. BABYLON.serialize(),
  47291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47292. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47293. __decorate([
  47294. BABYLON.serialize(),
  47295. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47296. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47297. __decorate([
  47298. BABYLON.serialize(),
  47299. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47300. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47301. __decorate([
  47302. BABYLON.serialize(),
  47303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47304. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47305. __decorate([
  47306. BABYLON.serialize(),
  47307. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47308. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47309. __decorate([
  47310. BABYLON.serialize(),
  47311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47312. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47313. __decorate([
  47314. BABYLON.serialize()
  47315. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47316. __decorate([
  47317. BABYLON.serialize()
  47318. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47319. __decorate([
  47320. BABYLON.serialize(),
  47321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47322. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47323. __decorate([
  47324. BABYLON.serialize(),
  47325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47326. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47327. __decorate([
  47328. BABYLON.serialize(),
  47329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47330. ], PBRMaterial.prototype, "useParallax", void 0);
  47331. __decorate([
  47332. BABYLON.serialize(),
  47333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47334. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47335. __decorate([
  47336. BABYLON.serialize(),
  47337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47338. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47339. __decorate([
  47340. BABYLON.serialize(),
  47341. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47342. ], PBRMaterial.prototype, "disableLighting", void 0);
  47343. __decorate([
  47344. BABYLON.serialize(),
  47345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47346. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47347. __decorate([
  47348. BABYLON.serialize(),
  47349. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47350. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47351. __decorate([
  47352. BABYLON.serialize(),
  47353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47354. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47355. __decorate([
  47356. BABYLON.serialize(),
  47357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47358. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47359. __decorate([
  47360. BABYLON.serialize(),
  47361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47362. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47363. __decorate([
  47364. BABYLON.serialize(),
  47365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47366. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47367. __decorate([
  47368. BABYLON.serialize(),
  47369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47370. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47371. __decorate([
  47372. BABYLON.serializeAsTexture(),
  47373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47374. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47375. __decorate([
  47376. BABYLON.serialize(),
  47377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47378. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47379. __decorate([
  47380. BABYLON.serialize(),
  47381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47382. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47383. __decorate([
  47384. BABYLON.serialize(),
  47385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47386. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47387. __decorate([
  47388. BABYLON.serialize(),
  47389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47390. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47391. __decorate([
  47392. BABYLON.serialize(),
  47393. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47394. ], PBRMaterial.prototype, "unlit", void 0);
  47395. return PBRMaterial;
  47396. }(BABYLON.PBRBaseMaterial));
  47397. BABYLON.PBRMaterial = PBRMaterial;
  47398. })(BABYLON || (BABYLON = {}));
  47399. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47400. var BABYLON;
  47401. (function (BABYLON) {
  47402. /**
  47403. * The PBR material of BJS following the metal roughness convention.
  47404. *
  47405. * This fits to the PBR convention in the GLTF definition:
  47406. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47407. */
  47408. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47409. __extends(PBRMetallicRoughnessMaterial, _super);
  47410. /**
  47411. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47412. *
  47413. * @param name The material name
  47414. * @param scene The scene the material will be use in.
  47415. */
  47416. function PBRMetallicRoughnessMaterial(name, scene) {
  47417. var _this = _super.call(this, name, scene) || this;
  47418. _this._useRoughnessFromMetallicTextureAlpha = false;
  47419. _this._useRoughnessFromMetallicTextureGreen = true;
  47420. _this._useMetallnessFromMetallicTextureBlue = true;
  47421. _this.metallic = 1.0;
  47422. _this.roughness = 1.0;
  47423. return _this;
  47424. }
  47425. /**
  47426. * Return the currrent class name of the material.
  47427. */
  47428. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47429. return "PBRMetallicRoughnessMaterial";
  47430. };
  47431. /**
  47432. * Return the active textures of the material.
  47433. */
  47434. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47435. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47436. if (this.baseTexture) {
  47437. activeTextures.push(this.baseTexture);
  47438. }
  47439. if (this.metallicRoughnessTexture) {
  47440. activeTextures.push(this.metallicRoughnessTexture);
  47441. }
  47442. return activeTextures;
  47443. };
  47444. /**
  47445. * Checks to see if a texture is used in the material.
  47446. * @param texture - Base texture to use.
  47447. * @returns - Boolean specifying if a texture is used in the material.
  47448. */
  47449. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47450. if (_super.prototype.hasTexture.call(this, texture)) {
  47451. return true;
  47452. }
  47453. if (this.baseTexture === texture) {
  47454. return true;
  47455. }
  47456. if (this.metallicRoughnessTexture === texture) {
  47457. return true;
  47458. }
  47459. return false;
  47460. };
  47461. /**
  47462. * Makes a duplicate of the current material.
  47463. * @param name - name to use for the new material.
  47464. */
  47465. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47466. var _this = this;
  47467. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47468. clone.id = name;
  47469. clone.name = name;
  47470. return clone;
  47471. };
  47472. /**
  47473. * Serialize the material to a parsable JSON object.
  47474. */
  47475. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47477. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47478. return serializationObject;
  47479. };
  47480. /**
  47481. * Parses a JSON object correponding to the serialize function.
  47482. */
  47483. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47484. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47485. };
  47486. __decorate([
  47487. BABYLON.serializeAsColor3(),
  47488. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47489. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47490. __decorate([
  47491. BABYLON.serializeAsTexture(),
  47492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47493. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47494. __decorate([
  47495. BABYLON.serialize(),
  47496. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47497. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47498. __decorate([
  47499. BABYLON.serialize(),
  47500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47501. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47502. __decorate([
  47503. BABYLON.serializeAsTexture(),
  47504. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47505. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47506. return PBRMetallicRoughnessMaterial;
  47507. }(BABYLON.PBRBaseSimpleMaterial));
  47508. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47509. })(BABYLON || (BABYLON = {}));
  47510. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47511. var BABYLON;
  47512. (function (BABYLON) {
  47513. /**
  47514. * The PBR material of BJS following the specular glossiness convention.
  47515. *
  47516. * This fits to the PBR convention in the GLTF definition:
  47517. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47518. */
  47519. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47520. __extends(PBRSpecularGlossinessMaterial, _super);
  47521. /**
  47522. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47523. *
  47524. * @param name The material name
  47525. * @param scene The scene the material will be use in.
  47526. */
  47527. function PBRSpecularGlossinessMaterial(name, scene) {
  47528. var _this = _super.call(this, name, scene) || this;
  47529. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47530. return _this;
  47531. }
  47532. /**
  47533. * Return the currrent class name of the material.
  47534. */
  47535. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47536. return "PBRSpecularGlossinessMaterial";
  47537. };
  47538. /**
  47539. * Return the active textures of the material.
  47540. */
  47541. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47542. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47543. if (this.diffuseTexture) {
  47544. activeTextures.push(this.diffuseTexture);
  47545. }
  47546. if (this.specularGlossinessTexture) {
  47547. activeTextures.push(this.specularGlossinessTexture);
  47548. }
  47549. return activeTextures;
  47550. };
  47551. /**
  47552. * Checks to see if a texture is used in the material.
  47553. * @param texture - Base texture to use.
  47554. * @returns - Boolean specifying if a texture is used in the material.
  47555. */
  47556. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47557. if (_super.prototype.hasTexture.call(this, texture)) {
  47558. return true;
  47559. }
  47560. if (this.diffuseTexture === texture) {
  47561. return true;
  47562. }
  47563. if (this.specularGlossinessTexture === texture) {
  47564. return true;
  47565. }
  47566. return false;
  47567. };
  47568. /**
  47569. * Makes a duplicate of the current material.
  47570. * @param name - name to use for the new material.
  47571. */
  47572. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47573. var _this = this;
  47574. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47575. clone.id = name;
  47576. clone.name = name;
  47577. return clone;
  47578. };
  47579. /**
  47580. * Serialize the material to a parsable JSON object.
  47581. */
  47582. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47583. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47584. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47585. return serializationObject;
  47586. };
  47587. /**
  47588. * Parses a JSON object correponding to the serialize function.
  47589. */
  47590. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47591. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47592. };
  47593. __decorate([
  47594. BABYLON.serializeAsColor3("diffuse"),
  47595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47596. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47597. __decorate([
  47598. BABYLON.serializeAsTexture(),
  47599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47600. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47601. __decorate([
  47602. BABYLON.serializeAsColor3("specular"),
  47603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47604. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47605. __decorate([
  47606. BABYLON.serialize(),
  47607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47608. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47609. __decorate([
  47610. BABYLON.serializeAsTexture(),
  47611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47612. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47613. return PBRSpecularGlossinessMaterial;
  47614. }(BABYLON.PBRBaseSimpleMaterial));
  47615. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47616. })(BABYLON || (BABYLON = {}));
  47617. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47618. var BABYLON;
  47619. (function (BABYLON) {
  47620. /**
  47621. * @ignore
  47622. * This is a list of all the different input types that are available in the application.
  47623. * Fo instance: ArcRotateCameraGamepadInput...
  47624. */
  47625. BABYLON.CameraInputTypes = {};
  47626. /**
  47627. * This represents the input manager used within a camera.
  47628. * It helps dealing with all the different kind of input attached to a camera.
  47629. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47630. */
  47631. var CameraInputsManager = /** @class */ (function () {
  47632. /**
  47633. * Instantiate a new Camera Input Manager.
  47634. * @param camera Defines the camera the input manager blongs to
  47635. */
  47636. function CameraInputsManager(camera) {
  47637. this.attached = {};
  47638. this.camera = camera;
  47639. this.checkInputs = function () { };
  47640. }
  47641. /**
  47642. * Add an input method to a camera
  47643. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47644. * @param input camera input method
  47645. */
  47646. CameraInputsManager.prototype.add = function (input) {
  47647. var type = input.getSimpleName();
  47648. if (this.attached[type]) {
  47649. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47650. return;
  47651. }
  47652. this.attached[type] = input;
  47653. input.camera = this.camera;
  47654. //for checkInputs, we are dynamically creating a function
  47655. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47656. if (input.checkInputs) {
  47657. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47658. }
  47659. if (this.attachedElement) {
  47660. input.attachControl(this.attachedElement);
  47661. }
  47662. };
  47663. /**
  47664. * Remove a specific input method from a camera
  47665. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47666. * @param inputToRemove camera input method
  47667. */
  47668. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47669. for (var cam in this.attached) {
  47670. var input = this.attached[cam];
  47671. if (input === inputToRemove) {
  47672. input.detachControl(this.attachedElement);
  47673. input.camera = null;
  47674. delete this.attached[cam];
  47675. this.rebuildInputCheck();
  47676. }
  47677. }
  47678. };
  47679. /**
  47680. * Remove a specific input type from a camera
  47681. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47682. * @param inputType the type of the input to remove
  47683. */
  47684. CameraInputsManager.prototype.removeByType = function (inputType) {
  47685. for (var cam in this.attached) {
  47686. var input = this.attached[cam];
  47687. if (input.getClassName() === inputType) {
  47688. input.detachControl(this.attachedElement);
  47689. input.camera = null;
  47690. delete this.attached[cam];
  47691. this.rebuildInputCheck();
  47692. }
  47693. }
  47694. };
  47695. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47696. var current = this.checkInputs;
  47697. return function () {
  47698. current();
  47699. fn();
  47700. };
  47701. };
  47702. /**
  47703. * Attach the input controls to the currently attached dom element to listen the events from.
  47704. * @param input Defines the input to attach
  47705. */
  47706. CameraInputsManager.prototype.attachInput = function (input) {
  47707. if (this.attachedElement) {
  47708. input.attachControl(this.attachedElement, this.noPreventDefault);
  47709. }
  47710. };
  47711. /**
  47712. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47713. * @param element Defines the dom element to collect the events from
  47714. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47715. */
  47716. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47717. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47718. if (this.attachedElement) {
  47719. return;
  47720. }
  47721. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47722. this.attachedElement = element;
  47723. this.noPreventDefault = noPreventDefault;
  47724. for (var cam in this.attached) {
  47725. this.attached[cam].attachControl(element, noPreventDefault);
  47726. }
  47727. };
  47728. /**
  47729. * Detach the current manager inputs controls from a specific dom element.
  47730. * @param element Defines the dom element to collect the events from
  47731. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47732. */
  47733. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47734. if (disconnect === void 0) { disconnect = false; }
  47735. if (this.attachedElement !== element) {
  47736. return;
  47737. }
  47738. for (var cam in this.attached) {
  47739. this.attached[cam].detachControl(element);
  47740. if (disconnect) {
  47741. this.attached[cam].camera = null;
  47742. }
  47743. }
  47744. this.attachedElement = null;
  47745. };
  47746. /**
  47747. * Rebuild the dynamic inputCheck function from the current list of
  47748. * defined inputs in the manager.
  47749. */
  47750. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47751. this.checkInputs = function () { };
  47752. for (var cam in this.attached) {
  47753. var input = this.attached[cam];
  47754. if (input.checkInputs) {
  47755. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47756. }
  47757. }
  47758. };
  47759. /**
  47760. * Remove all attached input methods from a camera
  47761. */
  47762. CameraInputsManager.prototype.clear = function () {
  47763. if (this.attachedElement) {
  47764. this.detachElement(this.attachedElement, true);
  47765. }
  47766. this.attached = {};
  47767. this.attachedElement = null;
  47768. this.checkInputs = function () { };
  47769. };
  47770. /**
  47771. * Serialize the current input manager attached to a camera.
  47772. * This ensures than once parsed,
  47773. * the input associated to the camera will be identical to the current ones
  47774. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47775. */
  47776. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47777. var inputs = {};
  47778. for (var cam in this.attached) {
  47779. var input = this.attached[cam];
  47780. var res = BABYLON.SerializationHelper.Serialize(input);
  47781. inputs[input.getClassName()] = res;
  47782. }
  47783. serializedCamera.inputsmgr = inputs;
  47784. };
  47785. /**
  47786. * Parses an input manager serialized JSON to restore the previous list of inputs
  47787. * and states associated to a camera.
  47788. * @param parsedCamera Defines the JSON to parse
  47789. */
  47790. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47791. var parsedInputs = parsedCamera.inputsmgr;
  47792. if (parsedInputs) {
  47793. this.clear();
  47794. for (var n in parsedInputs) {
  47795. var construct = BABYLON.CameraInputTypes[n];
  47796. if (construct) {
  47797. var parsedinput = parsedInputs[n];
  47798. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47799. this.add(input);
  47800. }
  47801. }
  47802. }
  47803. else {
  47804. //2016-03-08 this part is for managing backward compatibility
  47805. for (var n in this.attached) {
  47806. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47807. if (construct) {
  47808. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47809. this.remove(this.attached[n]);
  47810. this.add(input);
  47811. }
  47812. }
  47813. }
  47814. };
  47815. return CameraInputsManager;
  47816. }());
  47817. BABYLON.CameraInputsManager = CameraInputsManager;
  47818. })(BABYLON || (BABYLON = {}));
  47819. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47820. var BABYLON;
  47821. (function (BABYLON) {
  47822. /**
  47823. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47824. * This is the base of the follow, arc rotate cameras and Free camera
  47825. * @see http://doc.babylonjs.com/features/cameras
  47826. */
  47827. var TargetCamera = /** @class */ (function (_super) {
  47828. __extends(TargetCamera, _super);
  47829. /**
  47830. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47831. * This is the base of the follow, arc rotate cameras and Free camera
  47832. * @see http://doc.babylonjs.com/features/cameras
  47833. * @param name Defines the name of the camera in the scene
  47834. * @param position Defines the start position of the camera in the scene
  47835. * @param scene Defines the scene the camera belongs to
  47836. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47837. */
  47838. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47839. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47840. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47841. /**
  47842. * Define the current direction the camera is moving to
  47843. */
  47844. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47845. /**
  47846. * Define the current rotation the camera is rotating to
  47847. */
  47848. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47849. /**
  47850. * Define the current rotation of the camera
  47851. */
  47852. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47853. /**
  47854. * Define the current speed of the camera
  47855. */
  47856. _this.speed = 2.0;
  47857. /**
  47858. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47859. * around all axis.
  47860. */
  47861. _this.noRotationConstraint = false;
  47862. /**
  47863. * Define the current target of the camera as an object or a position.
  47864. */
  47865. _this.lockedTarget = null;
  47866. /** @hidden */
  47867. _this._currentTarget = BABYLON.Vector3.Zero();
  47868. /** @hidden */
  47869. _this._viewMatrix = BABYLON.Matrix.Zero();
  47870. /** @hidden */
  47871. _this._camMatrix = BABYLON.Matrix.Zero();
  47872. /** @hidden */
  47873. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47874. /** @hidden */
  47875. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47876. /** @hidden */
  47877. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47878. /** @hidden */
  47879. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47880. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47881. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47882. _this._defaultUp = BABYLON.Vector3.Up();
  47883. _this._cachedRotationZ = 0;
  47884. _this._cachedQuaternionRotationZ = 0;
  47885. return _this;
  47886. }
  47887. /**
  47888. * Gets the position in front of the camera at a given distance.
  47889. * @param distance The distance from the camera we want the position to be
  47890. * @returns the position
  47891. */
  47892. TargetCamera.prototype.getFrontPosition = function (distance) {
  47893. this.getWorldMatrix();
  47894. var direction = this.getTarget().subtract(this.position);
  47895. direction.normalize();
  47896. direction.scaleInPlace(distance);
  47897. return this.globalPosition.add(direction);
  47898. };
  47899. /** @hidden */
  47900. TargetCamera.prototype._getLockedTargetPosition = function () {
  47901. if (!this.lockedTarget) {
  47902. return null;
  47903. }
  47904. if (this.lockedTarget.absolutePosition) {
  47905. this.lockedTarget.computeWorldMatrix();
  47906. }
  47907. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47908. };
  47909. /**
  47910. * Store current camera state of the camera (fov, position, rotation, etc..)
  47911. * @returns the camera
  47912. */
  47913. TargetCamera.prototype.storeState = function () {
  47914. this._storedPosition = this.position.clone();
  47915. this._storedRotation = this.rotation.clone();
  47916. if (this.rotationQuaternion) {
  47917. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47918. }
  47919. return _super.prototype.storeState.call(this);
  47920. };
  47921. /**
  47922. * Restored camera state. You must call storeState() first
  47923. * @returns whether it was successful or not
  47924. * @hidden
  47925. */
  47926. TargetCamera.prototype._restoreStateValues = function () {
  47927. if (!_super.prototype._restoreStateValues.call(this)) {
  47928. return false;
  47929. }
  47930. this.position = this._storedPosition.clone();
  47931. this.rotation = this._storedRotation.clone();
  47932. if (this.rotationQuaternion) {
  47933. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47934. }
  47935. this.cameraDirection.copyFromFloats(0, 0, 0);
  47936. this.cameraRotation.copyFromFloats(0, 0);
  47937. return true;
  47938. };
  47939. /** @hidden */
  47940. TargetCamera.prototype._initCache = function () {
  47941. _super.prototype._initCache.call(this);
  47942. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47943. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47944. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47945. };
  47946. /** @hidden */
  47947. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47948. if (!ignoreParentClass) {
  47949. _super.prototype._updateCache.call(this);
  47950. }
  47951. var lockedTargetPosition = this._getLockedTargetPosition();
  47952. if (!lockedTargetPosition) {
  47953. this._cache.lockedTarget = null;
  47954. }
  47955. else {
  47956. if (!this._cache.lockedTarget) {
  47957. this._cache.lockedTarget = lockedTargetPosition.clone();
  47958. }
  47959. else {
  47960. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47961. }
  47962. }
  47963. this._cache.rotation.copyFrom(this.rotation);
  47964. if (this.rotationQuaternion)
  47965. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47966. };
  47967. // Synchronized
  47968. /** @hidden */
  47969. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47970. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47971. return false;
  47972. }
  47973. var lockedTargetPosition = this._getLockedTargetPosition();
  47974. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47975. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47976. };
  47977. // Methods
  47978. /** @hidden */
  47979. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47980. var engine = this.getEngine();
  47981. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47982. };
  47983. // Target
  47984. /** @hidden */
  47985. TargetCamera.prototype.setTarget = function (target) {
  47986. this.upVector.normalize();
  47987. if (this.position.z === target.z) {
  47988. this.position.z += BABYLON.Epsilon;
  47989. }
  47990. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  47991. this._camMatrix.invert();
  47992. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47993. var vDir = target.subtract(this.position);
  47994. if (vDir.x >= 0.0) {
  47995. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47996. }
  47997. else {
  47998. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47999. }
  48000. this.rotation.z = 0;
  48001. if (isNaN(this.rotation.x)) {
  48002. this.rotation.x = 0;
  48003. }
  48004. if (isNaN(this.rotation.y)) {
  48005. this.rotation.y = 0;
  48006. }
  48007. if (isNaN(this.rotation.z)) {
  48008. this.rotation.z = 0;
  48009. }
  48010. if (this.rotationQuaternion) {
  48011. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48012. }
  48013. };
  48014. /**
  48015. * Return the current target position of the camera. This value is expressed in local space.
  48016. * @returns the target position
  48017. */
  48018. TargetCamera.prototype.getTarget = function () {
  48019. return this._currentTarget;
  48020. };
  48021. /** @hidden */
  48022. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48023. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48024. };
  48025. /** @hidden */
  48026. TargetCamera.prototype._updatePosition = function () {
  48027. if (this.parent) {
  48028. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48029. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48030. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48031. return;
  48032. }
  48033. this.position.addInPlace(this.cameraDirection);
  48034. };
  48035. /** @hidden */
  48036. TargetCamera.prototype._checkInputs = function () {
  48037. var needToMove = this._decideIfNeedsToMove();
  48038. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48039. // Move
  48040. if (needToMove) {
  48041. this._updatePosition();
  48042. }
  48043. // Rotate
  48044. if (needToRotate) {
  48045. this.rotation.x += this.cameraRotation.x;
  48046. this.rotation.y += this.cameraRotation.y;
  48047. //rotate, if quaternion is set and rotation was used
  48048. if (this.rotationQuaternion) {
  48049. var len = this.rotation.lengthSquared();
  48050. if (len) {
  48051. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48052. }
  48053. }
  48054. if (!this.noRotationConstraint) {
  48055. var limit = (Math.PI / 2) * 0.95;
  48056. if (this.rotation.x > limit)
  48057. this.rotation.x = limit;
  48058. if (this.rotation.x < -limit)
  48059. this.rotation.x = -limit;
  48060. }
  48061. }
  48062. // Inertia
  48063. if (needToMove) {
  48064. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48065. this.cameraDirection.x = 0;
  48066. }
  48067. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48068. this.cameraDirection.y = 0;
  48069. }
  48070. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48071. this.cameraDirection.z = 0;
  48072. }
  48073. this.cameraDirection.scaleInPlace(this.inertia);
  48074. }
  48075. if (needToRotate) {
  48076. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48077. this.cameraRotation.x = 0;
  48078. }
  48079. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48080. this.cameraRotation.y = 0;
  48081. }
  48082. this.cameraRotation.scaleInPlace(this.inertia);
  48083. }
  48084. _super.prototype._checkInputs.call(this);
  48085. };
  48086. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48087. if (this.rotationQuaternion) {
  48088. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48089. }
  48090. else {
  48091. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48092. }
  48093. };
  48094. /**
  48095. * 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)
  48096. * @returns the current camera
  48097. */
  48098. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48099. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48100. return this;
  48101. };
  48102. /** @hidden */
  48103. TargetCamera.prototype._getViewMatrix = function () {
  48104. if (this.lockedTarget) {
  48105. this.setTarget(this._getLockedTargetPosition());
  48106. }
  48107. // Compute
  48108. this._updateCameraRotationMatrix();
  48109. // Apply the changed rotation to the upVector
  48110. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48111. this._rotateUpVectorWithCameraRotationMatrix();
  48112. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48113. }
  48114. else if (this._cachedRotationZ != this.rotation.z) {
  48115. this._rotateUpVectorWithCameraRotationMatrix();
  48116. this._cachedRotationZ = this.rotation.z;
  48117. }
  48118. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48119. // Computing target and final matrix
  48120. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48121. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48122. return this._viewMatrix;
  48123. };
  48124. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48125. if (this.parent) {
  48126. var parentWorldMatrix = this.parent.getWorldMatrix();
  48127. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48128. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48129. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48130. this._markSyncedWithParent();
  48131. }
  48132. else {
  48133. this._globalPosition.copyFrom(position);
  48134. this._globalCurrentTarget.copyFrom(target);
  48135. this._globalCurrentUpVector.copyFrom(up);
  48136. }
  48137. if (this.getScene().useRightHandedSystem) {
  48138. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48139. }
  48140. else {
  48141. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48142. }
  48143. };
  48144. /**
  48145. * @hidden
  48146. */
  48147. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48148. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48149. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48150. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48151. if (!this.rotationQuaternion) {
  48152. this.rotationQuaternion = new BABYLON.Quaternion();
  48153. }
  48154. rigCamera._cameraRigParams = {};
  48155. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48156. }
  48157. return rigCamera;
  48158. }
  48159. return null;
  48160. };
  48161. /**
  48162. * @hidden
  48163. */
  48164. TargetCamera.prototype._updateRigCameras = function () {
  48165. var camLeft = this._rigCameras[0];
  48166. var camRight = this._rigCameras[1];
  48167. switch (this.cameraRigMode) {
  48168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48170. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48171. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48172. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48173. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48174. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48175. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48176. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48177. camLeft.setTarget(this.getTarget());
  48178. camRight.setTarget(this.getTarget());
  48179. break;
  48180. case BABYLON.Camera.RIG_MODE_VR:
  48181. if (camLeft.rotationQuaternion) {
  48182. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48183. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48184. }
  48185. else {
  48186. camLeft.rotation.copyFrom(this.rotation);
  48187. camRight.rotation.copyFrom(this.rotation);
  48188. }
  48189. camLeft.position.copyFrom(this.position);
  48190. camRight.position.copyFrom(this.position);
  48191. break;
  48192. }
  48193. _super.prototype._updateRigCameras.call(this);
  48194. };
  48195. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48196. if (!this._rigCamTransformMatrix) {
  48197. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48198. }
  48199. var target = this.getTarget();
  48200. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48201. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48202. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48203. };
  48204. /**
  48205. * Gets the current object class name.
  48206. * @return the class name
  48207. */
  48208. TargetCamera.prototype.getClassName = function () {
  48209. return "TargetCamera";
  48210. };
  48211. __decorate([
  48212. BABYLON.serializeAsVector3()
  48213. ], TargetCamera.prototype, "rotation", void 0);
  48214. __decorate([
  48215. BABYLON.serialize()
  48216. ], TargetCamera.prototype, "speed", void 0);
  48217. __decorate([
  48218. BABYLON.serializeAsMeshReference("lockedTargetId")
  48219. ], TargetCamera.prototype, "lockedTarget", void 0);
  48220. return TargetCamera;
  48221. }(BABYLON.Camera));
  48222. BABYLON.TargetCamera = TargetCamera;
  48223. })(BABYLON || (BABYLON = {}));
  48224. //# sourceMappingURL=babylon.targetCamera.js.map
  48225. var BABYLON;
  48226. (function (BABYLON) {
  48227. /**
  48228. * Manage the mouse inputs to control the movement of a free camera.
  48229. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48230. */
  48231. var FreeCameraMouseInput = /** @class */ (function () {
  48232. /**
  48233. * Manage the mouse inputs to control the movement of a free camera.
  48234. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48235. * @param touchEnabled Defines if touch is enabled or not
  48236. */
  48237. function FreeCameraMouseInput(
  48238. /**
  48239. * Define if touch is enabled in the mouse input
  48240. */
  48241. touchEnabled) {
  48242. if (touchEnabled === void 0) { touchEnabled = true; }
  48243. this.touchEnabled = touchEnabled;
  48244. /**
  48245. * Defines the buttons associated with the input to handle camera move.
  48246. */
  48247. this.buttons = [0, 1, 2];
  48248. /**
  48249. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48250. */
  48251. this.angularSensibility = 2000.0;
  48252. this.previousPosition = null;
  48253. }
  48254. /**
  48255. * Attach the input controls to a specific dom element to get the input from.
  48256. * @param element Defines the element the controls should be listened from
  48257. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48258. */
  48259. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48260. var _this = this;
  48261. var engine = this.camera.getEngine();
  48262. if (!this._pointerInput) {
  48263. this._pointerInput = function (p, s) {
  48264. var evt = p.event;
  48265. if (engine.isInVRExclusivePointerMode) {
  48266. return;
  48267. }
  48268. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48269. return;
  48270. }
  48271. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48272. return;
  48273. }
  48274. var srcElement = (evt.srcElement || evt.target);
  48275. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48276. try {
  48277. srcElement.setPointerCapture(evt.pointerId);
  48278. }
  48279. catch (e) {
  48280. //Nothing to do with the error. Execution will continue.
  48281. }
  48282. _this.previousPosition = {
  48283. x: evt.clientX,
  48284. y: evt.clientY
  48285. };
  48286. if (!noPreventDefault) {
  48287. evt.preventDefault();
  48288. element.focus();
  48289. }
  48290. }
  48291. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48292. try {
  48293. srcElement.releasePointerCapture(evt.pointerId);
  48294. }
  48295. catch (e) {
  48296. //Nothing to do with the error.
  48297. }
  48298. _this.previousPosition = null;
  48299. if (!noPreventDefault) {
  48300. evt.preventDefault();
  48301. }
  48302. }
  48303. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48304. if (!_this.previousPosition || engine.isPointerLock) {
  48305. return;
  48306. }
  48307. var offsetX = evt.clientX - _this.previousPosition.x;
  48308. if (_this.camera.getScene().useRightHandedSystem)
  48309. offsetX *= -1;
  48310. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  48311. offsetX *= -1;
  48312. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48313. var offsetY = evt.clientY - _this.previousPosition.y;
  48314. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48315. _this.previousPosition = {
  48316. x: evt.clientX,
  48317. y: evt.clientY
  48318. };
  48319. if (!noPreventDefault) {
  48320. evt.preventDefault();
  48321. }
  48322. }
  48323. };
  48324. }
  48325. this._onMouseMove = function (evt) {
  48326. if (!engine.isPointerLock) {
  48327. return;
  48328. }
  48329. if (engine.isInVRExclusivePointerMode) {
  48330. return;
  48331. }
  48332. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48333. if (_this.camera.getScene().useRightHandedSystem)
  48334. offsetX *= -1;
  48335. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  48336. offsetX *= -1;
  48337. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48338. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48339. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48340. _this.previousPosition = null;
  48341. if (!noPreventDefault) {
  48342. evt.preventDefault();
  48343. }
  48344. };
  48345. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48346. element.addEventListener("mousemove", this._onMouseMove, false);
  48347. };
  48348. /**
  48349. * Detach the current controls from the specified dom element.
  48350. * @param element Defines the element to stop listening the inputs from
  48351. */
  48352. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48353. if (this._observer && element) {
  48354. this.camera.getScene().onPointerObservable.remove(this._observer);
  48355. if (this._onMouseMove) {
  48356. element.removeEventListener("mousemove", this._onMouseMove);
  48357. }
  48358. this._observer = null;
  48359. this._onMouseMove = null;
  48360. this.previousPosition = null;
  48361. }
  48362. };
  48363. /**
  48364. * Gets the class name of the current intput.
  48365. * @returns the class name
  48366. */
  48367. FreeCameraMouseInput.prototype.getClassName = function () {
  48368. return "FreeCameraMouseInput";
  48369. };
  48370. /**
  48371. * Get the friendly name associated with the input class.
  48372. * @returns the input friendly name
  48373. */
  48374. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48375. return "mouse";
  48376. };
  48377. __decorate([
  48378. BABYLON.serialize()
  48379. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48380. __decorate([
  48381. BABYLON.serialize()
  48382. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48383. return FreeCameraMouseInput;
  48384. }());
  48385. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48386. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48387. })(BABYLON || (BABYLON = {}));
  48388. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48389. var BABYLON;
  48390. (function (BABYLON) {
  48391. /**
  48392. * Manage the keyboard inputs to control the movement of a free camera.
  48393. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48394. */
  48395. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48396. function FreeCameraKeyboardMoveInput() {
  48397. /**
  48398. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48399. */
  48400. this.keysUp = [38];
  48401. /**
  48402. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48403. */
  48404. this.keysDown = [40];
  48405. /**
  48406. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48407. */
  48408. this.keysLeft = [37];
  48409. /**
  48410. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48411. */
  48412. this.keysRight = [39];
  48413. this._keys = new Array();
  48414. }
  48415. /**
  48416. * Attach the input controls to a specific dom element to get the input from.
  48417. * @param element Defines the element the controls should be listened from
  48418. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48419. */
  48420. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48421. var _this = this;
  48422. if (this._onCanvasBlurObserver) {
  48423. return;
  48424. }
  48425. this._scene = this.camera.getScene();
  48426. this._engine = this._scene.getEngine();
  48427. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48428. _this._keys = [];
  48429. });
  48430. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48431. var evt = info.event;
  48432. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48433. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48434. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48435. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48436. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48437. var index = _this._keys.indexOf(evt.keyCode);
  48438. if (index === -1) {
  48439. _this._keys.push(evt.keyCode);
  48440. }
  48441. if (!noPreventDefault) {
  48442. evt.preventDefault();
  48443. }
  48444. }
  48445. }
  48446. else {
  48447. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48448. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48449. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48450. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48451. var index = _this._keys.indexOf(evt.keyCode);
  48452. if (index >= 0) {
  48453. _this._keys.splice(index, 1);
  48454. }
  48455. if (!noPreventDefault) {
  48456. evt.preventDefault();
  48457. }
  48458. }
  48459. }
  48460. });
  48461. };
  48462. /**
  48463. * Detach the current controls from the specified dom element.
  48464. * @param element Defines the element to stop listening the inputs from
  48465. */
  48466. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48467. if (this._scene) {
  48468. if (this._onKeyboardObserver) {
  48469. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48470. }
  48471. if (this._onCanvasBlurObserver) {
  48472. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48473. }
  48474. this._onKeyboardObserver = null;
  48475. this._onCanvasBlurObserver = null;
  48476. }
  48477. this._keys = [];
  48478. };
  48479. /**
  48480. * Update the current camera state depending on the inputs that have been used this frame.
  48481. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48482. */
  48483. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48484. if (this._onKeyboardObserver) {
  48485. var camera = this.camera;
  48486. // Keyboard
  48487. for (var index = 0; index < this._keys.length; index++) {
  48488. var keyCode = this._keys[index];
  48489. var speed = camera._computeLocalCameraSpeed();
  48490. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48491. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48492. }
  48493. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48494. camera._localDirection.copyFromFloats(0, 0, speed);
  48495. }
  48496. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48497. camera._localDirection.copyFromFloats(speed, 0, 0);
  48498. }
  48499. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48500. camera._localDirection.copyFromFloats(0, 0, -speed);
  48501. }
  48502. if (camera.getScene().useRightHandedSystem) {
  48503. camera._localDirection.z *= -1;
  48504. }
  48505. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48506. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48507. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48508. }
  48509. }
  48510. };
  48511. /**
  48512. * Gets the class name of the current intput.
  48513. * @returns the class name
  48514. */
  48515. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48516. return "FreeCameraKeyboardMoveInput";
  48517. };
  48518. /** @hidden */
  48519. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48520. this._keys = [];
  48521. };
  48522. /**
  48523. * Get the friendly name associated with the input class.
  48524. * @returns the input friendly name
  48525. */
  48526. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48527. return "keyboard";
  48528. };
  48529. __decorate([
  48530. BABYLON.serialize()
  48531. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48532. __decorate([
  48533. BABYLON.serialize()
  48534. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48535. __decorate([
  48536. BABYLON.serialize()
  48537. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48538. __decorate([
  48539. BABYLON.serialize()
  48540. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48541. return FreeCameraKeyboardMoveInput;
  48542. }());
  48543. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48544. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48545. })(BABYLON || (BABYLON = {}));
  48546. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48547. var BABYLON;
  48548. (function (BABYLON) {
  48549. /**
  48550. * Default Inputs manager for the FreeCamera.
  48551. * It groups all the default supported inputs for ease of use.
  48552. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48553. */
  48554. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48555. __extends(FreeCameraInputsManager, _super);
  48556. /**
  48557. * Instantiates a new FreeCameraInputsManager.
  48558. * @param camera Defines the camera the inputs belong to
  48559. */
  48560. function FreeCameraInputsManager(camera) {
  48561. return _super.call(this, camera) || this;
  48562. }
  48563. /**
  48564. * Add keyboard input support to the input manager.
  48565. * @returns the current input manager
  48566. */
  48567. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48568. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48569. return this;
  48570. };
  48571. /**
  48572. * Add mouse input support to the input manager.
  48573. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48574. * @returns the current input manager
  48575. */
  48576. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48577. if (touchEnabled === void 0) { touchEnabled = true; }
  48578. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48579. return this;
  48580. };
  48581. /**
  48582. * Add orientation input support to the input manager.
  48583. * @returns the current input manager
  48584. */
  48585. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48586. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48587. return this;
  48588. };
  48589. /**
  48590. * Add touch input support to the input manager.
  48591. * @returns the current input manager
  48592. */
  48593. FreeCameraInputsManager.prototype.addTouch = function () {
  48594. this.add(new BABYLON.FreeCameraTouchInput());
  48595. return this;
  48596. };
  48597. /**
  48598. * Add virtual joystick input support to the input manager.
  48599. * @returns the current input manager
  48600. */
  48601. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48602. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48603. return this;
  48604. };
  48605. return FreeCameraInputsManager;
  48606. }(BABYLON.CameraInputsManager));
  48607. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48608. })(BABYLON || (BABYLON = {}));
  48609. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48610. var BABYLON;
  48611. (function (BABYLON) {
  48612. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48613. // Forcing to use the Universal camera
  48614. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48615. });
  48616. /**
  48617. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48618. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48619. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48620. */
  48621. var FreeCamera = /** @class */ (function (_super) {
  48622. __extends(FreeCamera, _super);
  48623. /**
  48624. * Instantiates a Free Camera.
  48625. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48626. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48627. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48628. * @param name Define the name of the camera in the scene
  48629. * @param position Define the start position of the camera in the scene
  48630. * @param scene Define the scene the camera belongs to
  48631. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48632. */
  48633. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48634. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48635. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48636. /**
  48637. * Define the collision ellipsoid of the camera.
  48638. * This is helpful to simulate a camera body like the player body around the camera
  48639. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48640. */
  48641. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48642. /**
  48643. * Define an offset for the position of the ellipsoid around the camera.
  48644. * This can be helpful to determine the center of the body near the gravity center of the body
  48645. * instead of its head.
  48646. */
  48647. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48648. /**
  48649. * Enable or disable collisions of the camera with the rest of the scene objects.
  48650. */
  48651. _this.checkCollisions = false;
  48652. /**
  48653. * Enable or disable gravity on the camera.
  48654. */
  48655. _this.applyGravity = false;
  48656. _this._needMoveForGravity = false;
  48657. _this._oldPosition = BABYLON.Vector3.Zero();
  48658. _this._diffPosition = BABYLON.Vector3.Zero();
  48659. _this._newPosition = BABYLON.Vector3.Zero();
  48660. // Collisions
  48661. _this._collisionMask = -1;
  48662. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48663. if (collidedMesh === void 0) { collidedMesh = null; }
  48664. //TODO move this to the collision coordinator!
  48665. if (_this.getScene().workerCollisions)
  48666. newPosition.multiplyInPlace(_this._collider._radius);
  48667. var updatePosition = function (newPos) {
  48668. _this._newPosition.copyFrom(newPos);
  48669. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48670. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48671. _this.position.addInPlace(_this._diffPosition);
  48672. if (_this.onCollide && collidedMesh) {
  48673. _this.onCollide(collidedMesh);
  48674. }
  48675. }
  48676. };
  48677. updatePosition(newPosition);
  48678. };
  48679. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48680. _this.inputs.addKeyboard().addMouse();
  48681. return _this;
  48682. }
  48683. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48684. /**
  48685. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48686. * Higher values reduce sensitivity.
  48687. */
  48688. get: function () {
  48689. var mouse = this.inputs.attached["mouse"];
  48690. if (mouse)
  48691. return mouse.angularSensibility;
  48692. return 0;
  48693. },
  48694. /**
  48695. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48696. * Higher values reduce sensitivity.
  48697. */
  48698. set: function (value) {
  48699. var mouse = this.inputs.attached["mouse"];
  48700. if (mouse)
  48701. mouse.angularSensibility = value;
  48702. },
  48703. enumerable: true,
  48704. configurable: true
  48705. });
  48706. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48707. /**
  48708. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48709. */
  48710. get: function () {
  48711. var keyboard = this.inputs.attached["keyboard"];
  48712. if (keyboard)
  48713. return keyboard.keysUp;
  48714. return [];
  48715. },
  48716. set: function (value) {
  48717. var keyboard = this.inputs.attached["keyboard"];
  48718. if (keyboard)
  48719. keyboard.keysUp = value;
  48720. },
  48721. enumerable: true,
  48722. configurable: true
  48723. });
  48724. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48725. /**
  48726. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48727. */
  48728. get: function () {
  48729. var keyboard = this.inputs.attached["keyboard"];
  48730. if (keyboard)
  48731. return keyboard.keysDown;
  48732. return [];
  48733. },
  48734. set: function (value) {
  48735. var keyboard = this.inputs.attached["keyboard"];
  48736. if (keyboard)
  48737. keyboard.keysDown = value;
  48738. },
  48739. enumerable: true,
  48740. configurable: true
  48741. });
  48742. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48743. /**
  48744. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48745. */
  48746. get: function () {
  48747. var keyboard = this.inputs.attached["keyboard"];
  48748. if (keyboard)
  48749. return keyboard.keysLeft;
  48750. return [];
  48751. },
  48752. set: function (value) {
  48753. var keyboard = this.inputs.attached["keyboard"];
  48754. if (keyboard)
  48755. keyboard.keysLeft = value;
  48756. },
  48757. enumerable: true,
  48758. configurable: true
  48759. });
  48760. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48761. /**
  48762. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48763. */
  48764. get: function () {
  48765. var keyboard = this.inputs.attached["keyboard"];
  48766. if (keyboard)
  48767. return keyboard.keysRight;
  48768. return [];
  48769. },
  48770. set: function (value) {
  48771. var keyboard = this.inputs.attached["keyboard"];
  48772. if (keyboard)
  48773. keyboard.keysRight = value;
  48774. },
  48775. enumerable: true,
  48776. configurable: true
  48777. });
  48778. /**
  48779. * Attached controls to the current camera.
  48780. * @param element Defines the element the controls should be listened from
  48781. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48782. */
  48783. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48784. this.inputs.attachElement(element, noPreventDefault);
  48785. };
  48786. /**
  48787. * Detach the current controls from the camera.
  48788. * The camera will stop reacting to inputs.
  48789. * @param element Defines the element to stop listening the inputs from
  48790. */
  48791. FreeCamera.prototype.detachControl = function (element) {
  48792. this.inputs.detachElement(element);
  48793. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48794. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48795. };
  48796. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48797. /**
  48798. * Define a collision mask to limit the list of object the camera can collide with
  48799. */
  48800. get: function () {
  48801. return this._collisionMask;
  48802. },
  48803. set: function (mask) {
  48804. this._collisionMask = !isNaN(mask) ? mask : -1;
  48805. },
  48806. enumerable: true,
  48807. configurable: true
  48808. });
  48809. /** @hidden */
  48810. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48811. var globalPosition;
  48812. if (this.parent) {
  48813. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48814. }
  48815. else {
  48816. globalPosition = this.position;
  48817. }
  48818. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48819. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48820. if (!this._collider) {
  48821. this._collider = new BABYLON.Collider();
  48822. }
  48823. this._collider._radius = this.ellipsoid;
  48824. this._collider.collisionMask = this._collisionMask;
  48825. //no need for clone, as long as gravity is not on.
  48826. var actualDisplacement = displacement;
  48827. //add gravity to the direction to prevent the dual-collision checking
  48828. if (this.applyGravity) {
  48829. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48830. actualDisplacement = displacement.add(this.getScene().gravity);
  48831. }
  48832. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48833. };
  48834. /** @hidden */
  48835. FreeCamera.prototype._checkInputs = function () {
  48836. if (!this._localDirection) {
  48837. this._localDirection = BABYLON.Vector3.Zero();
  48838. this._transformedDirection = BABYLON.Vector3.Zero();
  48839. }
  48840. this.inputs.checkInputs();
  48841. _super.prototype._checkInputs.call(this);
  48842. };
  48843. /** @hidden */
  48844. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48845. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48846. };
  48847. /** @hidden */
  48848. FreeCamera.prototype._updatePosition = function () {
  48849. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48850. this._collideWithWorld(this.cameraDirection);
  48851. }
  48852. else {
  48853. _super.prototype._updatePosition.call(this);
  48854. }
  48855. };
  48856. /**
  48857. * Destroy the camera and release the current resources hold by it.
  48858. */
  48859. FreeCamera.prototype.dispose = function () {
  48860. this.inputs.clear();
  48861. _super.prototype.dispose.call(this);
  48862. };
  48863. /**
  48864. * Gets the current object class name.
  48865. * @return the class name
  48866. */
  48867. FreeCamera.prototype.getClassName = function () {
  48868. return "FreeCamera";
  48869. };
  48870. __decorate([
  48871. BABYLON.serializeAsVector3()
  48872. ], FreeCamera.prototype, "ellipsoid", void 0);
  48873. __decorate([
  48874. BABYLON.serializeAsVector3()
  48875. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48876. __decorate([
  48877. BABYLON.serialize()
  48878. ], FreeCamera.prototype, "checkCollisions", void 0);
  48879. __decorate([
  48880. BABYLON.serialize()
  48881. ], FreeCamera.prototype, "applyGravity", void 0);
  48882. return FreeCamera;
  48883. }(BABYLON.TargetCamera));
  48884. BABYLON.FreeCamera = FreeCamera;
  48885. })(BABYLON || (BABYLON = {}));
  48886. //# sourceMappingURL=babylon.freeCamera.js.map
  48887. var BABYLON;
  48888. (function (BABYLON) {
  48889. /**
  48890. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48891. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48892. */
  48893. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48894. function ArcRotateCameraKeyboardMoveInput() {
  48895. /**
  48896. * Defines the list of key codes associated with the up action (increase alpha)
  48897. */
  48898. this.keysUp = [38];
  48899. /**
  48900. * Defines the list of key codes associated with the down action (decrease alpha)
  48901. */
  48902. this.keysDown = [40];
  48903. /**
  48904. * Defines the list of key codes associated with the left action (increase beta)
  48905. */
  48906. this.keysLeft = [37];
  48907. /**
  48908. * Defines the list of key codes associated with the right action (decrease beta)
  48909. */
  48910. this.keysRight = [39];
  48911. /**
  48912. * Defines the list of key codes associated with the reset action.
  48913. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48914. */
  48915. this.keysReset = [220];
  48916. /**
  48917. * Defines the panning sensibility of the inputs.
  48918. * (How fast is the camera paning)
  48919. */
  48920. this.panningSensibility = 50.0;
  48921. /**
  48922. * Defines the zooming sensibility of the inputs.
  48923. * (How fast is the camera zooming)
  48924. */
  48925. this.zoomingSensibility = 25.0;
  48926. /**
  48927. * Defines wether maintaining the alt key down switch the movement mode from
  48928. * orientation to zoom.
  48929. */
  48930. this.useAltToZoom = true;
  48931. /**
  48932. * Rotation speed of the camera
  48933. */
  48934. this.angularSpeed = 0.01;
  48935. this._keys = new Array();
  48936. }
  48937. /**
  48938. * Attach the input controls to a specific dom element to get the input from.
  48939. * @param element Defines the element the controls should be listened from
  48940. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48941. */
  48942. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48943. var _this = this;
  48944. if (this._onCanvasBlurObserver) {
  48945. return;
  48946. }
  48947. this._scene = this.camera.getScene();
  48948. this._engine = this._scene.getEngine();
  48949. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48950. _this._keys = [];
  48951. });
  48952. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48953. var evt = info.event;
  48954. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48955. _this._ctrlPressed = evt.ctrlKey;
  48956. _this._altPressed = evt.altKey;
  48957. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48958. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48959. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48960. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48961. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48962. var index = _this._keys.indexOf(evt.keyCode);
  48963. if (index === -1) {
  48964. _this._keys.push(evt.keyCode);
  48965. }
  48966. if (evt.preventDefault) {
  48967. if (!noPreventDefault) {
  48968. evt.preventDefault();
  48969. }
  48970. }
  48971. }
  48972. }
  48973. else {
  48974. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48975. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48976. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48977. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48978. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48979. var index = _this._keys.indexOf(evt.keyCode);
  48980. if (index >= 0) {
  48981. _this._keys.splice(index, 1);
  48982. }
  48983. if (evt.preventDefault) {
  48984. if (!noPreventDefault) {
  48985. evt.preventDefault();
  48986. }
  48987. }
  48988. }
  48989. }
  48990. });
  48991. };
  48992. /**
  48993. * Detach the current controls from the specified dom element.
  48994. * @param element Defines the element to stop listening the inputs from
  48995. */
  48996. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48997. if (this._scene) {
  48998. if (this._onKeyboardObserver) {
  48999. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49000. }
  49001. if (this._onCanvasBlurObserver) {
  49002. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49003. }
  49004. this._onKeyboardObserver = null;
  49005. this._onCanvasBlurObserver = null;
  49006. }
  49007. this._keys = [];
  49008. };
  49009. /**
  49010. * Update the current camera state depending on the inputs that have been used this frame.
  49011. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49012. */
  49013. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49014. if (this._onKeyboardObserver) {
  49015. var camera = this.camera;
  49016. for (var index = 0; index < this._keys.length; index++) {
  49017. var keyCode = this._keys[index];
  49018. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49019. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49020. camera.inertialPanningX -= 1 / this.panningSensibility;
  49021. }
  49022. else {
  49023. camera.inertialAlphaOffset -= this.angularSpeed;
  49024. }
  49025. }
  49026. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49027. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49028. camera.inertialPanningY += 1 / this.panningSensibility;
  49029. }
  49030. else if (this._altPressed && this.useAltToZoom) {
  49031. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49032. }
  49033. else {
  49034. camera.inertialBetaOffset -= this.angularSpeed;
  49035. }
  49036. }
  49037. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49038. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49039. camera.inertialPanningX += 1 / this.panningSensibility;
  49040. }
  49041. else {
  49042. camera.inertialAlphaOffset += this.angularSpeed;
  49043. }
  49044. }
  49045. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49046. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49047. camera.inertialPanningY -= 1 / this.panningSensibility;
  49048. }
  49049. else if (this._altPressed && this.useAltToZoom) {
  49050. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49051. }
  49052. else {
  49053. camera.inertialBetaOffset += this.angularSpeed;
  49054. }
  49055. }
  49056. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49057. if (camera.useInputToRestoreState) {
  49058. camera.restoreState();
  49059. }
  49060. }
  49061. }
  49062. }
  49063. };
  49064. /**
  49065. * Gets the class name of the current intput.
  49066. * @returns the class name
  49067. */
  49068. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49069. return "ArcRotateCameraKeyboardMoveInput";
  49070. };
  49071. /**
  49072. * Get the friendly name associated with the input class.
  49073. * @returns the input friendly name
  49074. */
  49075. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49076. return "keyboard";
  49077. };
  49078. __decorate([
  49079. BABYLON.serialize()
  49080. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49081. __decorate([
  49082. BABYLON.serialize()
  49083. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49084. __decorate([
  49085. BABYLON.serialize()
  49086. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49087. __decorate([
  49088. BABYLON.serialize()
  49089. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49090. __decorate([
  49091. BABYLON.serialize()
  49092. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49093. __decorate([
  49094. BABYLON.serialize()
  49095. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49096. __decorate([
  49097. BABYLON.serialize()
  49098. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49099. __decorate([
  49100. BABYLON.serialize()
  49101. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49102. __decorate([
  49103. BABYLON.serialize()
  49104. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49105. return ArcRotateCameraKeyboardMoveInput;
  49106. }());
  49107. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49108. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49109. })(BABYLON || (BABYLON = {}));
  49110. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49111. var BABYLON;
  49112. (function (BABYLON) {
  49113. /**
  49114. * Manage the mouse wheel inputs to control an arc rotate camera.
  49115. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49116. */
  49117. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49118. function ArcRotateCameraMouseWheelInput() {
  49119. /**
  49120. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49121. */
  49122. this.wheelPrecision = 3.0;
  49123. /**
  49124. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49125. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49126. */
  49127. this.wheelDeltaPercentage = 0;
  49128. }
  49129. /**
  49130. * Attach the input controls to a specific dom element to get the input from.
  49131. * @param element Defines the element the controls should be listened from
  49132. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49133. */
  49134. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49135. var _this = this;
  49136. this._wheel = function (p, s) {
  49137. //sanity check - this should be a PointerWheel event.
  49138. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  49139. return;
  49140. var event = p.event;
  49141. var delta = 0;
  49142. if (event.wheelDelta) {
  49143. if (_this.wheelDeltaPercentage) {
  49144. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49145. if (event.wheelDelta > 0) {
  49146. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49147. }
  49148. else {
  49149. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49150. }
  49151. }
  49152. else {
  49153. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49154. }
  49155. }
  49156. else if (event.detail) {
  49157. delta = -event.detail / _this.wheelPrecision;
  49158. }
  49159. if (delta)
  49160. _this.camera.inertialRadiusOffset += delta;
  49161. if (event.preventDefault) {
  49162. if (!noPreventDefault) {
  49163. event.preventDefault();
  49164. }
  49165. }
  49166. };
  49167. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49168. };
  49169. /**
  49170. * Detach the current controls from the specified dom element.
  49171. * @param element Defines the element to stop listening the inputs from
  49172. */
  49173. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49174. if (this._observer && element) {
  49175. this.camera.getScene().onPointerObservable.remove(this._observer);
  49176. this._observer = null;
  49177. this._wheel = null;
  49178. }
  49179. };
  49180. /**
  49181. * Gets the class name of the current intput.
  49182. * @returns the class name
  49183. */
  49184. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49185. return "ArcRotateCameraMouseWheelInput";
  49186. };
  49187. /**
  49188. * Get the friendly name associated with the input class.
  49189. * @returns the input friendly name
  49190. */
  49191. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49192. return "mousewheel";
  49193. };
  49194. __decorate([
  49195. BABYLON.serialize()
  49196. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49197. __decorate([
  49198. BABYLON.serialize()
  49199. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49200. return ArcRotateCameraMouseWheelInput;
  49201. }());
  49202. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49203. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49204. })(BABYLON || (BABYLON = {}));
  49205. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49206. var BABYLON;
  49207. (function (BABYLON) {
  49208. /**
  49209. * Manage the pointers inputs to control an arc rotate camera.
  49210. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49211. */
  49212. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49213. function ArcRotateCameraPointersInput() {
  49214. /**
  49215. * Defines the buttons associated with the input to handle camera move.
  49216. */
  49217. this.buttons = [0, 1, 2];
  49218. /**
  49219. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49220. */
  49221. this.angularSensibilityX = 1000.0;
  49222. /**
  49223. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49224. */
  49225. this.angularSensibilityY = 1000.0;
  49226. /**
  49227. * Defines the pointer pinch precision or how fast is the camera zooming.
  49228. */
  49229. this.pinchPrecision = 12.0;
  49230. /**
  49231. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49232. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49233. */
  49234. this.pinchDeltaPercentage = 0;
  49235. /**
  49236. * Defines the pointer panning sensibility or how fast is the camera moving.
  49237. */
  49238. this.panningSensibility = 1000.0;
  49239. /**
  49240. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49241. */
  49242. this.multiTouchPanning = true;
  49243. /**
  49244. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49245. */
  49246. this.multiTouchPanAndZoom = true;
  49247. /**
  49248. * Revers pinch action direction.
  49249. */
  49250. this.pinchInwards = true;
  49251. this._isPanClick = false;
  49252. }
  49253. /**
  49254. * Attach the input controls to a specific dom element to get the input from.
  49255. * @param element Defines the element the controls should be listened from
  49256. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49257. */
  49258. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49259. var _this = this;
  49260. var engine = this.camera.getEngine();
  49261. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49262. var pointA = null;
  49263. var pointB = null;
  49264. var previousPinchSquaredDistance = 0;
  49265. var initialDistance = 0;
  49266. var twoFingerActivityCount = 0;
  49267. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49268. this._pointerInput = function (p, s) {
  49269. var evt = p.event;
  49270. var isTouch = p.event.pointerType === "touch";
  49271. if (engine.isInVRExclusivePointerMode) {
  49272. return;
  49273. }
  49274. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49275. return;
  49276. }
  49277. var srcElement = (evt.srcElement || evt.target);
  49278. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49279. try {
  49280. srcElement.setPointerCapture(evt.pointerId);
  49281. }
  49282. catch (e) {
  49283. //Nothing to do with the error. Execution will continue.
  49284. }
  49285. // Manage panning with pan button click
  49286. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49287. // manage pointers
  49288. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49289. if (pointA === null) {
  49290. pointA = cacheSoloPointer;
  49291. }
  49292. else if (pointB === null) {
  49293. pointB = cacheSoloPointer;
  49294. }
  49295. if (!noPreventDefault) {
  49296. evt.preventDefault();
  49297. element.focus();
  49298. }
  49299. }
  49300. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49301. if (_this.camera.useInputToRestoreState) {
  49302. _this.camera.restoreState();
  49303. }
  49304. }
  49305. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49306. try {
  49307. srcElement.releasePointerCapture(evt.pointerId);
  49308. }
  49309. catch (e) {
  49310. //Nothing to do with the error.
  49311. }
  49312. cacheSoloPointer = null;
  49313. previousPinchSquaredDistance = 0;
  49314. previousMultiTouchPanPosition.isPaning = false;
  49315. previousMultiTouchPanPosition.isPinching = false;
  49316. twoFingerActivityCount = 0;
  49317. initialDistance = 0;
  49318. if (!isTouch) {
  49319. pointB = null; // Mouse and pen are mono pointer
  49320. }
  49321. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49322. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49323. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49324. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49325. if (engine._badOS) {
  49326. pointA = pointB = null;
  49327. }
  49328. else {
  49329. //only remove the impacted pointer in case of multitouch allowing on most
  49330. //platforms switching from rotate to zoom and pan seamlessly.
  49331. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49332. pointA = pointB;
  49333. pointB = null;
  49334. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49335. }
  49336. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49337. pointB = null;
  49338. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49339. }
  49340. else {
  49341. pointA = pointB = null;
  49342. }
  49343. }
  49344. if (!noPreventDefault) {
  49345. evt.preventDefault();
  49346. }
  49347. }
  49348. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49349. if (!noPreventDefault) {
  49350. evt.preventDefault();
  49351. }
  49352. // One button down
  49353. if (pointA && pointB === null && cacheSoloPointer) {
  49354. if (_this.panningSensibility !== 0 &&
  49355. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49356. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49357. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49358. }
  49359. else {
  49360. var offsetX = evt.clientX - cacheSoloPointer.x;
  49361. var offsetY = evt.clientY - cacheSoloPointer.y;
  49362. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49363. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49364. }
  49365. cacheSoloPointer.x = evt.clientX;
  49366. cacheSoloPointer.y = evt.clientY;
  49367. }
  49368. // Two buttons down: pinch/pan
  49369. else if (pointA && pointB) {
  49370. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49371. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49372. ed.x = evt.clientX;
  49373. ed.y = evt.clientY;
  49374. var direction = _this.pinchInwards ? 1 : -1;
  49375. var distX = pointA.x - pointB.x;
  49376. var distY = pointA.y - pointB.y;
  49377. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49378. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49379. if (previousPinchSquaredDistance === 0) {
  49380. initialDistance = pinchDistance;
  49381. previousPinchSquaredDistance = pinchSquaredDistance;
  49382. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49383. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49384. return;
  49385. }
  49386. if (_this.multiTouchPanAndZoom) {
  49387. if (_this.pinchDeltaPercentage) {
  49388. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49389. }
  49390. else {
  49391. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49392. (_this.pinchPrecision *
  49393. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49394. direction);
  49395. }
  49396. if (_this.panningSensibility !== 0) {
  49397. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49398. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49399. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49400. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49401. previousMultiTouchPanPosition.x = pointersCenterX;
  49402. previousMultiTouchPanPosition.y = pointersCenterY;
  49403. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49404. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49405. }
  49406. }
  49407. else {
  49408. twoFingerActivityCount++;
  49409. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49410. if (_this.pinchDeltaPercentage) {
  49411. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49412. }
  49413. else {
  49414. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49415. (_this.pinchPrecision *
  49416. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49417. direction);
  49418. }
  49419. previousMultiTouchPanPosition.isPaning = false;
  49420. previousMultiTouchPanPosition.isPinching = true;
  49421. }
  49422. else {
  49423. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49424. if (!previousMultiTouchPanPosition.isPaning) {
  49425. previousMultiTouchPanPosition.isPaning = true;
  49426. previousMultiTouchPanPosition.isPinching = false;
  49427. previousMultiTouchPanPosition.x = ed.x;
  49428. previousMultiTouchPanPosition.y = ed.y;
  49429. return;
  49430. }
  49431. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49432. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49433. }
  49434. }
  49435. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49436. previousMultiTouchPanPosition.x = ed.x;
  49437. previousMultiTouchPanPosition.y = ed.y;
  49438. }
  49439. }
  49440. previousPinchSquaredDistance = pinchSquaredDistance;
  49441. }
  49442. }
  49443. };
  49444. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49445. this._onContextMenu = function (evt) {
  49446. evt.preventDefault();
  49447. };
  49448. if (!this.camera._useCtrlForPanning) {
  49449. element.addEventListener("contextmenu", this._onContextMenu, false);
  49450. }
  49451. this._onLostFocus = function () {
  49452. //this._keys = [];
  49453. pointA = pointB = null;
  49454. previousPinchSquaredDistance = 0;
  49455. previousMultiTouchPanPosition.isPaning = false;
  49456. previousMultiTouchPanPosition.isPinching = false;
  49457. twoFingerActivityCount = 0;
  49458. cacheSoloPointer = null;
  49459. initialDistance = 0;
  49460. };
  49461. this._onMouseMove = function (evt) {
  49462. if (!engine.isPointerLock) {
  49463. return;
  49464. }
  49465. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49466. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49467. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49468. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49469. if (!noPreventDefault) {
  49470. evt.preventDefault();
  49471. }
  49472. };
  49473. this._onGestureStart = function (e) {
  49474. if (window.MSGesture === undefined) {
  49475. return;
  49476. }
  49477. if (!_this._MSGestureHandler) {
  49478. _this._MSGestureHandler = new MSGesture();
  49479. _this._MSGestureHandler.target = element;
  49480. }
  49481. _this._MSGestureHandler.addPointer(e.pointerId);
  49482. };
  49483. this._onGesture = function (e) {
  49484. _this.camera.radius *= e.scale;
  49485. if (e.preventDefault) {
  49486. if (!noPreventDefault) {
  49487. e.stopPropagation();
  49488. e.preventDefault();
  49489. }
  49490. }
  49491. };
  49492. element.addEventListener("mousemove", this._onMouseMove, false);
  49493. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49494. element.addEventListener("MSGestureChange", this._onGesture, false);
  49495. BABYLON.Tools.RegisterTopRootEvents([
  49496. { name: "blur", handler: this._onLostFocus }
  49497. ]);
  49498. };
  49499. /**
  49500. * Detach the current controls from the specified dom element.
  49501. * @param element Defines the element to stop listening the inputs from
  49502. */
  49503. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49504. if (this._onLostFocus) {
  49505. BABYLON.Tools.UnregisterTopRootEvents([
  49506. { name: "blur", handler: this._onLostFocus }
  49507. ]);
  49508. }
  49509. if (element && this._observer) {
  49510. this.camera.getScene().onPointerObservable.remove(this._observer);
  49511. this._observer = null;
  49512. if (this._onContextMenu) {
  49513. element.removeEventListener("contextmenu", this._onContextMenu);
  49514. }
  49515. if (this._onMouseMove) {
  49516. element.removeEventListener("mousemove", this._onMouseMove);
  49517. }
  49518. if (this._onGestureStart) {
  49519. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49520. }
  49521. if (this._onGesture) {
  49522. element.removeEventListener("MSGestureChange", this._onGesture);
  49523. }
  49524. this._isPanClick = false;
  49525. this.pinchInwards = true;
  49526. this._onMouseMove = null;
  49527. this._onGestureStart = null;
  49528. this._onGesture = null;
  49529. this._MSGestureHandler = null;
  49530. this._onLostFocus = null;
  49531. this._onContextMenu = null;
  49532. }
  49533. };
  49534. /**
  49535. * Gets the class name of the current intput.
  49536. * @returns the class name
  49537. */
  49538. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49539. return "ArcRotateCameraPointersInput";
  49540. };
  49541. /**
  49542. * Get the friendly name associated with the input class.
  49543. * @returns the input friendly name
  49544. */
  49545. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49546. return "pointers";
  49547. };
  49548. __decorate([
  49549. BABYLON.serialize()
  49550. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49551. __decorate([
  49552. BABYLON.serialize()
  49553. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49554. __decorate([
  49555. BABYLON.serialize()
  49556. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49557. __decorate([
  49558. BABYLON.serialize()
  49559. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49560. __decorate([
  49561. BABYLON.serialize()
  49562. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49563. __decorate([
  49564. BABYLON.serialize()
  49565. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49566. __decorate([
  49567. BABYLON.serialize()
  49568. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49569. __decorate([
  49570. BABYLON.serialize()
  49571. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49572. return ArcRotateCameraPointersInput;
  49573. }());
  49574. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49575. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49576. })(BABYLON || (BABYLON = {}));
  49577. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49578. var BABYLON;
  49579. (function (BABYLON) {
  49580. /**
  49581. * Default Inputs manager for the ArcRotateCamera.
  49582. * It groups all the default supported inputs for ease of use.
  49583. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49584. */
  49585. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49586. __extends(ArcRotateCameraInputsManager, _super);
  49587. /**
  49588. * Instantiates a new ArcRotateCameraInputsManager.
  49589. * @param camera Defines the camera the inputs belong to
  49590. */
  49591. function ArcRotateCameraInputsManager(camera) {
  49592. return _super.call(this, camera) || this;
  49593. }
  49594. /**
  49595. * Add mouse wheel input support to the input manager.
  49596. * @returns the current input manager
  49597. */
  49598. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49599. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49600. return this;
  49601. };
  49602. /**
  49603. * Add pointers input support to the input manager.
  49604. * @returns the current input manager
  49605. */
  49606. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49607. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49608. return this;
  49609. };
  49610. /**
  49611. * Add keyboard input support to the input manager.
  49612. * @returns the current input manager
  49613. */
  49614. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49615. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49616. return this;
  49617. };
  49618. /**
  49619. * Add orientation input support to the input manager.
  49620. * @returns the current input manager
  49621. */
  49622. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49623. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49624. return this;
  49625. };
  49626. return ArcRotateCameraInputsManager;
  49627. }(BABYLON.CameraInputsManager));
  49628. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49629. })(BABYLON || (BABYLON = {}));
  49630. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49631. var BABYLON;
  49632. (function (BABYLON) {
  49633. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49634. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49635. });
  49636. /**
  49637. * This represents an orbital type of camera.
  49638. *
  49639. * 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.
  49640. * 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.
  49641. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49642. */
  49643. var ArcRotateCamera = /** @class */ (function (_super) {
  49644. __extends(ArcRotateCamera, _super);
  49645. /**
  49646. * Instantiates a new ArcRotateCamera in a given scene
  49647. * @param name Defines the name of the camera
  49648. * @param alpha Defines the camera rotation along the logitudinal axis
  49649. * @param beta Defines the camera rotation along the latitudinal axis
  49650. * @param radius Defines the camera distance from its target
  49651. * @param target Defines the camera target
  49652. * @param scene Defines the scene the camera belongs to
  49653. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49654. */
  49655. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49656. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49657. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49658. /**
  49659. * Current inertia value on the longitudinal axis.
  49660. * The bigger this number the longer it will take for the camera to stop.
  49661. */
  49662. _this.inertialAlphaOffset = 0;
  49663. /**
  49664. * Current inertia value on the latitudinal axis.
  49665. * The bigger this number the longer it will take for the camera to stop.
  49666. */
  49667. _this.inertialBetaOffset = 0;
  49668. /**
  49669. * Current inertia value on the radius axis.
  49670. * The bigger this number the longer it will take for the camera to stop.
  49671. */
  49672. _this.inertialRadiusOffset = 0;
  49673. /**
  49674. * Minimum allowed angle on the longitudinal axis.
  49675. * This can help limiting how the Camera is able to move in the scene.
  49676. */
  49677. _this.lowerAlphaLimit = null;
  49678. /**
  49679. * Maximum allowed angle on the longitudinal axis.
  49680. * This can help limiting how the Camera is able to move in the scene.
  49681. */
  49682. _this.upperAlphaLimit = null;
  49683. /**
  49684. * Minimum allowed angle on the latitudinal axis.
  49685. * This can help limiting how the Camera is able to move in the scene.
  49686. */
  49687. _this.lowerBetaLimit = 0.01;
  49688. /**
  49689. * Maximum allowed angle on the latitudinal axis.
  49690. * This can help limiting how the Camera is able to move in the scene.
  49691. */
  49692. _this.upperBetaLimit = Math.PI;
  49693. /**
  49694. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49695. * This can help limiting how the Camera is able to move in the scene.
  49696. */
  49697. _this.lowerRadiusLimit = null;
  49698. /**
  49699. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49700. * This can help limiting how the Camera is able to move in the scene.
  49701. */
  49702. _this.upperRadiusLimit = null;
  49703. /**
  49704. * Defines the current inertia value used during panning of the camera along the X axis.
  49705. */
  49706. _this.inertialPanningX = 0;
  49707. /**
  49708. * Defines the current inertia value used during panning of the camera along the Y axis.
  49709. */
  49710. _this.inertialPanningY = 0;
  49711. /**
  49712. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49713. * Basically if your fingers moves away from more than this distance you will be considered
  49714. * in pinch mode.
  49715. */
  49716. _this.pinchToPanMaxDistance = 20;
  49717. /**
  49718. * Defines the maximum distance the camera can pan.
  49719. * This could help keeping the cammera always in your scene.
  49720. */
  49721. _this.panningDistanceLimit = null;
  49722. /**
  49723. * Defines the target of the camera before paning.
  49724. */
  49725. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49726. /**
  49727. * Defines the value of the inertia used during panning.
  49728. * 0 would mean stop inertia and one would mean no decelleration at all.
  49729. */
  49730. _this.panningInertia = 0.9;
  49731. //-- end properties for backward compatibility for inputs
  49732. /**
  49733. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49734. */
  49735. _this.zoomOnFactor = 1;
  49736. /**
  49737. * Defines a screen offset for the camera position.
  49738. */
  49739. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49740. /**
  49741. * Allows the camera to be completely reversed.
  49742. * If false the camera can not arrive upside down.
  49743. */
  49744. _this.allowUpsideDown = true;
  49745. /**
  49746. * Define if double tap/click is used to restore the previously saved state of the camera.
  49747. */
  49748. _this.useInputToRestoreState = true;
  49749. /** @hidden */
  49750. _this._viewMatrix = new BABYLON.Matrix();
  49751. /**
  49752. * Defines the allowed panning axis.
  49753. */
  49754. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49755. /**
  49756. * Observable triggered when the mesh target has been changed on the camera.
  49757. */
  49758. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49759. /**
  49760. * Defines whether the camera should check collision with the objects oh the scene.
  49761. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49762. */
  49763. _this.checkCollisions = false;
  49764. /**
  49765. * Defines the collision radius of the camera.
  49766. * This simulates a sphere around the camera.
  49767. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49768. */
  49769. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49770. _this._previousPosition = BABYLON.Vector3.Zero();
  49771. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49772. _this._newPosition = BABYLON.Vector3.Zero();
  49773. _this._computationVector = BABYLON.Vector3.Zero();
  49774. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49775. if (collidedMesh === void 0) { collidedMesh = null; }
  49776. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49777. newPosition.multiplyInPlace(_this._collider._radius);
  49778. }
  49779. if (!collidedMesh) {
  49780. _this._previousPosition.copyFrom(_this.position);
  49781. }
  49782. else {
  49783. _this.setPosition(newPosition);
  49784. if (_this.onCollide) {
  49785. _this.onCollide(collidedMesh);
  49786. }
  49787. }
  49788. // Recompute because of constraints
  49789. var cosa = Math.cos(_this.alpha);
  49790. var sina = Math.sin(_this.alpha);
  49791. var cosb = Math.cos(_this.beta);
  49792. var sinb = Math.sin(_this.beta);
  49793. if (sinb === 0) {
  49794. sinb = 0.0001;
  49795. }
  49796. var target = _this._getTargetPosition();
  49797. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49798. target.addToRef(_this._computationVector, _this._newPosition);
  49799. _this.position.copyFrom(_this._newPosition);
  49800. var up = _this.upVector;
  49801. if (_this.allowUpsideDown && _this.beta < 0) {
  49802. up = up.clone();
  49803. up = up.negate();
  49804. }
  49805. _this._computeViewMatrix(_this.position, target, up);
  49806. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49807. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49808. _this._collisionTriggered = false;
  49809. };
  49810. _this._target = BABYLON.Vector3.Zero();
  49811. if (target) {
  49812. _this.setTarget(target);
  49813. }
  49814. _this.alpha = alpha;
  49815. _this.beta = beta;
  49816. _this.radius = radius;
  49817. _this.getViewMatrix();
  49818. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49819. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49820. return _this;
  49821. }
  49822. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49823. /**
  49824. * Defines the target point of the camera.
  49825. * The camera looks towards it form the radius distance.
  49826. */
  49827. get: function () {
  49828. return this._target;
  49829. },
  49830. set: function (value) {
  49831. this.setTarget(value);
  49832. },
  49833. enumerable: true,
  49834. configurable: true
  49835. });
  49836. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49837. //-- begin properties for backward compatibility for inputs
  49838. /**
  49839. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49840. */
  49841. get: function () {
  49842. var pointers = this.inputs.attached["pointers"];
  49843. if (pointers)
  49844. return pointers.angularSensibilityX;
  49845. return 0;
  49846. },
  49847. set: function (value) {
  49848. var pointers = this.inputs.attached["pointers"];
  49849. if (pointers) {
  49850. pointers.angularSensibilityX = value;
  49851. }
  49852. },
  49853. enumerable: true,
  49854. configurable: true
  49855. });
  49856. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49857. /**
  49858. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49859. */
  49860. get: function () {
  49861. var pointers = this.inputs.attached["pointers"];
  49862. if (pointers)
  49863. return pointers.angularSensibilityY;
  49864. return 0;
  49865. },
  49866. set: function (value) {
  49867. var pointers = this.inputs.attached["pointers"];
  49868. if (pointers) {
  49869. pointers.angularSensibilityY = value;
  49870. }
  49871. },
  49872. enumerable: true,
  49873. configurable: true
  49874. });
  49875. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49876. /**
  49877. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49878. */
  49879. get: function () {
  49880. var pointers = this.inputs.attached["pointers"];
  49881. if (pointers)
  49882. return pointers.pinchPrecision;
  49883. return 0;
  49884. },
  49885. set: function (value) {
  49886. var pointers = this.inputs.attached["pointers"];
  49887. if (pointers) {
  49888. pointers.pinchPrecision = value;
  49889. }
  49890. },
  49891. enumerable: true,
  49892. configurable: true
  49893. });
  49894. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49895. /**
  49896. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49897. * It will be used instead of pinchDeltaPrecision if different from 0.
  49898. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49899. */
  49900. get: function () {
  49901. var pointers = this.inputs.attached["pointers"];
  49902. if (pointers)
  49903. return pointers.pinchDeltaPercentage;
  49904. return 0;
  49905. },
  49906. set: function (value) {
  49907. var pointers = this.inputs.attached["pointers"];
  49908. if (pointers) {
  49909. pointers.pinchDeltaPercentage = value;
  49910. }
  49911. },
  49912. enumerable: true,
  49913. configurable: true
  49914. });
  49915. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49916. /**
  49917. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49918. */
  49919. get: function () {
  49920. var pointers = this.inputs.attached["pointers"];
  49921. if (pointers)
  49922. return pointers.panningSensibility;
  49923. return 0;
  49924. },
  49925. set: function (value) {
  49926. var pointers = this.inputs.attached["pointers"];
  49927. if (pointers) {
  49928. pointers.panningSensibility = value;
  49929. }
  49930. },
  49931. enumerable: true,
  49932. configurable: true
  49933. });
  49934. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49935. /**
  49936. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49937. */
  49938. get: function () {
  49939. var keyboard = this.inputs.attached["keyboard"];
  49940. if (keyboard)
  49941. return keyboard.keysUp;
  49942. return [];
  49943. },
  49944. set: function (value) {
  49945. var keyboard = this.inputs.attached["keyboard"];
  49946. if (keyboard)
  49947. keyboard.keysUp = value;
  49948. },
  49949. enumerable: true,
  49950. configurable: true
  49951. });
  49952. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49953. /**
  49954. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49955. */
  49956. get: function () {
  49957. var keyboard = this.inputs.attached["keyboard"];
  49958. if (keyboard)
  49959. return keyboard.keysDown;
  49960. return [];
  49961. },
  49962. set: function (value) {
  49963. var keyboard = this.inputs.attached["keyboard"];
  49964. if (keyboard)
  49965. keyboard.keysDown = value;
  49966. },
  49967. enumerable: true,
  49968. configurable: true
  49969. });
  49970. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49971. /**
  49972. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  49973. */
  49974. get: function () {
  49975. var keyboard = this.inputs.attached["keyboard"];
  49976. if (keyboard)
  49977. return keyboard.keysLeft;
  49978. return [];
  49979. },
  49980. set: function (value) {
  49981. var keyboard = this.inputs.attached["keyboard"];
  49982. if (keyboard)
  49983. keyboard.keysLeft = value;
  49984. },
  49985. enumerable: true,
  49986. configurable: true
  49987. });
  49988. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  49989. /**
  49990. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  49991. */
  49992. get: function () {
  49993. var keyboard = this.inputs.attached["keyboard"];
  49994. if (keyboard)
  49995. return keyboard.keysRight;
  49996. return [];
  49997. },
  49998. set: function (value) {
  49999. var keyboard = this.inputs.attached["keyboard"];
  50000. if (keyboard)
  50001. keyboard.keysRight = value;
  50002. },
  50003. enumerable: true,
  50004. configurable: true
  50005. });
  50006. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  50007. /**
  50008. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50009. */
  50010. get: function () {
  50011. var mousewheel = this.inputs.attached["mousewheel"];
  50012. if (mousewheel)
  50013. return mousewheel.wheelPrecision;
  50014. return 0;
  50015. },
  50016. set: function (value) {
  50017. var mousewheel = this.inputs.attached["mousewheel"];
  50018. if (mousewheel)
  50019. mousewheel.wheelPrecision = value;
  50020. },
  50021. enumerable: true,
  50022. configurable: true
  50023. });
  50024. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50025. /**
  50026. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50027. * It will be used instead of pinchDeltaPrecision if different from 0.
  50028. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50029. */
  50030. get: function () {
  50031. var mousewheel = this.inputs.attached["mousewheel"];
  50032. if (mousewheel)
  50033. return mousewheel.wheelDeltaPercentage;
  50034. return 0;
  50035. },
  50036. set: function (value) {
  50037. var mousewheel = this.inputs.attached["mousewheel"];
  50038. if (mousewheel)
  50039. mousewheel.wheelDeltaPercentage = value;
  50040. },
  50041. enumerable: true,
  50042. configurable: true
  50043. });
  50044. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50045. /**
  50046. * Gets the bouncing behavior of the camera if it has been enabled.
  50047. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50048. */
  50049. get: function () {
  50050. return this._bouncingBehavior;
  50051. },
  50052. enumerable: true,
  50053. configurable: true
  50054. });
  50055. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50056. /**
  50057. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50058. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50059. */
  50060. get: function () {
  50061. return this._bouncingBehavior != null;
  50062. },
  50063. set: function (value) {
  50064. if (value === this.useBouncingBehavior) {
  50065. return;
  50066. }
  50067. if (value) {
  50068. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50069. this.addBehavior(this._bouncingBehavior);
  50070. }
  50071. else if (this._bouncingBehavior) {
  50072. this.removeBehavior(this._bouncingBehavior);
  50073. this._bouncingBehavior = null;
  50074. }
  50075. },
  50076. enumerable: true,
  50077. configurable: true
  50078. });
  50079. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50080. /**
  50081. * Gets the framing behavior of the camera if it has been enabled.
  50082. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50083. */
  50084. get: function () {
  50085. return this._framingBehavior;
  50086. },
  50087. enumerable: true,
  50088. configurable: true
  50089. });
  50090. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50091. /**
  50092. * Defines if the framing behavior of the camera is enabled on the camera.
  50093. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50094. */
  50095. get: function () {
  50096. return this._framingBehavior != null;
  50097. },
  50098. set: function (value) {
  50099. if (value === this.useFramingBehavior) {
  50100. return;
  50101. }
  50102. if (value) {
  50103. this._framingBehavior = new BABYLON.FramingBehavior();
  50104. this.addBehavior(this._framingBehavior);
  50105. }
  50106. else if (this._framingBehavior) {
  50107. this.removeBehavior(this._framingBehavior);
  50108. this._framingBehavior = null;
  50109. }
  50110. },
  50111. enumerable: true,
  50112. configurable: true
  50113. });
  50114. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50115. /**
  50116. * Gets the auto rotation behavior of the camera if it has been enabled.
  50117. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50118. */
  50119. get: function () {
  50120. return this._autoRotationBehavior;
  50121. },
  50122. enumerable: true,
  50123. configurable: true
  50124. });
  50125. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50126. /**
  50127. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50128. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50129. */
  50130. get: function () {
  50131. return this._autoRotationBehavior != null;
  50132. },
  50133. set: function (value) {
  50134. if (value === this.useAutoRotationBehavior) {
  50135. return;
  50136. }
  50137. if (value) {
  50138. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50139. this.addBehavior(this._autoRotationBehavior);
  50140. }
  50141. else if (this._autoRotationBehavior) {
  50142. this.removeBehavior(this._autoRotationBehavior);
  50143. this._autoRotationBehavior = null;
  50144. }
  50145. },
  50146. enumerable: true,
  50147. configurable: true
  50148. });
  50149. // Cache
  50150. /** @hidden */
  50151. ArcRotateCamera.prototype._initCache = function () {
  50152. _super.prototype._initCache.call(this);
  50153. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50154. this._cache.alpha = undefined;
  50155. this._cache.beta = undefined;
  50156. this._cache.radius = undefined;
  50157. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50158. };
  50159. /** @hidden */
  50160. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50161. if (!ignoreParentClass) {
  50162. _super.prototype._updateCache.call(this);
  50163. }
  50164. this._cache._target.copyFrom(this._getTargetPosition());
  50165. this._cache.alpha = this.alpha;
  50166. this._cache.beta = this.beta;
  50167. this._cache.radius = this.radius;
  50168. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50169. };
  50170. ArcRotateCamera.prototype._getTargetPosition = function () {
  50171. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50172. var pos = this._targetHost.getAbsolutePosition();
  50173. if (this._targetBoundingCenter) {
  50174. pos.addToRef(this._targetBoundingCenter, this._target);
  50175. }
  50176. else {
  50177. this._target.copyFrom(pos);
  50178. }
  50179. }
  50180. var lockedTargetPosition = this._getLockedTargetPosition();
  50181. if (lockedTargetPosition) {
  50182. return lockedTargetPosition;
  50183. }
  50184. return this._target;
  50185. };
  50186. /**
  50187. * Stores the current state of the camera (alpha, beta, radius and target)
  50188. * @returns the camera itself
  50189. */
  50190. ArcRotateCamera.prototype.storeState = function () {
  50191. this._storedAlpha = this.alpha;
  50192. this._storedBeta = this.beta;
  50193. this._storedRadius = this.radius;
  50194. this._storedTarget = this._getTargetPosition().clone();
  50195. return _super.prototype.storeState.call(this);
  50196. };
  50197. /**
  50198. * @hidden
  50199. * Restored camera state. You must call storeState() first
  50200. */
  50201. ArcRotateCamera.prototype._restoreStateValues = function () {
  50202. if (!_super.prototype._restoreStateValues.call(this)) {
  50203. return false;
  50204. }
  50205. this.alpha = this._storedAlpha;
  50206. this.beta = this._storedBeta;
  50207. this.radius = this._storedRadius;
  50208. this.setTarget(this._storedTarget.clone());
  50209. this.inertialAlphaOffset = 0;
  50210. this.inertialBetaOffset = 0;
  50211. this.inertialRadiusOffset = 0;
  50212. this.inertialPanningX = 0;
  50213. this.inertialPanningY = 0;
  50214. return true;
  50215. };
  50216. // Synchronized
  50217. /** @hidden */
  50218. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50219. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  50220. return false;
  50221. return this._cache._target.equals(this._getTargetPosition())
  50222. && this._cache.alpha === this.alpha
  50223. && this._cache.beta === this.beta
  50224. && this._cache.radius === this.radius
  50225. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50226. };
  50227. /**
  50228. * Attached controls to the current camera.
  50229. * @param element Defines the element the controls should be listened from
  50230. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50231. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50232. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50233. */
  50234. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50235. var _this = this;
  50236. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50237. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50238. this._useCtrlForPanning = useCtrlForPanning;
  50239. this._panningMouseButton = panningMouseButton;
  50240. this.inputs.attachElement(element, noPreventDefault);
  50241. this._reset = function () {
  50242. _this.inertialAlphaOffset = 0;
  50243. _this.inertialBetaOffset = 0;
  50244. _this.inertialRadiusOffset = 0;
  50245. _this.inertialPanningX = 0;
  50246. _this.inertialPanningY = 0;
  50247. };
  50248. };
  50249. /**
  50250. * Detach the current controls from the camera.
  50251. * The camera will stop reacting to inputs.
  50252. * @param element Defines the element to stop listening the inputs from
  50253. */
  50254. ArcRotateCamera.prototype.detachControl = function (element) {
  50255. this.inputs.detachElement(element);
  50256. if (this._reset) {
  50257. this._reset();
  50258. }
  50259. };
  50260. /** @hidden */
  50261. ArcRotateCamera.prototype._checkInputs = function () {
  50262. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50263. if (this._collisionTriggered) {
  50264. return;
  50265. }
  50266. this.inputs.checkInputs();
  50267. // Inertia
  50268. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50269. var inertialAlphaOffset = this.inertialAlphaOffset;
  50270. if (this.beta <= 0)
  50271. inertialAlphaOffset *= -1;
  50272. if (this.getScene().useRightHandedSystem)
  50273. inertialAlphaOffset *= -1;
  50274. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  50275. inertialAlphaOffset *= -1;
  50276. this.alpha += inertialAlphaOffset;
  50277. this.beta += this.inertialBetaOffset;
  50278. this.radius -= this.inertialRadiusOffset;
  50279. this.inertialAlphaOffset *= this.inertia;
  50280. this.inertialBetaOffset *= this.inertia;
  50281. this.inertialRadiusOffset *= this.inertia;
  50282. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  50283. this.inertialAlphaOffset = 0;
  50284. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  50285. this.inertialBetaOffset = 0;
  50286. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  50287. this.inertialRadiusOffset = 0;
  50288. }
  50289. // Panning inertia
  50290. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50291. if (!this._localDirection) {
  50292. this._localDirection = BABYLON.Vector3.Zero();
  50293. this._transformedDirection = BABYLON.Vector3.Zero();
  50294. }
  50295. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50296. this._localDirection.multiplyInPlace(this.panningAxis);
  50297. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50298. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50299. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50300. if (!this.panningAxis.y) {
  50301. this._transformedDirection.y = 0;
  50302. }
  50303. if (!this._targetHost) {
  50304. if (this.panningDistanceLimit) {
  50305. this._transformedDirection.addInPlace(this._target);
  50306. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50307. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50308. this._target.copyFrom(this._transformedDirection);
  50309. }
  50310. }
  50311. else {
  50312. this._target.addInPlace(this._transformedDirection);
  50313. }
  50314. }
  50315. this.inertialPanningX *= this.panningInertia;
  50316. this.inertialPanningY *= this.panningInertia;
  50317. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  50318. this.inertialPanningX = 0;
  50319. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  50320. this.inertialPanningY = 0;
  50321. }
  50322. // Limits
  50323. this._checkLimits();
  50324. _super.prototype._checkInputs.call(this);
  50325. };
  50326. ArcRotateCamera.prototype._checkLimits = function () {
  50327. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50328. if (this.allowUpsideDown && this.beta > Math.PI) {
  50329. this.beta = this.beta - (2 * Math.PI);
  50330. }
  50331. }
  50332. else {
  50333. if (this.beta < this.lowerBetaLimit) {
  50334. this.beta = this.lowerBetaLimit;
  50335. }
  50336. }
  50337. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50338. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50339. this.beta = this.beta + (2 * Math.PI);
  50340. }
  50341. }
  50342. else {
  50343. if (this.beta > this.upperBetaLimit) {
  50344. this.beta = this.upperBetaLimit;
  50345. }
  50346. }
  50347. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50348. this.alpha = this.lowerAlphaLimit;
  50349. }
  50350. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50351. this.alpha = this.upperAlphaLimit;
  50352. }
  50353. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50354. this.radius = this.lowerRadiusLimit;
  50355. }
  50356. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50357. this.radius = this.upperRadiusLimit;
  50358. }
  50359. };
  50360. /**
  50361. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50362. */
  50363. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50364. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50365. this.radius = this._computationVector.length();
  50366. if (this.radius === 0) {
  50367. this.radius = 0.0001; // Just to avoid division by zero
  50368. }
  50369. // Alpha
  50370. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50371. if (this._computationVector.z < 0) {
  50372. this.alpha = 2 * Math.PI - this.alpha;
  50373. }
  50374. // Beta
  50375. this.beta = Math.acos(this._computationVector.y / this.radius);
  50376. this._checkLimits();
  50377. };
  50378. /**
  50379. * Use a position to define the current camera related information like aplha, beta and radius
  50380. * @param position Defines the position to set the camera at
  50381. */
  50382. ArcRotateCamera.prototype.setPosition = function (position) {
  50383. if (this.position.equals(position)) {
  50384. return;
  50385. }
  50386. this.position.copyFrom(position);
  50387. this.rebuildAnglesAndRadius();
  50388. };
  50389. /**
  50390. * Defines the target the camera should look at.
  50391. * This will automatically adapt alpha beta and radius to fit within the new target.
  50392. * @param target Defines the new target as a Vector or a mesh
  50393. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50394. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50395. */
  50396. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50397. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50398. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50399. if (target.getBoundingInfo) {
  50400. if (toBoundingCenter) {
  50401. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50402. }
  50403. else {
  50404. this._targetBoundingCenter = null;
  50405. }
  50406. this._targetHost = target;
  50407. this._target = this._getTargetPosition();
  50408. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50409. }
  50410. else {
  50411. var newTarget = target;
  50412. var currentTarget = this._getTargetPosition();
  50413. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50414. return;
  50415. }
  50416. this._targetHost = null;
  50417. this._target = newTarget;
  50418. this._targetBoundingCenter = null;
  50419. this.onMeshTargetChangedObservable.notifyObservers(null);
  50420. }
  50421. this.rebuildAnglesAndRadius();
  50422. };
  50423. /** @hidden */
  50424. ArcRotateCamera.prototype._getViewMatrix = function () {
  50425. // Compute
  50426. var cosa = Math.cos(this.alpha);
  50427. var sina = Math.sin(this.alpha);
  50428. var cosb = Math.cos(this.beta);
  50429. var sinb = Math.sin(this.beta);
  50430. if (sinb === 0) {
  50431. sinb = 0.0001;
  50432. }
  50433. var target = this._getTargetPosition();
  50434. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50435. target.addToRef(this._computationVector, this._newPosition);
  50436. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50437. if (!this._collider) {
  50438. this._collider = new BABYLON.Collider();
  50439. }
  50440. this._collider._radius = this.collisionRadius;
  50441. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50442. this._collisionTriggered = true;
  50443. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50444. }
  50445. else {
  50446. this.position.copyFrom(this._newPosition);
  50447. var up = this.upVector;
  50448. if (this.allowUpsideDown && sinb < 0) {
  50449. up = up.clone();
  50450. up = up.negate();
  50451. }
  50452. this._computeViewMatrix(this.position, target, up);
  50453. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50454. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50455. }
  50456. this._currentTarget = target;
  50457. return this._viewMatrix;
  50458. };
  50459. /**
  50460. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50461. * @param meshes Defines the mesh to zoom on
  50462. * @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)
  50463. */
  50464. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50465. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50466. meshes = meshes || this.getScene().meshes;
  50467. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50468. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50469. this.radius = distance * this.zoomOnFactor;
  50470. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50471. };
  50472. /**
  50473. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50474. * The target will be changed but the radius
  50475. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50476. * @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)
  50477. */
  50478. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50479. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50480. var meshesOrMinMaxVector;
  50481. var distance;
  50482. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50483. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50484. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50485. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50486. }
  50487. else { //minMaxVector and distance
  50488. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50489. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50490. distance = minMaxVectorAndDistance.distance;
  50491. }
  50492. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50493. if (!doNotUpdateMaxZ) {
  50494. this.maxZ = distance * 2;
  50495. }
  50496. };
  50497. /**
  50498. * @override
  50499. * Override Camera.createRigCamera
  50500. */
  50501. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50502. var alphaShift = 0;
  50503. switch (this.cameraRigMode) {
  50504. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50505. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50506. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50507. case BABYLON.Camera.RIG_MODE_VR:
  50508. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50509. break;
  50510. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50511. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50512. break;
  50513. }
  50514. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50515. rigCam._cameraRigParams = {};
  50516. return rigCam;
  50517. };
  50518. /**
  50519. * @hidden
  50520. * @override
  50521. * Override Camera._updateRigCameras
  50522. */
  50523. ArcRotateCamera.prototype._updateRigCameras = function () {
  50524. var camLeft = this._rigCameras[0];
  50525. var camRight = this._rigCameras[1];
  50526. camLeft.beta = camRight.beta = this.beta;
  50527. camLeft.radius = camRight.radius = this.radius;
  50528. switch (this.cameraRigMode) {
  50529. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50530. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50531. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50532. case BABYLON.Camera.RIG_MODE_VR:
  50533. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50534. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50535. break;
  50536. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50537. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50538. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50539. break;
  50540. }
  50541. _super.prototype._updateRigCameras.call(this);
  50542. };
  50543. /**
  50544. * Destroy the camera and release the current resources hold by it.
  50545. */
  50546. ArcRotateCamera.prototype.dispose = function () {
  50547. this.inputs.clear();
  50548. _super.prototype.dispose.call(this);
  50549. };
  50550. /**
  50551. * Gets the current object class name.
  50552. * @return the class name
  50553. */
  50554. ArcRotateCamera.prototype.getClassName = function () {
  50555. return "ArcRotateCamera";
  50556. };
  50557. __decorate([
  50558. BABYLON.serialize()
  50559. ], ArcRotateCamera.prototype, "alpha", void 0);
  50560. __decorate([
  50561. BABYLON.serialize()
  50562. ], ArcRotateCamera.prototype, "beta", void 0);
  50563. __decorate([
  50564. BABYLON.serialize()
  50565. ], ArcRotateCamera.prototype, "radius", void 0);
  50566. __decorate([
  50567. BABYLON.serializeAsVector3("target")
  50568. ], ArcRotateCamera.prototype, "_target", void 0);
  50569. __decorate([
  50570. BABYLON.serialize()
  50571. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50572. __decorate([
  50573. BABYLON.serialize()
  50574. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50575. __decorate([
  50576. BABYLON.serialize()
  50577. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50578. __decorate([
  50579. BABYLON.serialize()
  50580. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50581. __decorate([
  50582. BABYLON.serialize()
  50583. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50584. __decorate([
  50585. BABYLON.serialize()
  50586. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50587. __decorate([
  50588. BABYLON.serialize()
  50589. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50590. __decorate([
  50591. BABYLON.serialize()
  50592. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50593. __decorate([
  50594. BABYLON.serialize()
  50595. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50596. __decorate([
  50597. BABYLON.serialize()
  50598. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50599. __decorate([
  50600. BABYLON.serialize()
  50601. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50602. __decorate([
  50603. BABYLON.serialize()
  50604. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50605. __decorate([
  50606. BABYLON.serialize()
  50607. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50608. __decorate([
  50609. BABYLON.serializeAsVector3()
  50610. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50611. __decorate([
  50612. BABYLON.serialize()
  50613. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50614. __decorate([
  50615. BABYLON.serialize()
  50616. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50617. __decorate([
  50618. BABYLON.serialize()
  50619. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50620. __decorate([
  50621. BABYLON.serialize()
  50622. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50623. __decorate([
  50624. BABYLON.serialize()
  50625. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50626. return ArcRotateCamera;
  50627. }(BABYLON.TargetCamera));
  50628. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50629. })(BABYLON || (BABYLON = {}));
  50630. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50631. var BABYLON;
  50632. (function (BABYLON) {
  50633. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50634. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50635. });
  50636. /**
  50637. * The HemisphericLight simulates the ambient environment light,
  50638. * so the passed direction is the light reflection direction, not the incoming direction.
  50639. */
  50640. var HemisphericLight = /** @class */ (function (_super) {
  50641. __extends(HemisphericLight, _super);
  50642. /**
  50643. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50644. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50645. * The HemisphericLight can't cast shadows.
  50646. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50647. * @param name The friendly name of the light
  50648. * @param direction The direction of the light reflection
  50649. * @param scene The scene the light belongs to
  50650. */
  50651. function HemisphericLight(name, direction, scene) {
  50652. var _this = _super.call(this, name, scene) || this;
  50653. /**
  50654. * The groundColor is the light in the opposite direction to the one specified during creation.
  50655. * 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.
  50656. */
  50657. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50658. _this.direction = direction || BABYLON.Vector3.Up();
  50659. return _this;
  50660. }
  50661. HemisphericLight.prototype._buildUniformLayout = function () {
  50662. this._uniformBuffer.addUniform("vLightData", 4);
  50663. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50664. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50665. this._uniformBuffer.addUniform("vLightGround", 3);
  50666. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50667. this._uniformBuffer.addUniform("depthValues", 2);
  50668. this._uniformBuffer.create();
  50669. };
  50670. /**
  50671. * Returns the string "HemisphericLight".
  50672. * @return The class name
  50673. */
  50674. HemisphericLight.prototype.getClassName = function () {
  50675. return "HemisphericLight";
  50676. };
  50677. /**
  50678. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50679. * Returns the updated direction.
  50680. * @param target The target the direction should point to
  50681. * @return The computed direction
  50682. */
  50683. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50684. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50685. return this.direction;
  50686. };
  50687. /**
  50688. * Returns the shadow generator associated to the light.
  50689. * @returns Always null for hemispheric lights because it does not support shadows.
  50690. */
  50691. HemisphericLight.prototype.getShadowGenerator = function () {
  50692. return null;
  50693. };
  50694. /**
  50695. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50696. * @param effect The effect to update
  50697. * @param lightIndex The index of the light in the effect to update
  50698. * @returns The hemispheric light
  50699. */
  50700. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50701. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50702. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50703. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50704. return this;
  50705. };
  50706. /**
  50707. * Computes the world matrix of the node
  50708. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50709. * @param useWasUpdatedFlag defines a reserved property
  50710. * @returns the world matrix
  50711. */
  50712. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50713. if (!this._worldMatrix) {
  50714. this._worldMatrix = BABYLON.Matrix.Identity();
  50715. }
  50716. return this._worldMatrix;
  50717. };
  50718. /**
  50719. * Returns the integer 3.
  50720. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50721. */
  50722. HemisphericLight.prototype.getTypeID = function () {
  50723. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50724. };
  50725. /**
  50726. * Prepares the list of defines specific to the light type.
  50727. * @param defines the list of defines
  50728. * @param lightIndex defines the index of the light for the effect
  50729. */
  50730. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50731. defines["HEMILIGHT" + lightIndex] = true;
  50732. };
  50733. __decorate([
  50734. BABYLON.serializeAsColor3()
  50735. ], HemisphericLight.prototype, "groundColor", void 0);
  50736. __decorate([
  50737. BABYLON.serializeAsVector3()
  50738. ], HemisphericLight.prototype, "direction", void 0);
  50739. return HemisphericLight;
  50740. }(BABYLON.Light));
  50741. BABYLON.HemisphericLight = HemisphericLight;
  50742. })(BABYLON || (BABYLON = {}));
  50743. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50744. var BABYLON;
  50745. (function (BABYLON) {
  50746. /**
  50747. * Base implementation IShadowLight
  50748. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50749. */
  50750. var ShadowLight = /** @class */ (function (_super) {
  50751. __extends(ShadowLight, _super);
  50752. function ShadowLight() {
  50753. var _this = _super !== null && _super.apply(this, arguments) || this;
  50754. _this._needProjectionMatrixCompute = true;
  50755. return _this;
  50756. }
  50757. ShadowLight.prototype._setPosition = function (value) {
  50758. this._position = value;
  50759. };
  50760. Object.defineProperty(ShadowLight.prototype, "position", {
  50761. /**
  50762. * Sets the position the shadow will be casted from. Also use as the light position for both
  50763. * point and spot lights.
  50764. */
  50765. get: function () {
  50766. return this._position;
  50767. },
  50768. /**
  50769. * Sets the position the shadow will be casted from. Also use as the light position for both
  50770. * point and spot lights.
  50771. */
  50772. set: function (value) {
  50773. this._setPosition(value);
  50774. },
  50775. enumerable: true,
  50776. configurable: true
  50777. });
  50778. ShadowLight.prototype._setDirection = function (value) {
  50779. this._direction = value;
  50780. };
  50781. Object.defineProperty(ShadowLight.prototype, "direction", {
  50782. /**
  50783. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50784. * Also use as the light direction on spot and directional lights.
  50785. */
  50786. get: function () {
  50787. return this._direction;
  50788. },
  50789. /**
  50790. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50791. * Also use as the light direction on spot and directional lights.
  50792. */
  50793. set: function (value) {
  50794. this._setDirection(value);
  50795. },
  50796. enumerable: true,
  50797. configurable: true
  50798. });
  50799. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50800. /**
  50801. * Gets the shadow projection clipping minimum z value.
  50802. */
  50803. get: function () {
  50804. return this._shadowMinZ;
  50805. },
  50806. /**
  50807. * Sets the shadow projection clipping minimum z value.
  50808. */
  50809. set: function (value) {
  50810. this._shadowMinZ = value;
  50811. this.forceProjectionMatrixCompute();
  50812. },
  50813. enumerable: true,
  50814. configurable: true
  50815. });
  50816. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50817. /**
  50818. * Sets the shadow projection clipping maximum z value.
  50819. */
  50820. get: function () {
  50821. return this._shadowMaxZ;
  50822. },
  50823. /**
  50824. * Gets the shadow projection clipping maximum z value.
  50825. */
  50826. set: function (value) {
  50827. this._shadowMaxZ = value;
  50828. this.forceProjectionMatrixCompute();
  50829. },
  50830. enumerable: true,
  50831. configurable: true
  50832. });
  50833. /**
  50834. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50835. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50836. */
  50837. ShadowLight.prototype.computeTransformedInformation = function () {
  50838. if (this.parent && this.parent.getWorldMatrix) {
  50839. if (!this.transformedPosition) {
  50840. this.transformedPosition = BABYLON.Vector3.Zero();
  50841. }
  50842. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50843. // In case the direction is present.
  50844. if (this.direction) {
  50845. if (!this.transformedDirection) {
  50846. this.transformedDirection = BABYLON.Vector3.Zero();
  50847. }
  50848. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50849. }
  50850. return true;
  50851. }
  50852. return false;
  50853. };
  50854. /**
  50855. * Return the depth scale used for the shadow map.
  50856. * @returns the depth scale.
  50857. */
  50858. ShadowLight.prototype.getDepthScale = function () {
  50859. return 50.0;
  50860. };
  50861. /**
  50862. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50863. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50864. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50865. */
  50866. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50867. return this.transformedDirection ? this.transformedDirection : this.direction;
  50868. };
  50869. /**
  50870. * Returns the ShadowLight absolute position in the World.
  50871. * @returns the position vector in world space
  50872. */
  50873. ShadowLight.prototype.getAbsolutePosition = function () {
  50874. return this.transformedPosition ? this.transformedPosition : this.position;
  50875. };
  50876. /**
  50877. * Sets the ShadowLight direction toward the passed target.
  50878. * @param target The point tot target in local space
  50879. * @returns the updated ShadowLight direction
  50880. */
  50881. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50882. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50883. return this.direction;
  50884. };
  50885. /**
  50886. * Returns the light rotation in euler definition.
  50887. * @returns the x y z rotation in local space.
  50888. */
  50889. ShadowLight.prototype.getRotation = function () {
  50890. this.direction.normalize();
  50891. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50892. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50893. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50894. };
  50895. /**
  50896. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50897. * @returns true if a cube texture needs to be use
  50898. */
  50899. ShadowLight.prototype.needCube = function () {
  50900. return false;
  50901. };
  50902. /**
  50903. * Detects if the projection matrix requires to be recomputed this frame.
  50904. * @returns true if it requires to be recomputed otherwise, false.
  50905. */
  50906. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50907. return this._needProjectionMatrixCompute;
  50908. };
  50909. /**
  50910. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50911. */
  50912. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50913. this._needProjectionMatrixCompute = true;
  50914. };
  50915. /** @hidden */
  50916. ShadowLight.prototype._initCache = function () {
  50917. _super.prototype._initCache.call(this);
  50918. this._cache.position = BABYLON.Vector3.Zero();
  50919. };
  50920. /** @hidden */
  50921. ShadowLight.prototype._isSynchronized = function () {
  50922. if (!this._cache.position.equals(this.position))
  50923. return false;
  50924. return true;
  50925. };
  50926. /**
  50927. * Computes the world matrix of the node
  50928. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50929. * @returns the world matrix
  50930. */
  50931. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50932. if (!force && this.isSynchronized()) {
  50933. this._currentRenderId = this.getScene().getRenderId();
  50934. return this._worldMatrix;
  50935. }
  50936. this._updateCache();
  50937. this._cache.position.copyFrom(this.position);
  50938. if (!this._worldMatrix) {
  50939. this._worldMatrix = BABYLON.Matrix.Identity();
  50940. }
  50941. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50942. if (this.parent && this.parent.getWorldMatrix) {
  50943. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50944. this._markSyncedWithParent();
  50945. }
  50946. // Cache the determinant
  50947. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50948. return this._worldMatrix;
  50949. };
  50950. /**
  50951. * Gets the minZ used for shadow according to both the scene and the light.
  50952. * @param activeCamera The camera we are returning the min for
  50953. * @returns the depth min z
  50954. */
  50955. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50956. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50957. };
  50958. /**
  50959. * Gets the maxZ used for shadow according to both the scene and the light.
  50960. * @param activeCamera The camera we are returning the max for
  50961. * @returns the depth max z
  50962. */
  50963. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50964. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50965. };
  50966. /**
  50967. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50968. * @param matrix The materix to updated with the projection information
  50969. * @param viewMatrix The transform matrix of the light
  50970. * @param renderList The list of mesh to render in the map
  50971. * @returns The current light
  50972. */
  50973. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50974. if (this.customProjectionMatrixBuilder) {
  50975. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  50976. }
  50977. else {
  50978. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  50979. }
  50980. return this;
  50981. };
  50982. __decorate([
  50983. BABYLON.serializeAsVector3()
  50984. ], ShadowLight.prototype, "position", null);
  50985. __decorate([
  50986. BABYLON.serializeAsVector3()
  50987. ], ShadowLight.prototype, "direction", null);
  50988. __decorate([
  50989. BABYLON.serialize()
  50990. ], ShadowLight.prototype, "shadowMinZ", null);
  50991. __decorate([
  50992. BABYLON.serialize()
  50993. ], ShadowLight.prototype, "shadowMaxZ", null);
  50994. return ShadowLight;
  50995. }(BABYLON.Light));
  50996. BABYLON.ShadowLight = ShadowLight;
  50997. })(BABYLON || (BABYLON = {}));
  50998. //# sourceMappingURL=babylon.shadowLight.js.map
  50999. var BABYLON;
  51000. (function (BABYLON) {
  51001. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  51002. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  51003. });
  51004. /**
  51005. * A point light is a light defined by an unique point in world space.
  51006. * The light is emitted in every direction from this point.
  51007. * A good example of a point light is a standard light bulb.
  51008. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51009. */
  51010. var PointLight = /** @class */ (function (_super) {
  51011. __extends(PointLight, _super);
  51012. /**
  51013. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  51014. * A PointLight emits the light in every direction.
  51015. * It can cast shadows.
  51016. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  51017. * ```javascript
  51018. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  51019. * ```
  51020. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51021. * @param name The light friendly name
  51022. * @param position The position of the point light in the scene
  51023. * @param scene The scene the lights belongs to
  51024. */
  51025. function PointLight(name, position, scene) {
  51026. var _this = _super.call(this, name, scene) || this;
  51027. _this._shadowAngle = Math.PI / 2;
  51028. _this.position = position;
  51029. return _this;
  51030. }
  51031. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51032. /**
  51033. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51034. * This specifies what angle the shadow will use to be created.
  51035. *
  51036. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51037. */
  51038. get: function () {
  51039. return this._shadowAngle;
  51040. },
  51041. /**
  51042. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51043. * This specifies what angle the shadow will use to be created.
  51044. *
  51045. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51046. */
  51047. set: function (value) {
  51048. this._shadowAngle = value;
  51049. this.forceProjectionMatrixCompute();
  51050. },
  51051. enumerable: true,
  51052. configurable: true
  51053. });
  51054. Object.defineProperty(PointLight.prototype, "direction", {
  51055. /**
  51056. * Gets the direction if it has been set.
  51057. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51058. */
  51059. get: function () {
  51060. return this._direction;
  51061. },
  51062. /**
  51063. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51064. */
  51065. set: function (value) {
  51066. var previousNeedCube = this.needCube();
  51067. this._direction = value;
  51068. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51069. this._shadowGenerator.recreateShadowMap();
  51070. }
  51071. },
  51072. enumerable: true,
  51073. configurable: true
  51074. });
  51075. /**
  51076. * Returns the string "PointLight"
  51077. * @returns the class name
  51078. */
  51079. PointLight.prototype.getClassName = function () {
  51080. return "PointLight";
  51081. };
  51082. /**
  51083. * Returns the integer 0.
  51084. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51085. */
  51086. PointLight.prototype.getTypeID = function () {
  51087. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51088. };
  51089. /**
  51090. * Specifies wether or not the shadowmap should be a cube texture.
  51091. * @returns true if the shadowmap needs to be a cube texture.
  51092. */
  51093. PointLight.prototype.needCube = function () {
  51094. return !this.direction;
  51095. };
  51096. /**
  51097. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51098. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51099. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51100. */
  51101. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51102. if (this.direction) {
  51103. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51104. }
  51105. else {
  51106. switch (faceIndex) {
  51107. case 0:
  51108. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51109. case 1:
  51110. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51111. case 2:
  51112. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51113. case 3:
  51114. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51115. case 4:
  51116. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51117. case 5:
  51118. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51119. }
  51120. }
  51121. return BABYLON.Vector3.Zero();
  51122. };
  51123. /**
  51124. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51125. * - fov = PI / 2
  51126. * - aspect ratio : 1.0
  51127. * - z-near and far equal to the active camera minZ and maxZ.
  51128. * Returns the PointLight.
  51129. */
  51130. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51131. var activeCamera = this.getScene().activeCamera;
  51132. if (!activeCamera) {
  51133. return;
  51134. }
  51135. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51136. };
  51137. PointLight.prototype._buildUniformLayout = function () {
  51138. this._uniformBuffer.addUniform("vLightData", 4);
  51139. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51140. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51141. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51142. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51143. this._uniformBuffer.addUniform("depthValues", 2);
  51144. this._uniformBuffer.create();
  51145. };
  51146. /**
  51147. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51148. * @param effect The effect to update
  51149. * @param lightIndex The index of the light in the effect to update
  51150. * @returns The point light
  51151. */
  51152. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51153. if (this.computeTransformedInformation()) {
  51154. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51155. }
  51156. else {
  51157. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51158. }
  51159. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51160. return this;
  51161. };
  51162. /**
  51163. * Prepares the list of defines specific to the light type.
  51164. * @param defines the list of defines
  51165. * @param lightIndex defines the index of the light for the effect
  51166. */
  51167. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51168. defines["POINTLIGHT" + lightIndex] = true;
  51169. };
  51170. __decorate([
  51171. BABYLON.serialize()
  51172. ], PointLight.prototype, "shadowAngle", null);
  51173. return PointLight;
  51174. }(BABYLON.ShadowLight));
  51175. BABYLON.PointLight = PointLight;
  51176. })(BABYLON || (BABYLON = {}));
  51177. //# sourceMappingURL=babylon.pointLight.js.map
  51178. var BABYLON;
  51179. (function (BABYLON) {
  51180. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51181. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51182. });
  51183. /**
  51184. * A directional light is defined by a direction (what a surprise!).
  51185. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51186. * 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.
  51187. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51188. */
  51189. var DirectionalLight = /** @class */ (function (_super) {
  51190. __extends(DirectionalLight, _super);
  51191. /**
  51192. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51193. * The directional light is emitted from everywhere in the given direction.
  51194. * It can cast shadows.
  51195. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51196. * @param name The friendly name of the light
  51197. * @param direction The direction of the light
  51198. * @param scene The scene the light belongs to
  51199. */
  51200. function DirectionalLight(name, direction, scene) {
  51201. var _this = _super.call(this, name, scene) || this;
  51202. _this._shadowFrustumSize = 0;
  51203. _this._shadowOrthoScale = 0.1;
  51204. /**
  51205. * Automatically compute the projection matrix to best fit (including all the casters)
  51206. * on each frame.
  51207. */
  51208. _this.autoUpdateExtends = true;
  51209. // Cache
  51210. _this._orthoLeft = Number.MAX_VALUE;
  51211. _this._orthoRight = Number.MIN_VALUE;
  51212. _this._orthoTop = Number.MIN_VALUE;
  51213. _this._orthoBottom = Number.MAX_VALUE;
  51214. _this.position = direction.scale(-1.0);
  51215. _this.direction = direction;
  51216. return _this;
  51217. }
  51218. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51219. /**
  51220. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51221. */
  51222. get: function () {
  51223. return this._shadowFrustumSize;
  51224. },
  51225. /**
  51226. * Specifies a fix frustum size for the shadow generation.
  51227. */
  51228. set: function (value) {
  51229. this._shadowFrustumSize = value;
  51230. this.forceProjectionMatrixCompute();
  51231. },
  51232. enumerable: true,
  51233. configurable: true
  51234. });
  51235. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51236. /**
  51237. * Gets the shadow projection scale against the optimal computed one.
  51238. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51239. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51240. */
  51241. get: function () {
  51242. return this._shadowOrthoScale;
  51243. },
  51244. /**
  51245. * Sets the shadow projection scale against the optimal computed one.
  51246. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51247. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51248. */
  51249. set: function (value) {
  51250. this._shadowOrthoScale = value;
  51251. this.forceProjectionMatrixCompute();
  51252. },
  51253. enumerable: true,
  51254. configurable: true
  51255. });
  51256. /**
  51257. * Returns the string "DirectionalLight".
  51258. * @return The class name
  51259. */
  51260. DirectionalLight.prototype.getClassName = function () {
  51261. return "DirectionalLight";
  51262. };
  51263. /**
  51264. * Returns the integer 1.
  51265. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51266. */
  51267. DirectionalLight.prototype.getTypeID = function () {
  51268. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51269. };
  51270. /**
  51271. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51272. * Returns the DirectionalLight Shadow projection matrix.
  51273. */
  51274. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51275. if (this.shadowFrustumSize > 0) {
  51276. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51277. }
  51278. else {
  51279. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51280. }
  51281. };
  51282. /**
  51283. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51284. * Returns the DirectionalLight Shadow projection matrix.
  51285. */
  51286. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51287. var activeCamera = this.getScene().activeCamera;
  51288. if (!activeCamera) {
  51289. return;
  51290. }
  51291. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51292. };
  51293. /**
  51294. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51295. * Returns the DirectionalLight Shadow projection matrix.
  51296. */
  51297. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51298. var activeCamera = this.getScene().activeCamera;
  51299. if (!activeCamera) {
  51300. return;
  51301. }
  51302. // Check extends
  51303. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51304. var tempVector3 = BABYLON.Vector3.Zero();
  51305. this._orthoLeft = Number.MAX_VALUE;
  51306. this._orthoRight = Number.MIN_VALUE;
  51307. this._orthoTop = Number.MIN_VALUE;
  51308. this._orthoBottom = Number.MAX_VALUE;
  51309. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51310. var mesh = renderList[meshIndex];
  51311. if (!mesh) {
  51312. continue;
  51313. }
  51314. var boundingInfo = mesh.getBoundingInfo();
  51315. var boundingBox = boundingInfo.boundingBox;
  51316. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51317. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51318. if (tempVector3.x < this._orthoLeft)
  51319. this._orthoLeft = tempVector3.x;
  51320. if (tempVector3.y < this._orthoBottom)
  51321. this._orthoBottom = tempVector3.y;
  51322. if (tempVector3.x > this._orthoRight)
  51323. this._orthoRight = tempVector3.x;
  51324. if (tempVector3.y > this._orthoTop)
  51325. this._orthoTop = tempVector3.y;
  51326. }
  51327. }
  51328. }
  51329. var xOffset = this._orthoRight - this._orthoLeft;
  51330. var yOffset = this._orthoTop - this._orthoBottom;
  51331. 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);
  51332. };
  51333. DirectionalLight.prototype._buildUniformLayout = function () {
  51334. this._uniformBuffer.addUniform("vLightData", 4);
  51335. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51336. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51337. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51338. this._uniformBuffer.addUniform("depthValues", 2);
  51339. this._uniformBuffer.create();
  51340. };
  51341. /**
  51342. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51343. * @param effect The effect to update
  51344. * @param lightIndex The index of the light in the effect to update
  51345. * @returns The directional light
  51346. */
  51347. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51348. if (this.computeTransformedInformation()) {
  51349. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51350. return this;
  51351. }
  51352. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51353. return this;
  51354. };
  51355. /**
  51356. * Gets the minZ used for shadow according to both the scene and the light.
  51357. *
  51358. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51359. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51360. * @param activeCamera The camera we are returning the min for
  51361. * @returns the depth min z
  51362. */
  51363. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51364. return 1;
  51365. };
  51366. /**
  51367. * Gets the maxZ used for shadow according to both the scene and the light.
  51368. *
  51369. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51370. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51371. * @param activeCamera The camera we are returning the max for
  51372. * @returns the depth max z
  51373. */
  51374. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51375. return 1;
  51376. };
  51377. /**
  51378. * Prepares the list of defines specific to the light type.
  51379. * @param defines the list of defines
  51380. * @param lightIndex defines the index of the light for the effect
  51381. */
  51382. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51383. defines["DIRLIGHT" + lightIndex] = true;
  51384. };
  51385. __decorate([
  51386. BABYLON.serialize()
  51387. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51388. __decorate([
  51389. BABYLON.serialize()
  51390. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51391. __decorate([
  51392. BABYLON.serialize()
  51393. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51394. return DirectionalLight;
  51395. }(BABYLON.ShadowLight));
  51396. BABYLON.DirectionalLight = DirectionalLight;
  51397. })(BABYLON || (BABYLON = {}));
  51398. //# sourceMappingURL=babylon.directionalLight.js.map
  51399. var BABYLON;
  51400. (function (BABYLON) {
  51401. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51402. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51403. });
  51404. /**
  51405. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51406. * These values define a cone of light starting from the position, emitting toward the direction.
  51407. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51408. * and the exponent defines the speed of the decay of the light with distance (reach).
  51409. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51410. */
  51411. var SpotLight = /** @class */ (function (_super) {
  51412. __extends(SpotLight, _super);
  51413. /**
  51414. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51415. * It can cast shadows.
  51416. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51417. * @param name The light friendly name
  51418. * @param position The position of the spot light in the scene
  51419. * @param direction The direction of the light in the scene
  51420. * @param angle The cone angle of the light in Radians
  51421. * @param exponent The light decay speed with the distance from the emission spot
  51422. * @param scene The scene the lights belongs to
  51423. */
  51424. function SpotLight(name, position, direction, angle, exponent, scene) {
  51425. var _this = _super.call(this, name, scene) || this;
  51426. _this._innerAngle = 0;
  51427. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51428. _this._projectionTextureLightNear = 1e-6;
  51429. _this._projectionTextureLightFar = 1000.0;
  51430. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51431. _this._projectionTextureViewLightDirty = true;
  51432. _this._projectionTextureProjectionLightDirty = true;
  51433. _this._projectionTextureDirty = true;
  51434. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51435. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51436. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51437. _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);
  51438. _this.position = position;
  51439. _this.direction = direction;
  51440. _this.angle = angle;
  51441. _this.exponent = exponent;
  51442. return _this;
  51443. }
  51444. Object.defineProperty(SpotLight.prototype, "angle", {
  51445. /**
  51446. * Gets the cone angle of the spot light in Radians.
  51447. */
  51448. get: function () {
  51449. return this._angle;
  51450. },
  51451. /**
  51452. * Sets the cone angle of the spot light in Radians.
  51453. */
  51454. set: function (value) {
  51455. this._angle = value;
  51456. this._cosHalfAngle = Math.cos(value * 0.5);
  51457. this._projectionTextureProjectionLightDirty = true;
  51458. this.forceProjectionMatrixCompute();
  51459. this._computeAngleValues();
  51460. },
  51461. enumerable: true,
  51462. configurable: true
  51463. });
  51464. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51465. /**
  51466. * Only used in gltf falloff mode, this defines the angle where
  51467. * the directional falloff will start before cutting at angle which could be seen
  51468. * as outer angle.
  51469. */
  51470. get: function () {
  51471. return this._innerAngle;
  51472. },
  51473. /**
  51474. * Only used in gltf falloff mode, this defines the angle where
  51475. * the directional falloff will start before cutting at angle which could be seen
  51476. * as outer angle.
  51477. */
  51478. set: function (value) {
  51479. this._innerAngle = value;
  51480. this._computeAngleValues();
  51481. },
  51482. enumerable: true,
  51483. configurable: true
  51484. });
  51485. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51486. /**
  51487. * Allows scaling the angle of the light for shadow generation only.
  51488. */
  51489. get: function () {
  51490. return this._shadowAngleScale;
  51491. },
  51492. /**
  51493. * Allows scaling the angle of the light for shadow generation only.
  51494. */
  51495. set: function (value) {
  51496. this._shadowAngleScale = value;
  51497. this.forceProjectionMatrixCompute();
  51498. },
  51499. enumerable: true,
  51500. configurable: true
  51501. });
  51502. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51503. /**
  51504. * Allows reading the projecton texture
  51505. */
  51506. get: function () {
  51507. return this._projectionTextureMatrix;
  51508. },
  51509. enumerable: true,
  51510. configurable: true
  51511. });
  51512. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51513. /**
  51514. * Gets the near clip of the Spotlight for texture projection.
  51515. */
  51516. get: function () {
  51517. return this._projectionTextureLightNear;
  51518. },
  51519. /**
  51520. * Sets the near clip of the Spotlight for texture projection.
  51521. */
  51522. set: function (value) {
  51523. this._projectionTextureLightNear = value;
  51524. this._projectionTextureProjectionLightDirty = true;
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51530. /**
  51531. * Gets the far clip of the Spotlight for texture projection.
  51532. */
  51533. get: function () {
  51534. return this._projectionTextureLightFar;
  51535. },
  51536. /**
  51537. * Sets the far clip of the Spotlight for texture projection.
  51538. */
  51539. set: function (value) {
  51540. this._projectionTextureLightFar = value;
  51541. this._projectionTextureProjectionLightDirty = true;
  51542. },
  51543. enumerable: true,
  51544. configurable: true
  51545. });
  51546. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51547. /**
  51548. * Gets the Up vector of the Spotlight for texture projection.
  51549. */
  51550. get: function () {
  51551. return this._projectionTextureUpDirection;
  51552. },
  51553. /**
  51554. * Sets the Up vector of the Spotlight for texture projection.
  51555. */
  51556. set: function (value) {
  51557. this._projectionTextureUpDirection = value;
  51558. this._projectionTextureProjectionLightDirty = true;
  51559. },
  51560. enumerable: true,
  51561. configurable: true
  51562. });
  51563. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51564. /**
  51565. * Gets the projection texture of the light.
  51566. */
  51567. get: function () {
  51568. return this._projectionTexture;
  51569. },
  51570. /**
  51571. * Sets the projection texture of the light.
  51572. */
  51573. set: function (value) {
  51574. this._projectionTexture = value;
  51575. this._projectionTextureDirty = true;
  51576. },
  51577. enumerable: true,
  51578. configurable: true
  51579. });
  51580. /**
  51581. * Returns the string "SpotLight".
  51582. * @returns the class name
  51583. */
  51584. SpotLight.prototype.getClassName = function () {
  51585. return "SpotLight";
  51586. };
  51587. /**
  51588. * Returns the integer 2.
  51589. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51590. */
  51591. SpotLight.prototype.getTypeID = function () {
  51592. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51593. };
  51594. /**
  51595. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51596. */
  51597. SpotLight.prototype._setDirection = function (value) {
  51598. _super.prototype._setDirection.call(this, value);
  51599. this._projectionTextureViewLightDirty = true;
  51600. };
  51601. /**
  51602. * Overrides the position setter to recompute the projection texture view light Matrix.
  51603. */
  51604. SpotLight.prototype._setPosition = function (value) {
  51605. _super.prototype._setPosition.call(this, value);
  51606. this._projectionTextureViewLightDirty = true;
  51607. };
  51608. /**
  51609. * 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.
  51610. * Returns the SpotLight.
  51611. */
  51612. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51613. var activeCamera = this.getScene().activeCamera;
  51614. if (!activeCamera) {
  51615. return;
  51616. }
  51617. this._shadowAngleScale = this._shadowAngleScale || 1;
  51618. var angle = this._shadowAngleScale * this._angle;
  51619. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51620. };
  51621. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51622. this._projectionTextureViewLightDirty = false;
  51623. this._projectionTextureDirty = true;
  51624. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51625. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51626. };
  51627. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51628. this._projectionTextureProjectionLightDirty = false;
  51629. this._projectionTextureDirty = true;
  51630. var light_far = this.projectionTextureLightFar;
  51631. var light_near = this.projectionTextureLightNear;
  51632. var P = light_far / (light_far - light_near);
  51633. var Q = -P * light_near;
  51634. var S = 1.0 / Math.tan(this._angle / 2.0);
  51635. var A = 1.0;
  51636. 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);
  51637. };
  51638. /**
  51639. * Main function for light texture projection matrix computing.
  51640. */
  51641. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51642. this._projectionTextureDirty = false;
  51643. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51644. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51645. };
  51646. SpotLight.prototype._buildUniformLayout = function () {
  51647. this._uniformBuffer.addUniform("vLightData", 4);
  51648. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51649. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51650. this._uniformBuffer.addUniform("vLightDirection", 3);
  51651. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51652. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51653. this._uniformBuffer.addUniform("depthValues", 2);
  51654. this._uniformBuffer.create();
  51655. };
  51656. SpotLight.prototype._computeAngleValues = function () {
  51657. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51658. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51659. };
  51660. /**
  51661. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51662. * @param effect The effect to update
  51663. * @param lightIndex The index of the light in the effect to update
  51664. * @returns The spot light
  51665. */
  51666. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51667. var normalizeDirection;
  51668. if (this.computeTransformedInformation()) {
  51669. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51670. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51671. }
  51672. else {
  51673. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51674. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51675. }
  51676. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51677. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51678. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51679. if (this._projectionTextureViewLightDirty) {
  51680. this._computeProjectionTextureViewLightMatrix();
  51681. }
  51682. if (this._projectionTextureProjectionLightDirty) {
  51683. this._computeProjectionTextureProjectionLightMatrix();
  51684. }
  51685. if (this._projectionTextureDirty) {
  51686. this._computeProjectionTextureMatrix();
  51687. }
  51688. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51689. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51690. }
  51691. return this;
  51692. };
  51693. /**
  51694. * Disposes the light and the associated resources.
  51695. */
  51696. SpotLight.prototype.dispose = function () {
  51697. _super.prototype.dispose.call(this);
  51698. if (this._projectionTexture) {
  51699. this._projectionTexture.dispose();
  51700. }
  51701. };
  51702. /**
  51703. * Prepares the list of defines specific to the light type.
  51704. * @param defines the list of defines
  51705. * @param lightIndex defines the index of the light for the effect
  51706. */
  51707. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51708. defines["SPOTLIGHT" + lightIndex] = true;
  51709. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51710. };
  51711. __decorate([
  51712. BABYLON.serialize()
  51713. ], SpotLight.prototype, "angle", null);
  51714. __decorate([
  51715. BABYLON.serialize()
  51716. ], SpotLight.prototype, "innerAngle", null);
  51717. __decorate([
  51718. BABYLON.serialize()
  51719. ], SpotLight.prototype, "shadowAngleScale", null);
  51720. __decorate([
  51721. BABYLON.serialize()
  51722. ], SpotLight.prototype, "exponent", void 0);
  51723. __decorate([
  51724. BABYLON.serialize()
  51725. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51726. __decorate([
  51727. BABYLON.serialize()
  51728. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51729. __decorate([
  51730. BABYLON.serialize()
  51731. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51732. __decorate([
  51733. BABYLON.serializeAsTexture("projectedLightTexture")
  51734. ], SpotLight.prototype, "_projectionTexture", void 0);
  51735. return SpotLight;
  51736. }(BABYLON.ShadowLight));
  51737. BABYLON.SpotLight = SpotLight;
  51738. })(BABYLON || (BABYLON = {}));
  51739. //# sourceMappingURL=babylon.spotLight.js.map
  51740. var BABYLON;
  51741. (function (BABYLON) {
  51742. /**
  51743. * Class used to override all child animations of a given target
  51744. */
  51745. var AnimationPropertiesOverride = /** @class */ (function () {
  51746. function AnimationPropertiesOverride() {
  51747. /**
  51748. * Gets or sets a value indicating if animation blending must be used
  51749. */
  51750. this.enableBlending = false;
  51751. /**
  51752. * Gets or sets the blending speed to use when enableBlending is true
  51753. */
  51754. this.blendingSpeed = 0.01;
  51755. /**
  51756. * Gets or sets the default loop mode to use
  51757. */
  51758. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51759. }
  51760. return AnimationPropertiesOverride;
  51761. }());
  51762. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51763. })(BABYLON || (BABYLON = {}));
  51764. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51765. var BABYLON;
  51766. (function (BABYLON) {
  51767. /**
  51768. * Represents the range of an animation
  51769. */
  51770. var AnimationRange = /** @class */ (function () {
  51771. /**
  51772. * Initializes the range of an animation
  51773. * @param name The name of the animation range
  51774. * @param from The starting frame of the animation
  51775. * @param to The ending frame of the animation
  51776. */
  51777. function AnimationRange(
  51778. /**The name of the animation range**/
  51779. name,
  51780. /**The starting frame of the animation */
  51781. from,
  51782. /**The ending frame of the animation*/
  51783. to) {
  51784. this.name = name;
  51785. this.from = from;
  51786. this.to = to;
  51787. }
  51788. /**
  51789. * Makes a copy of the animation range
  51790. * @returns A copy of the animation range
  51791. */
  51792. AnimationRange.prototype.clone = function () {
  51793. return new AnimationRange(this.name, this.from, this.to);
  51794. };
  51795. return AnimationRange;
  51796. }());
  51797. BABYLON.AnimationRange = AnimationRange;
  51798. /**
  51799. * Composed of a frame, and an action function
  51800. */
  51801. var AnimationEvent = /** @class */ (function () {
  51802. /**
  51803. * Initializes the animation event
  51804. * @param frame The frame for which the event is triggered
  51805. * @param action The event to perform when triggered
  51806. * @param onlyOnce Specifies if the event should be triggered only once
  51807. */
  51808. function AnimationEvent(
  51809. /** The frame for which the event is triggered **/
  51810. frame,
  51811. /** The event to perform when triggered **/
  51812. action,
  51813. /** Specifies if the event should be triggered only once**/
  51814. onlyOnce) {
  51815. this.frame = frame;
  51816. this.action = action;
  51817. this.onlyOnce = onlyOnce;
  51818. /**
  51819. * Specifies if the animation event is done
  51820. */
  51821. this.isDone = false;
  51822. }
  51823. /** @hidden */
  51824. AnimationEvent.prototype._clone = function () {
  51825. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51826. };
  51827. return AnimationEvent;
  51828. }());
  51829. BABYLON.AnimationEvent = AnimationEvent;
  51830. /**
  51831. * A cursor which tracks a point on a path
  51832. */
  51833. var PathCursor = /** @class */ (function () {
  51834. /**
  51835. * Initializes the path cursor
  51836. * @param path The path to track
  51837. */
  51838. function PathCursor(path) {
  51839. this.path = path;
  51840. /**
  51841. * Stores path cursor callbacks for when an onchange event is triggered
  51842. */
  51843. this._onchange = new Array();
  51844. /**
  51845. * The value of the path cursor
  51846. */
  51847. this.value = 0;
  51848. /**
  51849. * The animation array of the path cursor
  51850. */
  51851. this.animations = new Array();
  51852. }
  51853. /**
  51854. * Gets the cursor point on the path
  51855. * @returns A point on the path cursor at the cursor location
  51856. */
  51857. PathCursor.prototype.getPoint = function () {
  51858. var point = this.path.getPointAtLengthPosition(this.value);
  51859. return new BABYLON.Vector3(point.x, 0, point.y);
  51860. };
  51861. /**
  51862. * Moves the cursor ahead by the step amount
  51863. * @param step The amount to move the cursor forward
  51864. * @returns This path cursor
  51865. */
  51866. PathCursor.prototype.moveAhead = function (step) {
  51867. if (step === void 0) { step = 0.002; }
  51868. this.move(step);
  51869. return this;
  51870. };
  51871. /**
  51872. * Moves the cursor behind by the step amount
  51873. * @param step The amount to move the cursor back
  51874. * @returns This path cursor
  51875. */
  51876. PathCursor.prototype.moveBack = function (step) {
  51877. if (step === void 0) { step = 0.002; }
  51878. this.move(-step);
  51879. return this;
  51880. };
  51881. /**
  51882. * Moves the cursor by the step amount
  51883. * If the step amount is greater than one, an exception is thrown
  51884. * @param step The amount to move the cursor
  51885. * @returns This path cursor
  51886. */
  51887. PathCursor.prototype.move = function (step) {
  51888. if (Math.abs(step) > 1) {
  51889. throw "step size should be less than 1.";
  51890. }
  51891. this.value += step;
  51892. this.ensureLimits();
  51893. this.raiseOnChange();
  51894. return this;
  51895. };
  51896. /**
  51897. * Ensures that the value is limited between zero and one
  51898. * @returns This path cursor
  51899. */
  51900. PathCursor.prototype.ensureLimits = function () {
  51901. while (this.value > 1) {
  51902. this.value -= 1;
  51903. }
  51904. while (this.value < 0) {
  51905. this.value += 1;
  51906. }
  51907. return this;
  51908. };
  51909. /**
  51910. * Runs onchange callbacks on change (used by the animation engine)
  51911. * @returns This path cursor
  51912. */
  51913. PathCursor.prototype.raiseOnChange = function () {
  51914. var _this = this;
  51915. this._onchange.forEach(function (f) { return f(_this); });
  51916. return this;
  51917. };
  51918. /**
  51919. * Executes a function on change
  51920. * @param f A path cursor onchange callback
  51921. * @returns This path cursor
  51922. */
  51923. PathCursor.prototype.onchange = function (f) {
  51924. this._onchange.push(f);
  51925. return this;
  51926. };
  51927. return PathCursor;
  51928. }());
  51929. BABYLON.PathCursor = PathCursor;
  51930. /**
  51931. * Enum for the animation key frame interpolation type
  51932. */
  51933. var AnimationKeyInterpolation;
  51934. (function (AnimationKeyInterpolation) {
  51935. /**
  51936. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51937. */
  51938. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51939. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51940. /**
  51941. * Class used to store any kind of animation
  51942. */
  51943. var Animation = /** @class */ (function () {
  51944. /**
  51945. * Initializes the animation
  51946. * @param name Name of the animation
  51947. * @param targetProperty Property to animate
  51948. * @param framePerSecond The frames per second of the animation
  51949. * @param dataType The data type of the animation
  51950. * @param loopMode The loop mode of the animation
  51951. * @param enableBlendings Specifies if blending should be enabled
  51952. */
  51953. function Animation(
  51954. /**Name of the animation */
  51955. name,
  51956. /**Property to animate */
  51957. targetProperty,
  51958. /**The frames per second of the animation */
  51959. framePerSecond,
  51960. /**The data type of the animation */
  51961. dataType,
  51962. /**The loop mode of the animation */
  51963. loopMode,
  51964. /**Specifies if blending should be enabled */
  51965. enableBlending) {
  51966. this.name = name;
  51967. this.targetProperty = targetProperty;
  51968. this.framePerSecond = framePerSecond;
  51969. this.dataType = dataType;
  51970. this.loopMode = loopMode;
  51971. this.enableBlending = enableBlending;
  51972. /**
  51973. * @hidden Internal use only
  51974. */
  51975. this._runtimeAnimations = new Array();
  51976. /**
  51977. * The set of event that will be linked to this animation
  51978. */
  51979. this._events = new Array();
  51980. /**
  51981. * Stores the blending speed of the animation
  51982. */
  51983. this.blendingSpeed = 0.01;
  51984. /**
  51985. * Stores the animation ranges for the animation
  51986. */
  51987. this._ranges = {};
  51988. this.targetPropertyPath = targetProperty.split(".");
  51989. this.dataType = dataType;
  51990. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  51991. }
  51992. /**
  51993. * @hidden Internal use
  51994. */
  51995. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  51996. var dataType = undefined;
  51997. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  51998. dataType = Animation.ANIMATIONTYPE_FLOAT;
  51999. }
  52000. else if (from instanceof BABYLON.Quaternion) {
  52001. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  52002. }
  52003. else if (from instanceof BABYLON.Vector3) {
  52004. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  52005. }
  52006. else if (from instanceof BABYLON.Vector2) {
  52007. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  52008. }
  52009. else if (from instanceof BABYLON.Color3) {
  52010. dataType = Animation.ANIMATIONTYPE_COLOR3;
  52011. }
  52012. else if (from instanceof BABYLON.Size) {
  52013. dataType = Animation.ANIMATIONTYPE_SIZE;
  52014. }
  52015. if (dataType == undefined) {
  52016. return null;
  52017. }
  52018. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  52019. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  52020. animation.setKeys(keys);
  52021. if (easingFunction !== undefined) {
  52022. animation.setEasingFunction(easingFunction);
  52023. }
  52024. return animation;
  52025. };
  52026. /**
  52027. * Sets up an animation
  52028. * @param property The property to animate
  52029. * @param animationType The animation type to apply
  52030. * @param framePerSecond The frames per second of the animation
  52031. * @param easingFunction The easing function used in the animation
  52032. * @returns The created animation
  52033. */
  52034. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52035. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52036. animation.setEasingFunction(easingFunction);
  52037. return animation;
  52038. };
  52039. /**
  52040. * Create and start an animation on a node
  52041. * @param name defines the name of the global animation that will be run on all nodes
  52042. * @param node defines the root node where the animation will take place
  52043. * @param targetProperty defines property to animate
  52044. * @param framePerSecond defines the number of frame per second yo use
  52045. * @param totalFrame defines the number of frames in total
  52046. * @param from defines the initial value
  52047. * @param to defines the final value
  52048. * @param loopMode defines which loop mode you want to use (off by default)
  52049. * @param easingFunction defines the easing function to use (linear by default)
  52050. * @param onAnimationEnd defines the callback to call when animation end
  52051. * @returns the animatable created for this animation
  52052. */
  52053. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52054. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52055. if (!animation) {
  52056. return null;
  52057. }
  52058. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52059. };
  52060. /**
  52061. * Create and start an animation on a node and its descendants
  52062. * @param name defines the name of the global animation that will be run on all nodes
  52063. * @param node defines the root node where the animation will take place
  52064. * @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
  52065. * @param targetProperty defines property to animate
  52066. * @param framePerSecond defines the number of frame per second to use
  52067. * @param totalFrame defines the number of frames in total
  52068. * @param from defines the initial value
  52069. * @param to defines the final value
  52070. * @param loopMode defines which loop mode you want to use (off by default)
  52071. * @param easingFunction defines the easing function to use (linear by default)
  52072. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52073. * @returns the list of animatables created for all nodes
  52074. * @example https://www.babylonjs-playground.com/#MH0VLI
  52075. */
  52076. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52077. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52078. if (!animation) {
  52079. return null;
  52080. }
  52081. var scene = node.getScene();
  52082. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52083. };
  52084. /**
  52085. * Creates a new animation, merges it with the existing animations and starts it
  52086. * @param name Name of the animation
  52087. * @param node Node which contains the scene that begins the animations
  52088. * @param targetProperty Specifies which property to animate
  52089. * @param framePerSecond The frames per second of the animation
  52090. * @param totalFrame The total number of frames
  52091. * @param from The frame at the beginning of the animation
  52092. * @param to The frame at the end of the animation
  52093. * @param loopMode Specifies the loop mode of the animation
  52094. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52095. * @param onAnimationEnd Callback to run once the animation is complete
  52096. * @returns Nullable animation
  52097. */
  52098. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52099. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52100. if (!animation) {
  52101. return null;
  52102. }
  52103. node.animations.push(animation);
  52104. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52105. };
  52106. /**
  52107. * Transition property of an host to the target Value
  52108. * @param property The property to transition
  52109. * @param targetValue The target Value of the property
  52110. * @param host The object where the property to animate belongs
  52111. * @param scene Scene used to run the animation
  52112. * @param frameRate Framerate (in frame/s) to use
  52113. * @param transition The transition type we want to use
  52114. * @param duration The duration of the animation, in milliseconds
  52115. * @param onAnimationEnd Callback trigger at the end of the animation
  52116. * @returns Nullable animation
  52117. */
  52118. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52119. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52120. if (duration <= 0) {
  52121. host[property] = targetValue;
  52122. if (onAnimationEnd) {
  52123. onAnimationEnd();
  52124. }
  52125. return null;
  52126. }
  52127. var endFrame = frameRate * (duration / 1000);
  52128. transition.setKeys([{
  52129. frame: 0,
  52130. value: host[property].clone ? host[property].clone() : host[property]
  52131. },
  52132. {
  52133. frame: endFrame,
  52134. value: targetValue
  52135. }]);
  52136. if (!host.animations) {
  52137. host.animations = [];
  52138. }
  52139. host.animations.push(transition);
  52140. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52141. animation.onAnimationEnd = onAnimationEnd;
  52142. return animation;
  52143. };
  52144. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52145. /**
  52146. * Return the array of runtime animations currently using this animation
  52147. */
  52148. get: function () {
  52149. return this._runtimeAnimations;
  52150. },
  52151. enumerable: true,
  52152. configurable: true
  52153. });
  52154. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52155. /**
  52156. * Specifies if any of the runtime animations are currently running
  52157. */
  52158. get: function () {
  52159. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52160. var runtimeAnimation = _a[_i];
  52161. if (!runtimeAnimation.isStopped) {
  52162. return true;
  52163. }
  52164. }
  52165. return false;
  52166. },
  52167. enumerable: true,
  52168. configurable: true
  52169. });
  52170. // Methods
  52171. /**
  52172. * Converts the animation to a string
  52173. * @param fullDetails support for multiple levels of logging within scene loading
  52174. * @returns String form of the animation
  52175. */
  52176. Animation.prototype.toString = function (fullDetails) {
  52177. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52178. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52179. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52180. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52181. if (fullDetails) {
  52182. ret += ", Ranges: {";
  52183. var first = true;
  52184. for (var name in this._ranges) {
  52185. if (first) {
  52186. ret += ", ";
  52187. first = false;
  52188. }
  52189. ret += name;
  52190. }
  52191. ret += "}";
  52192. }
  52193. return ret;
  52194. };
  52195. /**
  52196. * Add an event to this animation
  52197. * @param event Event to add
  52198. */
  52199. Animation.prototype.addEvent = function (event) {
  52200. this._events.push(event);
  52201. };
  52202. /**
  52203. * Remove all events found at the given frame
  52204. * @param frame The frame to remove events from
  52205. */
  52206. Animation.prototype.removeEvents = function (frame) {
  52207. for (var index = 0; index < this._events.length; index++) {
  52208. if (this._events[index].frame === frame) {
  52209. this._events.splice(index, 1);
  52210. index--;
  52211. }
  52212. }
  52213. };
  52214. /**
  52215. * Retrieves all the events from the animation
  52216. * @returns Events from the animation
  52217. */
  52218. Animation.prototype.getEvents = function () {
  52219. return this._events;
  52220. };
  52221. /**
  52222. * Creates an animation range
  52223. * @param name Name of the animation range
  52224. * @param from Starting frame of the animation range
  52225. * @param to Ending frame of the animation
  52226. */
  52227. Animation.prototype.createRange = function (name, from, to) {
  52228. // check name not already in use; could happen for bones after serialized
  52229. if (!this._ranges[name]) {
  52230. this._ranges[name] = new AnimationRange(name, from, to);
  52231. }
  52232. };
  52233. /**
  52234. * Deletes an animation range by name
  52235. * @param name Name of the animation range to delete
  52236. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52237. */
  52238. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52239. if (deleteFrames === void 0) { deleteFrames = true; }
  52240. var range = this._ranges[name];
  52241. if (!range) {
  52242. return;
  52243. }
  52244. if (deleteFrames) {
  52245. var from = range.from;
  52246. var to = range.to;
  52247. // this loop MUST go high to low for multiple splices to work
  52248. for (var key = this._keys.length - 1; key >= 0; key--) {
  52249. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52250. this._keys.splice(key, 1);
  52251. }
  52252. }
  52253. }
  52254. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52255. };
  52256. /**
  52257. * Gets the animation range by name, or null if not defined
  52258. * @param name Name of the animation range
  52259. * @returns Nullable animation range
  52260. */
  52261. Animation.prototype.getRange = function (name) {
  52262. return this._ranges[name];
  52263. };
  52264. /**
  52265. * Gets the key frames from the animation
  52266. * @returns The key frames of the animation
  52267. */
  52268. Animation.prototype.getKeys = function () {
  52269. return this._keys;
  52270. };
  52271. /**
  52272. * Gets the highest frame rate of the animation
  52273. * @returns Highest frame rate of the animation
  52274. */
  52275. Animation.prototype.getHighestFrame = function () {
  52276. var ret = 0;
  52277. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52278. if (ret < this._keys[key].frame) {
  52279. ret = this._keys[key].frame;
  52280. }
  52281. }
  52282. return ret;
  52283. };
  52284. /**
  52285. * Gets the easing function of the animation
  52286. * @returns Easing function of the animation
  52287. */
  52288. Animation.prototype.getEasingFunction = function () {
  52289. return this._easingFunction;
  52290. };
  52291. /**
  52292. * Sets the easing function of the animation
  52293. * @param easingFunction A custom mathematical formula for animation
  52294. */
  52295. Animation.prototype.setEasingFunction = function (easingFunction) {
  52296. this._easingFunction = easingFunction;
  52297. };
  52298. /**
  52299. * Interpolates a scalar linearly
  52300. * @param startValue Start value of the animation curve
  52301. * @param endValue End value of the animation curve
  52302. * @param gradient Scalar amount to interpolate
  52303. * @returns Interpolated scalar value
  52304. */
  52305. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52306. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52307. };
  52308. /**
  52309. * Interpolates a scalar cubically
  52310. * @param startValue Start value of the animation curve
  52311. * @param outTangent End tangent of the animation
  52312. * @param endValue End value of the animation curve
  52313. * @param inTangent Start tangent of the animation curve
  52314. * @param gradient Scalar amount to interpolate
  52315. * @returns Interpolated scalar value
  52316. */
  52317. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52318. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52319. };
  52320. /**
  52321. * Interpolates a quaternion using a spherical linear interpolation
  52322. * @param startValue Start value of the animation curve
  52323. * @param endValue End value of the animation curve
  52324. * @param gradient Scalar amount to interpolate
  52325. * @returns Interpolated quaternion value
  52326. */
  52327. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52328. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52329. };
  52330. /**
  52331. * Interpolates a quaternion cubically
  52332. * @param startValue Start value of the animation curve
  52333. * @param outTangent End tangent of the animation curve
  52334. * @param endValue End value of the animation curve
  52335. * @param inTangent Start tangent of the animation curve
  52336. * @param gradient Scalar amount to interpolate
  52337. * @returns Interpolated quaternion value
  52338. */
  52339. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52340. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52341. };
  52342. /**
  52343. * Interpolates a Vector3 linearl
  52344. * @param startValue Start value of the animation curve
  52345. * @param endValue End value of the animation curve
  52346. * @param gradient Scalar amount to interpolate
  52347. * @returns Interpolated scalar value
  52348. */
  52349. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52350. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52351. };
  52352. /**
  52353. * Interpolates a Vector3 cubically
  52354. * @param startValue Start value of the animation curve
  52355. * @param outTangent End tangent of the animation
  52356. * @param endValue End value of the animation curve
  52357. * @param inTangent Start tangent of the animation curve
  52358. * @param gradient Scalar amount to interpolate
  52359. * @returns InterpolatedVector3 value
  52360. */
  52361. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52362. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52363. };
  52364. /**
  52365. * Interpolates a Vector2 linearly
  52366. * @param startValue Start value of the animation curve
  52367. * @param endValue End value of the animation curve
  52368. * @param gradient Scalar amount to interpolate
  52369. * @returns Interpolated Vector2 value
  52370. */
  52371. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52372. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52373. };
  52374. /**
  52375. * Interpolates a Vector2 cubically
  52376. * @param startValue Start value of the animation curve
  52377. * @param outTangent End tangent of the animation
  52378. * @param endValue End value of the animation curve
  52379. * @param inTangent Start tangent of the animation curve
  52380. * @param gradient Scalar amount to interpolate
  52381. * @returns Interpolated Vector2 value
  52382. */
  52383. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52384. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52385. };
  52386. /**
  52387. * Interpolates a size linearly
  52388. * @param startValue Start value of the animation curve
  52389. * @param endValue End value of the animation curve
  52390. * @param gradient Scalar amount to interpolate
  52391. * @returns Interpolated Size value
  52392. */
  52393. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52394. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52395. };
  52396. /**
  52397. * Interpolates a Color3 linearly
  52398. * @param startValue Start value of the animation curve
  52399. * @param endValue End value of the animation curve
  52400. * @param gradient Scalar amount to interpolate
  52401. * @returns Interpolated Color3 value
  52402. */
  52403. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52404. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52405. };
  52406. /**
  52407. * @hidden Internal use only
  52408. */
  52409. Animation.prototype._getKeyValue = function (value) {
  52410. if (typeof value === "function") {
  52411. return value();
  52412. }
  52413. return value;
  52414. };
  52415. /**
  52416. * @hidden Internal use only
  52417. */
  52418. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52419. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52420. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52421. }
  52422. var keys = this.getKeys();
  52423. // Try to get a hash to find the right key
  52424. 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));
  52425. if (keys[startKeyIndex].frame >= currentFrame) {
  52426. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52427. startKeyIndex--;
  52428. }
  52429. }
  52430. for (var key = startKeyIndex; key < keys.length; key++) {
  52431. var endKey = keys[key + 1];
  52432. if (endKey.frame >= currentFrame) {
  52433. var startKey = keys[key];
  52434. var startValue = this._getKeyValue(startKey.value);
  52435. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52436. return startValue;
  52437. }
  52438. var endValue = this._getKeyValue(endKey.value);
  52439. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52440. var frameDelta = endKey.frame - startKey.frame;
  52441. // gradient : percent of currentFrame between the frame inf and the frame sup
  52442. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52443. // check for easingFunction and correction of gradient
  52444. var easingFunction = this.getEasingFunction();
  52445. if (easingFunction != null) {
  52446. gradient = easingFunction.ease(gradient);
  52447. }
  52448. switch (this.dataType) {
  52449. // Float
  52450. case Animation.ANIMATIONTYPE_FLOAT:
  52451. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52452. switch (loopMode) {
  52453. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52454. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52455. return floatValue;
  52456. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52457. return offsetValue * repeatCount + floatValue;
  52458. }
  52459. break;
  52460. // Quaternion
  52461. case Animation.ANIMATIONTYPE_QUATERNION:
  52462. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52463. switch (loopMode) {
  52464. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52465. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52466. return quatValue;
  52467. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52468. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52469. }
  52470. return quatValue;
  52471. // Vector3
  52472. case Animation.ANIMATIONTYPE_VECTOR3:
  52473. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52474. switch (loopMode) {
  52475. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52476. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52477. return vec3Value;
  52478. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52479. return vec3Value.add(offsetValue.scale(repeatCount));
  52480. }
  52481. // Vector2
  52482. case Animation.ANIMATIONTYPE_VECTOR2:
  52483. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52484. switch (loopMode) {
  52485. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52486. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52487. return vec2Value;
  52488. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52489. return vec2Value.add(offsetValue.scale(repeatCount));
  52490. }
  52491. // Size
  52492. case Animation.ANIMATIONTYPE_SIZE:
  52493. switch (loopMode) {
  52494. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52495. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52496. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52497. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52498. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52499. }
  52500. // Color3
  52501. case Animation.ANIMATIONTYPE_COLOR3:
  52502. switch (loopMode) {
  52503. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52504. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52505. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52506. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52507. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52508. }
  52509. // Matrix
  52510. case Animation.ANIMATIONTYPE_MATRIX:
  52511. switch (loopMode) {
  52512. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52513. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52514. if (Animation.AllowMatricesInterpolation) {
  52515. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52516. }
  52517. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52518. return startValue;
  52519. }
  52520. default:
  52521. break;
  52522. }
  52523. break;
  52524. }
  52525. }
  52526. return this._getKeyValue(keys[keys.length - 1].value);
  52527. };
  52528. /**
  52529. * Defines the function to use to interpolate matrices
  52530. * @param startValue defines the start matrix
  52531. * @param endValue defines the end matrix
  52532. * @param gradient defines the gradient between both matrices
  52533. * @param result defines an optional target matrix where to store the interpolation
  52534. * @returns the interpolated matrix
  52535. */
  52536. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52537. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52538. if (result) {
  52539. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52540. return result;
  52541. }
  52542. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52543. }
  52544. if (result) {
  52545. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52546. return result;
  52547. }
  52548. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52549. };
  52550. /**
  52551. * Makes a copy of the animation
  52552. * @returns Cloned animation
  52553. */
  52554. Animation.prototype.clone = function () {
  52555. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52556. clone.enableBlending = this.enableBlending;
  52557. clone.blendingSpeed = this.blendingSpeed;
  52558. if (this._keys) {
  52559. clone.setKeys(this._keys);
  52560. }
  52561. if (this._ranges) {
  52562. clone._ranges = {};
  52563. for (var name in this._ranges) {
  52564. var range = this._ranges[name];
  52565. if (!range) {
  52566. continue;
  52567. }
  52568. clone._ranges[name] = range.clone();
  52569. }
  52570. }
  52571. return clone;
  52572. };
  52573. /**
  52574. * Sets the key frames of the animation
  52575. * @param values The animation key frames to set
  52576. */
  52577. Animation.prototype.setKeys = function (values) {
  52578. this._keys = values.slice(0);
  52579. };
  52580. /**
  52581. * Serializes the animation to an object
  52582. * @returns Serialized object
  52583. */
  52584. Animation.prototype.serialize = function () {
  52585. var serializationObject = {};
  52586. serializationObject.name = this.name;
  52587. serializationObject.property = this.targetProperty;
  52588. serializationObject.framePerSecond = this.framePerSecond;
  52589. serializationObject.dataType = this.dataType;
  52590. serializationObject.loopBehavior = this.loopMode;
  52591. serializationObject.enableBlending = this.enableBlending;
  52592. serializationObject.blendingSpeed = this.blendingSpeed;
  52593. var dataType = this.dataType;
  52594. serializationObject.keys = [];
  52595. var keys = this.getKeys();
  52596. for (var index = 0; index < keys.length; index++) {
  52597. var animationKey = keys[index];
  52598. var key = {};
  52599. key.frame = animationKey.frame;
  52600. switch (dataType) {
  52601. case Animation.ANIMATIONTYPE_FLOAT:
  52602. key.values = [animationKey.value];
  52603. break;
  52604. case Animation.ANIMATIONTYPE_QUATERNION:
  52605. case Animation.ANIMATIONTYPE_MATRIX:
  52606. case Animation.ANIMATIONTYPE_VECTOR3:
  52607. case Animation.ANIMATIONTYPE_COLOR3:
  52608. key.values = animationKey.value.asArray();
  52609. break;
  52610. }
  52611. serializationObject.keys.push(key);
  52612. }
  52613. serializationObject.ranges = [];
  52614. for (var name in this._ranges) {
  52615. var source = this._ranges[name];
  52616. if (!source) {
  52617. continue;
  52618. }
  52619. var range = {};
  52620. range.name = name;
  52621. range.from = source.from;
  52622. range.to = source.to;
  52623. serializationObject.ranges.push(range);
  52624. }
  52625. return serializationObject;
  52626. };
  52627. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52628. /**
  52629. * Get the float animation type
  52630. */
  52631. get: function () {
  52632. return Animation._ANIMATIONTYPE_FLOAT;
  52633. },
  52634. enumerable: true,
  52635. configurable: true
  52636. });
  52637. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52638. /**
  52639. * Get the Vector3 animation type
  52640. */
  52641. get: function () {
  52642. return Animation._ANIMATIONTYPE_VECTOR3;
  52643. },
  52644. enumerable: true,
  52645. configurable: true
  52646. });
  52647. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52648. /**
  52649. * Get the Vector2 animation type
  52650. */
  52651. get: function () {
  52652. return Animation._ANIMATIONTYPE_VECTOR2;
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52658. /**
  52659. * Get the Size animation type
  52660. */
  52661. get: function () {
  52662. return Animation._ANIMATIONTYPE_SIZE;
  52663. },
  52664. enumerable: true,
  52665. configurable: true
  52666. });
  52667. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52668. /**
  52669. * Get the Quaternion animation type
  52670. */
  52671. get: function () {
  52672. return Animation._ANIMATIONTYPE_QUATERNION;
  52673. },
  52674. enumerable: true,
  52675. configurable: true
  52676. });
  52677. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52678. /**
  52679. * Get the Matrix animation type
  52680. */
  52681. get: function () {
  52682. return Animation._ANIMATIONTYPE_MATRIX;
  52683. },
  52684. enumerable: true,
  52685. configurable: true
  52686. });
  52687. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52688. /**
  52689. * Get the Color3 animation type
  52690. */
  52691. get: function () {
  52692. return Animation._ANIMATIONTYPE_COLOR3;
  52693. },
  52694. enumerable: true,
  52695. configurable: true
  52696. });
  52697. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52698. /**
  52699. * Get the Relative Loop Mode
  52700. */
  52701. get: function () {
  52702. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52703. },
  52704. enumerable: true,
  52705. configurable: true
  52706. });
  52707. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52708. /**
  52709. * Get the Cycle Loop Mode
  52710. */
  52711. get: function () {
  52712. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52713. },
  52714. enumerable: true,
  52715. configurable: true
  52716. });
  52717. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52718. /**
  52719. * Get the Constant Loop Mode
  52720. */
  52721. get: function () {
  52722. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52723. },
  52724. enumerable: true,
  52725. configurable: true
  52726. });
  52727. /** @hidden */
  52728. Animation._UniversalLerp = function (left, right, amount) {
  52729. var constructor = left.constructor;
  52730. if (constructor.Lerp) { // Lerp supported
  52731. return constructor.Lerp(left, right, amount);
  52732. }
  52733. else if (constructor.Slerp) { // Slerp supported
  52734. return constructor.Slerp(left, right, amount);
  52735. }
  52736. else if (left.toFixed) { // Number
  52737. return left * (1.0 - amount) + amount * right;
  52738. }
  52739. else { // Blending not supported
  52740. return right;
  52741. }
  52742. };
  52743. /**
  52744. * Parses an animation object and creates an animation
  52745. * @param parsedAnimation Parsed animation object
  52746. * @returns Animation object
  52747. */
  52748. Animation.Parse = function (parsedAnimation) {
  52749. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52750. var dataType = parsedAnimation.dataType;
  52751. var keys = [];
  52752. var data;
  52753. var index;
  52754. if (parsedAnimation.enableBlending) {
  52755. animation.enableBlending = parsedAnimation.enableBlending;
  52756. }
  52757. if (parsedAnimation.blendingSpeed) {
  52758. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52759. }
  52760. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52761. var key = parsedAnimation.keys[index];
  52762. var inTangent;
  52763. var outTangent;
  52764. switch (dataType) {
  52765. case Animation.ANIMATIONTYPE_FLOAT:
  52766. data = key.values[0];
  52767. if (key.values.length >= 1) {
  52768. inTangent = key.values[1];
  52769. }
  52770. if (key.values.length >= 2) {
  52771. outTangent = key.values[2];
  52772. }
  52773. break;
  52774. case Animation.ANIMATIONTYPE_QUATERNION:
  52775. data = BABYLON.Quaternion.FromArray(key.values);
  52776. if (key.values.length >= 8) {
  52777. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52778. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52779. inTangent = _inTangent;
  52780. }
  52781. }
  52782. if (key.values.length >= 12) {
  52783. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52784. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52785. outTangent = _outTangent;
  52786. }
  52787. }
  52788. break;
  52789. case Animation.ANIMATIONTYPE_MATRIX:
  52790. data = BABYLON.Matrix.FromArray(key.values);
  52791. break;
  52792. case Animation.ANIMATIONTYPE_COLOR3:
  52793. data = BABYLON.Color3.FromArray(key.values);
  52794. break;
  52795. case Animation.ANIMATIONTYPE_VECTOR3:
  52796. default:
  52797. data = BABYLON.Vector3.FromArray(key.values);
  52798. break;
  52799. }
  52800. var keyData = {};
  52801. keyData.frame = key.frame;
  52802. keyData.value = data;
  52803. if (inTangent != undefined) {
  52804. keyData.inTangent = inTangent;
  52805. }
  52806. if (outTangent != undefined) {
  52807. keyData.outTangent = outTangent;
  52808. }
  52809. keys.push(keyData);
  52810. }
  52811. animation.setKeys(keys);
  52812. if (parsedAnimation.ranges) {
  52813. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52814. data = parsedAnimation.ranges[index];
  52815. animation.createRange(data.name, data.from, data.to);
  52816. }
  52817. }
  52818. return animation;
  52819. };
  52820. /**
  52821. * Appends the serialized animations from the source animations
  52822. * @param source Source containing the animations
  52823. * @param destination Target to store the animations
  52824. */
  52825. Animation.AppendSerializedAnimations = function (source, destination) {
  52826. if (source.animations) {
  52827. destination.animations = [];
  52828. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52829. var animation = source.animations[animationIndex];
  52830. destination.animations.push(animation.serialize());
  52831. }
  52832. }
  52833. };
  52834. /**
  52835. * Use matrix interpolation instead of using direct key value when animating matrices
  52836. */
  52837. Animation.AllowMatricesInterpolation = false;
  52838. /**
  52839. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52840. */
  52841. Animation.AllowMatrixDecomposeForInterpolation = true;
  52842. // Statics
  52843. /**
  52844. * Float animation type
  52845. */
  52846. Animation._ANIMATIONTYPE_FLOAT = 0;
  52847. /**
  52848. * Vector3 animation type
  52849. */
  52850. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52851. /**
  52852. * Quaternion animation type
  52853. */
  52854. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52855. /**
  52856. * Matrix animation type
  52857. */
  52858. Animation._ANIMATIONTYPE_MATRIX = 3;
  52859. /**
  52860. * Color3 animation type
  52861. */
  52862. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52863. /**
  52864. * Vector2 animation type
  52865. */
  52866. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52867. /**
  52868. * Size animation type
  52869. */
  52870. Animation._ANIMATIONTYPE_SIZE = 6;
  52871. /**
  52872. * Relative Loop Mode
  52873. */
  52874. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52875. /**
  52876. * Cycle Loop Mode
  52877. */
  52878. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52879. /**
  52880. * Constant Loop Mode
  52881. */
  52882. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52883. return Animation;
  52884. }());
  52885. BABYLON.Animation = Animation;
  52886. })(BABYLON || (BABYLON = {}));
  52887. //# sourceMappingURL=babylon.animation.js.map
  52888. var BABYLON;
  52889. (function (BABYLON) {
  52890. /**
  52891. * This class defines the direct association between an animation and a target
  52892. */
  52893. var TargetedAnimation = /** @class */ (function () {
  52894. function TargetedAnimation() {
  52895. }
  52896. return TargetedAnimation;
  52897. }());
  52898. BABYLON.TargetedAnimation = TargetedAnimation;
  52899. /**
  52900. * Use this class to create coordinated animations on multiple targets
  52901. */
  52902. var AnimationGroup = /** @class */ (function () {
  52903. /**
  52904. * Instantiates a new Animation Group.
  52905. * This helps managing several animations at once.
  52906. * @see http://doc.babylonjs.com/how_to/group
  52907. * @param name Defines the name of the group
  52908. * @param scene Defines the scene the group belongs to
  52909. */
  52910. function AnimationGroup(
  52911. /** The name of the animation group */
  52912. name, scene) {
  52913. if (scene === void 0) { scene = null; }
  52914. this.name = name;
  52915. this._targetedAnimations = new Array();
  52916. this._animatables = new Array();
  52917. this._from = Number.MAX_VALUE;
  52918. this._to = -Number.MAX_VALUE;
  52919. this._speedRatio = 1;
  52920. /**
  52921. * This observable will notify when one animation have ended.
  52922. */
  52923. this.onAnimationEndObservable = new BABYLON.Observable();
  52924. /**
  52925. * This observable will notify when all animations have ended.
  52926. */
  52927. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52928. /**
  52929. * This observable will notify when all animations have paused.
  52930. */
  52931. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52932. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52933. this._scene.animationGroups.push(this);
  52934. }
  52935. Object.defineProperty(AnimationGroup.prototype, "from", {
  52936. /**
  52937. * Gets the first frame
  52938. */
  52939. get: function () {
  52940. return this._from;
  52941. },
  52942. enumerable: true,
  52943. configurable: true
  52944. });
  52945. Object.defineProperty(AnimationGroup.prototype, "to", {
  52946. /**
  52947. * Gets the last frame
  52948. */
  52949. get: function () {
  52950. return this._to;
  52951. },
  52952. enumerable: true,
  52953. configurable: true
  52954. });
  52955. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52956. /**
  52957. * Define if the animations are started
  52958. */
  52959. get: function () {
  52960. return this._isStarted;
  52961. },
  52962. enumerable: true,
  52963. configurable: true
  52964. });
  52965. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52966. /**
  52967. * Gets or sets the speed ratio to use for all animations
  52968. */
  52969. get: function () {
  52970. return this._speedRatio;
  52971. },
  52972. /**
  52973. * Gets or sets the speed ratio to use for all animations
  52974. */
  52975. set: function (value) {
  52976. if (this._speedRatio === value) {
  52977. return;
  52978. }
  52979. this._speedRatio = value;
  52980. for (var index = 0; index < this._animatables.length; index++) {
  52981. var animatable = this._animatables[index];
  52982. animatable.speedRatio = this._speedRatio;
  52983. }
  52984. },
  52985. enumerable: true,
  52986. configurable: true
  52987. });
  52988. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  52989. /**
  52990. * Gets the targeted animations for this animation group
  52991. */
  52992. get: function () {
  52993. return this._targetedAnimations;
  52994. },
  52995. enumerable: true,
  52996. configurable: true
  52997. });
  52998. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  52999. /**
  53000. * returning the list of animatables controlled by this animation group.
  53001. */
  53002. get: function () {
  53003. return this._animatables;
  53004. },
  53005. enumerable: true,
  53006. configurable: true
  53007. });
  53008. /**
  53009. * Add an animation (with its target) in the group
  53010. * @param animation defines the animation we want to add
  53011. * @param target defines the target of the animation
  53012. * @returns the TargetedAnimation object
  53013. */
  53014. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  53015. var targetedAnimation = {
  53016. animation: animation,
  53017. target: target
  53018. };
  53019. var keys = animation.getKeys();
  53020. if (this._from > keys[0].frame) {
  53021. this._from = keys[0].frame;
  53022. }
  53023. if (this._to < keys[keys.length - 1].frame) {
  53024. this._to = keys[keys.length - 1].frame;
  53025. }
  53026. this._targetedAnimations.push(targetedAnimation);
  53027. return targetedAnimation;
  53028. };
  53029. /**
  53030. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53031. * It can add constant keys at begin or end
  53032. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53033. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53034. * @returns the animation group
  53035. */
  53036. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53037. if (beginFrame === void 0) { beginFrame = null; }
  53038. if (endFrame === void 0) { endFrame = null; }
  53039. if (beginFrame == null)
  53040. beginFrame = this._from;
  53041. if (endFrame == null)
  53042. endFrame = this._to;
  53043. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53044. var targetedAnimation = this._targetedAnimations[index];
  53045. var keys = targetedAnimation.animation.getKeys();
  53046. var startKey = keys[0];
  53047. var endKey = keys[keys.length - 1];
  53048. if (startKey.frame > beginFrame) {
  53049. var newKey = {
  53050. frame: beginFrame,
  53051. value: startKey.value,
  53052. inTangent: startKey.inTangent,
  53053. outTangent: startKey.outTangent,
  53054. interpolation: startKey.interpolation
  53055. };
  53056. keys.splice(0, 0, newKey);
  53057. }
  53058. if (endKey.frame < endFrame) {
  53059. var newKey = {
  53060. frame: endFrame,
  53061. value: endKey.value,
  53062. inTangent: endKey.outTangent,
  53063. outTangent: endKey.outTangent,
  53064. interpolation: endKey.interpolation
  53065. };
  53066. keys.push(newKey);
  53067. }
  53068. }
  53069. this._from = beginFrame;
  53070. this._to = endFrame;
  53071. return this;
  53072. };
  53073. /**
  53074. * Start all animations on given targets
  53075. * @param loop defines if animations must loop
  53076. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53077. * @param from defines the from key (optional)
  53078. * @param to defines the to key (optional)
  53079. * @returns the current animation group
  53080. */
  53081. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53082. var _this = this;
  53083. if (loop === void 0) { loop = false; }
  53084. if (speedRatio === void 0) { speedRatio = 1; }
  53085. if (this._isStarted || this._targetedAnimations.length === 0) {
  53086. return this;
  53087. }
  53088. var _loop_1 = function (targetedAnimation) {
  53089. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53090. animatable.onAnimationEnd = function () {
  53091. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53092. _this._checkAnimationGroupEnded(animatable);
  53093. };
  53094. this_1._animatables.push(animatable);
  53095. };
  53096. var this_1 = this;
  53097. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53098. var targetedAnimation = _a[_i];
  53099. _loop_1(targetedAnimation);
  53100. }
  53101. this._speedRatio = speedRatio;
  53102. this._isStarted = true;
  53103. return this;
  53104. };
  53105. /**
  53106. * Pause all animations
  53107. * @returns the animation group
  53108. */
  53109. AnimationGroup.prototype.pause = function () {
  53110. if (!this._isStarted) {
  53111. return this;
  53112. }
  53113. for (var index = 0; index < this._animatables.length; index++) {
  53114. var animatable = this._animatables[index];
  53115. animatable.pause();
  53116. }
  53117. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53118. return this;
  53119. };
  53120. /**
  53121. * Play all animations to initial state
  53122. * This function will start() the animations if they were not started or will restart() them if they were paused
  53123. * @param loop defines if animations must loop
  53124. * @returns the animation group
  53125. */
  53126. AnimationGroup.prototype.play = function (loop) {
  53127. // only if all animatables are ready and exist
  53128. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53129. if (loop !== undefined) {
  53130. for (var index = 0; index < this._animatables.length; index++) {
  53131. var animatable = this._animatables[index];
  53132. animatable.loopAnimation = loop;
  53133. }
  53134. }
  53135. this.restart();
  53136. }
  53137. else {
  53138. this.stop();
  53139. this.start(loop, this._speedRatio);
  53140. }
  53141. return this;
  53142. };
  53143. /**
  53144. * Reset all animations to initial state
  53145. * @returns the animation group
  53146. */
  53147. AnimationGroup.prototype.reset = function () {
  53148. if (!this._isStarted) {
  53149. return this;
  53150. }
  53151. for (var index = 0; index < this._animatables.length; index++) {
  53152. var animatable = this._animatables[index];
  53153. animatable.reset();
  53154. }
  53155. return this;
  53156. };
  53157. /**
  53158. * Restart animations from key 0
  53159. * @returns the animation group
  53160. */
  53161. AnimationGroup.prototype.restart = function () {
  53162. if (!this._isStarted) {
  53163. return this;
  53164. }
  53165. for (var index = 0; index < this._animatables.length; index++) {
  53166. var animatable = this._animatables[index];
  53167. animatable.restart();
  53168. }
  53169. return this;
  53170. };
  53171. /**
  53172. * Stop all animations
  53173. * @returns the animation group
  53174. */
  53175. AnimationGroup.prototype.stop = function () {
  53176. if (!this._isStarted) {
  53177. return this;
  53178. }
  53179. var list = this._animatables.slice();
  53180. for (var index = 0; index < list.length; index++) {
  53181. list[index].stop();
  53182. }
  53183. this._isStarted = false;
  53184. return this;
  53185. };
  53186. /**
  53187. * Set animation weight for all animatables
  53188. * @param weight defines the weight to use
  53189. * @return the animationGroup
  53190. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53191. */
  53192. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53193. for (var index = 0; index < this._animatables.length; index++) {
  53194. var animatable = this._animatables[index];
  53195. animatable.weight = weight;
  53196. }
  53197. return this;
  53198. };
  53199. /**
  53200. * Synchronize and normalize all animatables with a source animatable
  53201. * @param root defines the root animatable to synchronize with
  53202. * @return the animationGroup
  53203. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53204. */
  53205. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53206. for (var index = 0; index < this._animatables.length; index++) {
  53207. var animatable = this._animatables[index];
  53208. animatable.syncWith(root);
  53209. }
  53210. return this;
  53211. };
  53212. /**
  53213. * Goes to a specific frame in this animation group
  53214. * @param frame the frame number to go to
  53215. * @return the animationGroup
  53216. */
  53217. AnimationGroup.prototype.goToFrame = function (frame) {
  53218. if (!this._isStarted) {
  53219. return this;
  53220. }
  53221. for (var index = 0; index < this._animatables.length; index++) {
  53222. var animatable = this._animatables[index];
  53223. animatable.goToFrame(frame);
  53224. }
  53225. return this;
  53226. };
  53227. /**
  53228. * Dispose all associated resources
  53229. */
  53230. AnimationGroup.prototype.dispose = function () {
  53231. this._targetedAnimations = [];
  53232. this._animatables = [];
  53233. var index = this._scene.animationGroups.indexOf(this);
  53234. if (index > -1) {
  53235. this._scene.animationGroups.splice(index, 1);
  53236. }
  53237. };
  53238. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53239. // animatable should be taken out of the array
  53240. var idx = this._animatables.indexOf(animatable);
  53241. if (idx > -1) {
  53242. this._animatables.splice(idx, 1);
  53243. }
  53244. // all animatables were removed? animation group ended!
  53245. if (this._animatables.length === 0) {
  53246. this._isStarted = false;
  53247. this.onAnimationGroupEndObservable.notifyObservers(this);
  53248. }
  53249. };
  53250. // Statics
  53251. /**
  53252. * Returns a new AnimationGroup object parsed from the source provided.
  53253. * @param parsedAnimationGroup defines the source
  53254. * @param scene defines the scene that will receive the animationGroup
  53255. * @returns a new AnimationGroup
  53256. */
  53257. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53258. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53259. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53260. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53261. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53262. var id = targetedAnimation.targetId;
  53263. var targetNode = scene.getNodeByID(id);
  53264. if (targetNode != null)
  53265. animationGroup.addTargetedAnimation(animation, targetNode);
  53266. }
  53267. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  53268. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53269. return animationGroup;
  53270. };
  53271. /**
  53272. * Returns the string "AnimationGroup"
  53273. * @returns "AnimationGroup"
  53274. */
  53275. AnimationGroup.prototype.getClassName = function () {
  53276. return "AnimationGroup";
  53277. };
  53278. /**
  53279. * Creates a detailled string about the object
  53280. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53281. * @returns a string representing the object
  53282. */
  53283. AnimationGroup.prototype.toString = function (fullDetails) {
  53284. var ret = "Name: " + this.name;
  53285. ret += ", type: " + this.getClassName();
  53286. if (fullDetails) {
  53287. ret += ", from: " + this._from;
  53288. ret += ", to: " + this._to;
  53289. ret += ", isStarted: " + this._isStarted;
  53290. ret += ", speedRatio: " + this._speedRatio;
  53291. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53292. ret += ", animatables length: " + this._animatables;
  53293. }
  53294. return ret;
  53295. };
  53296. return AnimationGroup;
  53297. }());
  53298. BABYLON.AnimationGroup = AnimationGroup;
  53299. })(BABYLON || (BABYLON = {}));
  53300. //# sourceMappingURL=babylon.animationGroup.js.map
  53301. var BABYLON;
  53302. (function (BABYLON) {
  53303. // Static values to help the garbage collector
  53304. // Quaternion
  53305. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53306. // Vector3
  53307. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53308. // Vector2
  53309. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53310. // Size
  53311. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53312. // Color3
  53313. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53314. /**
  53315. * Defines a runtime animation
  53316. */
  53317. var RuntimeAnimation = /** @class */ (function () {
  53318. /**
  53319. * Create a new RuntimeAnimation object
  53320. * @param target defines the target of the animation
  53321. * @param animation defines the source animation object
  53322. * @param scene defines the hosting scene
  53323. * @param host defines the initiating Animatable
  53324. */
  53325. function RuntimeAnimation(target, animation, scene, host) {
  53326. var _this = this;
  53327. this._events = new Array();
  53328. /**
  53329. * The current frame of the runtime animation
  53330. */
  53331. this._currentFrame = 0;
  53332. /**
  53333. * The original value of the runtime animation
  53334. */
  53335. this._originalValue = new Array();
  53336. /**
  53337. * The offsets cache of the runtime animation
  53338. */
  53339. this._offsetsCache = {};
  53340. /**
  53341. * The high limits cache of the runtime animation
  53342. */
  53343. this._highLimitsCache = {};
  53344. /**
  53345. * Specifies if the runtime animation has been stopped
  53346. */
  53347. this._stopped = false;
  53348. /**
  53349. * The blending factor of the runtime animation
  53350. */
  53351. this._blendingFactor = 0;
  53352. /**
  53353. * The target path of the runtime animation
  53354. */
  53355. this._targetPath = "";
  53356. /**
  53357. * The weight of the runtime animation
  53358. */
  53359. this._weight = 1.0;
  53360. /**
  53361. * The ratio offset of the runtime animation
  53362. */
  53363. this._ratioOffset = 0;
  53364. /**
  53365. * The previous delay of the runtime animation
  53366. */
  53367. this._previousDelay = 0;
  53368. /**
  53369. * The previous ratio of the runtime animation
  53370. */
  53371. this._previousRatio = 0;
  53372. this._animation = animation;
  53373. this._target = target;
  53374. this._scene = scene;
  53375. this._host = host;
  53376. animation._runtimeAnimations.push(this);
  53377. // Cloning events locally
  53378. var events = animation.getEvents();
  53379. if (events && events.length > 0) {
  53380. events.forEach(function (e) {
  53381. _this._events.push(e._clone());
  53382. });
  53383. }
  53384. }
  53385. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53386. /**
  53387. * Gets the current frame of the runtime animation
  53388. */
  53389. get: function () {
  53390. return this._currentFrame;
  53391. },
  53392. enumerable: true,
  53393. configurable: true
  53394. });
  53395. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53396. /**
  53397. * Gets the weight of the runtime animation
  53398. */
  53399. get: function () {
  53400. return this._weight;
  53401. },
  53402. enumerable: true,
  53403. configurable: true
  53404. });
  53405. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53406. /**
  53407. * Gets the current value of the runtime animation
  53408. */
  53409. get: function () {
  53410. return this._currentValue;
  53411. },
  53412. enumerable: true,
  53413. configurable: true
  53414. });
  53415. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53416. /**
  53417. * Gets the target path of the runtime animation
  53418. */
  53419. get: function () {
  53420. return this._targetPath;
  53421. },
  53422. enumerable: true,
  53423. configurable: true
  53424. });
  53425. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53426. /**
  53427. * Gets the actual target of the runtime animation
  53428. */
  53429. get: function () {
  53430. return this._activeTarget;
  53431. },
  53432. enumerable: true,
  53433. configurable: true
  53434. });
  53435. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53436. /**
  53437. * Gets the animation from the runtime animation
  53438. */
  53439. get: function () {
  53440. return this._animation;
  53441. },
  53442. enumerable: true,
  53443. configurable: true
  53444. });
  53445. /**
  53446. * Resets the runtime animation to the beginning
  53447. * @param restoreOriginal defines whether to restore the target property to the original value
  53448. */
  53449. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53450. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53451. if (restoreOriginal) {
  53452. if (this._target instanceof Array) {
  53453. var index = 0;
  53454. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53455. var target = _a[_i];
  53456. if (this._originalValue[index] !== undefined) {
  53457. this._setValue(target, this._originalValue[index], -1);
  53458. }
  53459. index++;
  53460. }
  53461. }
  53462. else {
  53463. if (this._originalValue[0] !== undefined) {
  53464. this._setValue(this._target, this._originalValue[0], -1);
  53465. }
  53466. }
  53467. }
  53468. this._offsetsCache = {};
  53469. this._highLimitsCache = {};
  53470. this._currentFrame = 0;
  53471. this._blendingFactor = 0;
  53472. this._originalValue = new Array();
  53473. // Events
  53474. for (var index = 0; index < this._events.length; index++) {
  53475. this._events[index].isDone = false;
  53476. }
  53477. };
  53478. /**
  53479. * Specifies if the runtime animation is stopped
  53480. * @returns Boolean specifying if the runtime animation is stopped
  53481. */
  53482. RuntimeAnimation.prototype.isStopped = function () {
  53483. return this._stopped;
  53484. };
  53485. /**
  53486. * Disposes of the runtime animation
  53487. */
  53488. RuntimeAnimation.prototype.dispose = function () {
  53489. var index = this._animation.runtimeAnimations.indexOf(this);
  53490. if (index > -1) {
  53491. this._animation.runtimeAnimations.splice(index, 1);
  53492. }
  53493. };
  53494. /**
  53495. * Interpolates the animation from the current frame
  53496. * @param currentFrame The frame to interpolate the animation to
  53497. * @param repeatCount The number of times that the animation should loop
  53498. * @param loopMode The type of looping mode to use
  53499. * @param offsetValue Animation offset value
  53500. * @param highLimitValue The high limit value
  53501. * @returns The interpolated value
  53502. */
  53503. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53504. this._currentFrame = currentFrame;
  53505. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53506. this._workValue = BABYLON.Matrix.Zero();
  53507. }
  53508. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53509. };
  53510. /**
  53511. * Apply the interpolated value to the target
  53512. * @param currentValue defines the value computed by the animation
  53513. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53514. */
  53515. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53516. if (weight === void 0) { weight = 1.0; }
  53517. if (this._target instanceof Array) {
  53518. var index = 0;
  53519. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53520. var target = _a[_i];
  53521. this._setValue(target, currentValue, weight, index);
  53522. index++;
  53523. }
  53524. }
  53525. else {
  53526. this._setValue(this._target, currentValue, weight);
  53527. }
  53528. };
  53529. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53530. if (targetIndex === void 0) { targetIndex = 0; }
  53531. // Set value
  53532. var path;
  53533. var destination;
  53534. var targetPropertyPath = this._animation.targetPropertyPath;
  53535. if (targetPropertyPath.length > 1) {
  53536. var property = target[targetPropertyPath[0]];
  53537. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53538. property = property[targetPropertyPath[index]];
  53539. }
  53540. path = targetPropertyPath[targetPropertyPath.length - 1];
  53541. destination = property;
  53542. }
  53543. else {
  53544. path = targetPropertyPath[0];
  53545. destination = target;
  53546. }
  53547. this._targetPath = path;
  53548. this._activeTarget = destination;
  53549. this._weight = weight;
  53550. if (this._originalValue[targetIndex] === undefined) {
  53551. var originalValue = void 0;
  53552. if (destination.getRestPose && path === "_matrix") { // For bones
  53553. originalValue = destination.getRestPose();
  53554. }
  53555. else {
  53556. originalValue = destination[path];
  53557. }
  53558. if (originalValue && originalValue.clone) {
  53559. this._originalValue[targetIndex] = originalValue.clone();
  53560. }
  53561. else {
  53562. this._originalValue[targetIndex] = originalValue;
  53563. }
  53564. }
  53565. // Blending
  53566. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53567. if (enableBlending && this._blendingFactor <= 1.0) {
  53568. if (!this._originalBlendValue) {
  53569. var originalValue = destination[path];
  53570. if (originalValue.clone) {
  53571. this._originalBlendValue = originalValue.clone();
  53572. }
  53573. else {
  53574. this._originalBlendValue = originalValue;
  53575. }
  53576. }
  53577. if (this._originalBlendValue.m) { // Matrix
  53578. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53579. if (this._currentValue) {
  53580. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53581. }
  53582. else {
  53583. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53584. }
  53585. }
  53586. else {
  53587. if (this._currentValue) {
  53588. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53589. }
  53590. else {
  53591. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53592. }
  53593. }
  53594. }
  53595. else {
  53596. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53597. }
  53598. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53599. this._blendingFactor += blendingSpeed;
  53600. }
  53601. else {
  53602. this._currentValue = currentValue;
  53603. }
  53604. if (weight !== -1.0) {
  53605. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53606. }
  53607. else {
  53608. destination[path] = this._currentValue;
  53609. }
  53610. if (target.markAsDirty) {
  53611. target.markAsDirty(this._animation.targetProperty);
  53612. }
  53613. };
  53614. /**
  53615. * Gets the loop pmode of the runtime animation
  53616. * @returns Loop Mode
  53617. */
  53618. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53619. if (this._target && this._target.animationPropertiesOverride) {
  53620. return this._target.animationPropertiesOverride.loopMode;
  53621. }
  53622. return this._animation.loopMode;
  53623. };
  53624. /**
  53625. * Move the current animation to a given frame
  53626. * @param frame defines the frame to move to
  53627. */
  53628. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53629. var keys = this._animation.getKeys();
  53630. if (frame < keys[0].frame) {
  53631. frame = keys[0].frame;
  53632. }
  53633. else if (frame > keys[keys.length - 1].frame) {
  53634. frame = keys[keys.length - 1].frame;
  53635. }
  53636. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53637. this.setValue(currentValue, -1);
  53638. };
  53639. /**
  53640. * @hidden Internal use only
  53641. */
  53642. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53643. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53644. this._ratioOffset = this._previousRatio - newRatio;
  53645. };
  53646. /**
  53647. * Execute the current animation
  53648. * @param delay defines the delay to add to the current frame
  53649. * @param from defines the lower bound of the animation range
  53650. * @param to defines the upper bound of the animation range
  53651. * @param loop defines if the current animation must loop
  53652. * @param speedRatio defines the current speed ratio
  53653. * @param weight defines the weight of the animation (default is -1 so no weight)
  53654. * @returns a boolean indicating if the animation is running
  53655. */
  53656. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53657. if (weight === void 0) { weight = -1.0; }
  53658. var targetPropertyPath = this._animation.targetPropertyPath;
  53659. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53660. this._stopped = true;
  53661. return false;
  53662. }
  53663. var returnValue = true;
  53664. var keys = this._animation.getKeys();
  53665. // Adding a start key at frame 0 if missing
  53666. if (keys[0].frame !== 0) {
  53667. var newKey = { frame: 0, value: keys[0].value };
  53668. keys.splice(0, 0, newKey);
  53669. }
  53670. // Adding a duplicate key when there is only one key at frame zero
  53671. else if (keys.length === 1) {
  53672. var newKey = { frame: 0.001, value: keys[0].value };
  53673. keys.push(newKey);
  53674. }
  53675. // Check limits
  53676. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53677. from = keys[0].frame;
  53678. }
  53679. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53680. to = keys[keys.length - 1].frame;
  53681. }
  53682. //to and from cannot be the same key
  53683. if (from === to) {
  53684. if (from > keys[0].frame) {
  53685. from--;
  53686. }
  53687. else if (to < keys[keys.length - 1].frame) {
  53688. to++;
  53689. }
  53690. }
  53691. // Compute ratio
  53692. var range = to - from;
  53693. var offsetValue;
  53694. // ratio represents the frame delta between from and to
  53695. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53696. var highLimitValue = 0;
  53697. this._previousDelay = delay;
  53698. this._previousRatio = ratio;
  53699. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53700. returnValue = false;
  53701. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53702. }
  53703. else {
  53704. // Get max value if required
  53705. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53706. var keyOffset = to.toString() + from.toString();
  53707. if (!this._offsetsCache[keyOffset]) {
  53708. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53709. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53710. switch (this._animation.dataType) {
  53711. // Float
  53712. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53713. this._offsetsCache[keyOffset] = toValue - fromValue;
  53714. break;
  53715. // Quaternion
  53716. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53717. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53718. break;
  53719. // Vector3
  53720. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53721. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53722. // Vector2
  53723. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53724. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53725. // Size
  53726. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53727. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53728. // Color3
  53729. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53730. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53731. default:
  53732. break;
  53733. }
  53734. this._highLimitsCache[keyOffset] = toValue;
  53735. }
  53736. highLimitValue = this._highLimitsCache[keyOffset];
  53737. offsetValue = this._offsetsCache[keyOffset];
  53738. }
  53739. }
  53740. if (offsetValue === undefined) {
  53741. switch (this._animation.dataType) {
  53742. // Float
  53743. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53744. offsetValue = 0;
  53745. break;
  53746. // Quaternion
  53747. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53748. offsetValue = _staticOffsetValueQuaternion;
  53749. break;
  53750. // Vector3
  53751. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53752. offsetValue = _staticOffsetValueVector3;
  53753. break;
  53754. // Vector2
  53755. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53756. offsetValue = _staticOffsetValueVector2;
  53757. break;
  53758. // Size
  53759. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53760. offsetValue = _staticOffsetValueSize;
  53761. break;
  53762. // Color3
  53763. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53764. offsetValue = _staticOffsetValueColor3;
  53765. }
  53766. }
  53767. // Compute value
  53768. var repeatCount = (ratio / range) >> 0;
  53769. var currentFrame = returnValue ? from + ratio % range : to;
  53770. // Need to normalize?
  53771. if (this._host && this._host.syncRoot) {
  53772. var syncRoot = this._host.syncRoot;
  53773. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53774. currentFrame = from + (to - from) * hostNormalizedFrame;
  53775. }
  53776. // Reset events if looping
  53777. var events = this._events;
  53778. if (range > 0 && this.currentFrame > currentFrame ||
  53779. range < 0 && this.currentFrame < currentFrame) {
  53780. // Need to reset animation events
  53781. for (var index = 0; index < events.length; index++) {
  53782. if (!events[index].onlyOnce) {
  53783. // reset event, the animation is looping
  53784. events[index].isDone = false;
  53785. }
  53786. }
  53787. }
  53788. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53789. // Set value
  53790. this.setValue(currentValue, weight);
  53791. // Check events
  53792. for (var index = 0; index < events.length; index++) {
  53793. // Make sure current frame has passed event frame and that event frame is within the current range
  53794. // Also, handle both forward and reverse animations
  53795. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53796. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53797. var event = events[index];
  53798. if (!event.isDone) {
  53799. // If event should be done only once, remove it.
  53800. if (event.onlyOnce) {
  53801. events.splice(index, 1);
  53802. index--;
  53803. }
  53804. event.isDone = true;
  53805. event.action(currentFrame);
  53806. } // Don't do anything if the event has already be done.
  53807. }
  53808. }
  53809. if (!returnValue) {
  53810. this._stopped = true;
  53811. }
  53812. return returnValue;
  53813. };
  53814. return RuntimeAnimation;
  53815. }());
  53816. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53817. })(BABYLON || (BABYLON = {}));
  53818. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53819. var BABYLON;
  53820. (function (BABYLON) {
  53821. /**
  53822. * Class used to store an actual running animation
  53823. */
  53824. var Animatable = /** @class */ (function () {
  53825. /**
  53826. * Creates a new Animatable
  53827. * @param scene defines the hosting scene
  53828. * @param target defines the target object
  53829. * @param fromFrame defines the starting frame number (default is 0)
  53830. * @param toFrame defines the ending frame number (default is 100)
  53831. * @param loopAnimation defines if the animation must loop (default is false)
  53832. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53833. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53834. * @param animations defines a group of animation to add to the new Animatable
  53835. */
  53836. function Animatable(scene,
  53837. /** defines the target object */
  53838. target,
  53839. /** defines the starting frame number (default is 0) */
  53840. fromFrame,
  53841. /** defines the ending frame number (default is 100) */
  53842. toFrame,
  53843. /** defines if the animation must loop (default is false) */
  53844. loopAnimation, speedRatio,
  53845. /** defines a callback to call when animation ends if it is not looping */
  53846. onAnimationEnd, animations) {
  53847. if (fromFrame === void 0) { fromFrame = 0; }
  53848. if (toFrame === void 0) { toFrame = 100; }
  53849. if (loopAnimation === void 0) { loopAnimation = false; }
  53850. if (speedRatio === void 0) { speedRatio = 1.0; }
  53851. this.target = target;
  53852. this.fromFrame = fromFrame;
  53853. this.toFrame = toFrame;
  53854. this.loopAnimation = loopAnimation;
  53855. this.onAnimationEnd = onAnimationEnd;
  53856. this._localDelayOffset = null;
  53857. this._pausedDelay = null;
  53858. this._runtimeAnimations = new Array();
  53859. this._paused = false;
  53860. this._speedRatio = 1;
  53861. this._weight = -1.0;
  53862. /**
  53863. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53864. * This will only apply for non looping animation (default is true)
  53865. */
  53866. this.disposeOnEnd = true;
  53867. /**
  53868. * Gets a boolean indicating if the animation has started
  53869. */
  53870. this.animationStarted = false;
  53871. /**
  53872. * Observer raised when the animation ends
  53873. */
  53874. this.onAnimationEndObservable = new BABYLON.Observable();
  53875. this._scene = scene;
  53876. if (animations) {
  53877. this.appendAnimations(target, animations);
  53878. }
  53879. this._speedRatio = speedRatio;
  53880. scene._activeAnimatables.push(this);
  53881. }
  53882. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53883. /**
  53884. * Gets the root Animatable used to synchronize and normalize animations
  53885. */
  53886. get: function () {
  53887. return this._syncRoot;
  53888. },
  53889. enumerable: true,
  53890. configurable: true
  53891. });
  53892. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53893. /**
  53894. * Gets the current frame of the first RuntimeAnimation
  53895. * Used to synchronize Animatables
  53896. */
  53897. get: function () {
  53898. if (this._runtimeAnimations.length === 0) {
  53899. return 0;
  53900. }
  53901. return this._runtimeAnimations[0].currentFrame;
  53902. },
  53903. enumerable: true,
  53904. configurable: true
  53905. });
  53906. Object.defineProperty(Animatable.prototype, "weight", {
  53907. /**
  53908. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53909. */
  53910. get: function () {
  53911. return this._weight;
  53912. },
  53913. set: function (value) {
  53914. if (value === -1) { // -1 is ok and means no weight
  53915. this._weight = -1;
  53916. return;
  53917. }
  53918. // Else weight must be in [0, 1] range
  53919. this._weight = Math.min(Math.max(value, 0), 1.0);
  53920. },
  53921. enumerable: true,
  53922. configurable: true
  53923. });
  53924. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53925. /**
  53926. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53927. */
  53928. get: function () {
  53929. return this._speedRatio;
  53930. },
  53931. set: function (value) {
  53932. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53933. var animation = this._runtimeAnimations[index];
  53934. animation._prepareForSpeedRatioChange(value);
  53935. }
  53936. this._speedRatio = value;
  53937. },
  53938. enumerable: true,
  53939. configurable: true
  53940. });
  53941. // Methods
  53942. /**
  53943. * Synchronize and normalize current Animatable with a source Animatable
  53944. * This is useful when using animation weights and when animations are not of the same length
  53945. * @param root defines the root Animatable to synchronize with
  53946. * @returns the current Animatable
  53947. */
  53948. Animatable.prototype.syncWith = function (root) {
  53949. this._syncRoot = root;
  53950. if (root) {
  53951. // Make sure this animatable will animate after the root
  53952. var index = this._scene._activeAnimatables.indexOf(this);
  53953. if (index > -1) {
  53954. this._scene._activeAnimatables.splice(index, 1);
  53955. this._scene._activeAnimatables.push(this);
  53956. }
  53957. }
  53958. return this;
  53959. };
  53960. /**
  53961. * Gets the list of runtime animations
  53962. * @returns an array of RuntimeAnimation
  53963. */
  53964. Animatable.prototype.getAnimations = function () {
  53965. return this._runtimeAnimations;
  53966. };
  53967. /**
  53968. * Adds more animations to the current animatable
  53969. * @param target defines the target of the animations
  53970. * @param animations defines the new animations to add
  53971. */
  53972. Animatable.prototype.appendAnimations = function (target, animations) {
  53973. for (var index = 0; index < animations.length; index++) {
  53974. var animation = animations[index];
  53975. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  53976. }
  53977. };
  53978. /**
  53979. * Gets the source animation for a specific property
  53980. * @param property defines the propertyu to look for
  53981. * @returns null or the source animation for the given property
  53982. */
  53983. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  53984. var runtimeAnimations = this._runtimeAnimations;
  53985. for (var index = 0; index < runtimeAnimations.length; index++) {
  53986. if (runtimeAnimations[index].animation.targetProperty === property) {
  53987. return runtimeAnimations[index].animation;
  53988. }
  53989. }
  53990. return null;
  53991. };
  53992. /**
  53993. * Gets the runtime animation for a specific property
  53994. * @param property defines the propertyu to look for
  53995. * @returns null or the runtime animation for the given property
  53996. */
  53997. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  53998. var runtimeAnimations = this._runtimeAnimations;
  53999. for (var index = 0; index < runtimeAnimations.length; index++) {
  54000. if (runtimeAnimations[index].animation.targetProperty === property) {
  54001. return runtimeAnimations[index];
  54002. }
  54003. }
  54004. return null;
  54005. };
  54006. /**
  54007. * Resets the animatable to its original state
  54008. */
  54009. Animatable.prototype.reset = function () {
  54010. var runtimeAnimations = this._runtimeAnimations;
  54011. for (var index = 0; index < runtimeAnimations.length; index++) {
  54012. runtimeAnimations[index].reset(true);
  54013. }
  54014. this._localDelayOffset = null;
  54015. this._pausedDelay = null;
  54016. };
  54017. /**
  54018. * Allows the animatable to blend with current running animations
  54019. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54020. * @param blendingSpeed defines the blending speed to use
  54021. */
  54022. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54023. var runtimeAnimations = this._runtimeAnimations;
  54024. for (var index = 0; index < runtimeAnimations.length; index++) {
  54025. runtimeAnimations[index].animation.enableBlending = true;
  54026. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54027. }
  54028. };
  54029. /**
  54030. * Disable animation blending
  54031. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54032. */
  54033. Animatable.prototype.disableBlending = function () {
  54034. var runtimeAnimations = this._runtimeAnimations;
  54035. for (var index = 0; index < runtimeAnimations.length; index++) {
  54036. runtimeAnimations[index].animation.enableBlending = false;
  54037. }
  54038. };
  54039. /**
  54040. * Jump directly to a given frame
  54041. * @param frame defines the frame to jump to
  54042. */
  54043. Animatable.prototype.goToFrame = function (frame) {
  54044. var runtimeAnimations = this._runtimeAnimations;
  54045. if (runtimeAnimations[0]) {
  54046. var fps = runtimeAnimations[0].animation.framePerSecond;
  54047. var currentFrame = runtimeAnimations[0].currentFrame;
  54048. var adjustTime = frame - currentFrame;
  54049. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54050. if (this._localDelayOffset === null) {
  54051. this._localDelayOffset = 0;
  54052. }
  54053. this._localDelayOffset -= delay;
  54054. }
  54055. for (var index = 0; index < runtimeAnimations.length; index++) {
  54056. runtimeAnimations[index].goToFrame(frame);
  54057. }
  54058. };
  54059. /**
  54060. * Pause the animation
  54061. */
  54062. Animatable.prototype.pause = function () {
  54063. if (this._paused) {
  54064. return;
  54065. }
  54066. this._paused = true;
  54067. };
  54068. /**
  54069. * Restart the animation
  54070. */
  54071. Animatable.prototype.restart = function () {
  54072. this._paused = false;
  54073. };
  54074. Animatable.prototype._raiseOnAnimationEnd = function () {
  54075. if (this.onAnimationEnd) {
  54076. this.onAnimationEnd();
  54077. }
  54078. this.onAnimationEndObservable.notifyObservers(this);
  54079. };
  54080. /**
  54081. * Stop and delete the current animation
  54082. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54083. * @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)
  54084. */
  54085. Animatable.prototype.stop = function (animationName, targetMask) {
  54086. if (animationName || targetMask) {
  54087. var idx = this._scene._activeAnimatables.indexOf(this);
  54088. if (idx > -1) {
  54089. var runtimeAnimations = this._runtimeAnimations;
  54090. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54091. var runtimeAnimation = runtimeAnimations[index];
  54092. if (animationName && runtimeAnimation.animation.name != animationName) {
  54093. continue;
  54094. }
  54095. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54096. continue;
  54097. }
  54098. runtimeAnimation.dispose();
  54099. runtimeAnimations.splice(index, 1);
  54100. }
  54101. if (runtimeAnimations.length == 0) {
  54102. this._scene._activeAnimatables.splice(idx, 1);
  54103. this._raiseOnAnimationEnd();
  54104. }
  54105. }
  54106. }
  54107. else {
  54108. var index = this._scene._activeAnimatables.indexOf(this);
  54109. if (index > -1) {
  54110. this._scene._activeAnimatables.splice(index, 1);
  54111. var runtimeAnimations = this._runtimeAnimations;
  54112. for (var index = 0; index < runtimeAnimations.length; index++) {
  54113. runtimeAnimations[index].dispose();
  54114. }
  54115. this._raiseOnAnimationEnd();
  54116. }
  54117. }
  54118. };
  54119. /**
  54120. * Wait asynchronously for the animation to end
  54121. * @returns a promise which will be fullfilled when the animation ends
  54122. */
  54123. Animatable.prototype.waitAsync = function () {
  54124. var _this = this;
  54125. return new Promise(function (resolve, reject) {
  54126. _this.onAnimationEndObservable.add(function () {
  54127. resolve(_this);
  54128. }, undefined, undefined, _this, true);
  54129. });
  54130. };
  54131. /** @hidden */
  54132. Animatable.prototype._animate = function (delay) {
  54133. if (this._paused) {
  54134. this.animationStarted = false;
  54135. if (this._pausedDelay === null) {
  54136. this._pausedDelay = delay;
  54137. }
  54138. return true;
  54139. }
  54140. if (this._localDelayOffset === null) {
  54141. this._localDelayOffset = delay;
  54142. this._pausedDelay = null;
  54143. }
  54144. else if (this._pausedDelay !== null) {
  54145. this._localDelayOffset += delay - this._pausedDelay;
  54146. this._pausedDelay = null;
  54147. }
  54148. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54149. return true;
  54150. }
  54151. // Animating
  54152. var running = false;
  54153. var runtimeAnimations = this._runtimeAnimations;
  54154. var index;
  54155. for (index = 0; index < runtimeAnimations.length; index++) {
  54156. var animation = runtimeAnimations[index];
  54157. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54158. running = running || isRunning;
  54159. }
  54160. this.animationStarted = running;
  54161. if (!running) {
  54162. if (this.disposeOnEnd) {
  54163. // Remove from active animatables
  54164. index = this._scene._activeAnimatables.indexOf(this);
  54165. this._scene._activeAnimatables.splice(index, 1);
  54166. // Dispose all runtime animations
  54167. for (index = 0; index < runtimeAnimations.length; index++) {
  54168. runtimeAnimations[index].dispose();
  54169. }
  54170. }
  54171. this._raiseOnAnimationEnd();
  54172. if (this.disposeOnEnd) {
  54173. this.onAnimationEnd = null;
  54174. this.onAnimationEndObservable.clear();
  54175. }
  54176. }
  54177. return running;
  54178. };
  54179. return Animatable;
  54180. }());
  54181. BABYLON.Animatable = Animatable;
  54182. })(BABYLON || (BABYLON = {}));
  54183. //# sourceMappingURL=babylon.animatable.js.map
  54184. var BABYLON;
  54185. (function (BABYLON) {
  54186. /**
  54187. * Base class used for every default easing function.
  54188. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54189. */
  54190. var EasingFunction = /** @class */ (function () {
  54191. function EasingFunction() {
  54192. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54193. }
  54194. /**
  54195. * Sets the easing mode of the current function.
  54196. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54197. */
  54198. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54199. var n = Math.min(Math.max(easingMode, 0), 2);
  54200. this._easingMode = n;
  54201. };
  54202. /**
  54203. * Gets the current easing mode.
  54204. * @returns the easing mode
  54205. */
  54206. EasingFunction.prototype.getEasingMode = function () {
  54207. return this._easingMode;
  54208. };
  54209. /**
  54210. * @hidden
  54211. */
  54212. EasingFunction.prototype.easeInCore = function (gradient) {
  54213. throw new Error('You must implement this method');
  54214. };
  54215. /**
  54216. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54217. * of the easing function.
  54218. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54219. * @returns the corresponding value on the curve defined by the easing function
  54220. */
  54221. EasingFunction.prototype.ease = function (gradient) {
  54222. switch (this._easingMode) {
  54223. case EasingFunction.EASINGMODE_EASEIN:
  54224. return this.easeInCore(gradient);
  54225. case EasingFunction.EASINGMODE_EASEOUT:
  54226. return (1 - this.easeInCore(1 - gradient));
  54227. }
  54228. if (gradient >= 0.5) {
  54229. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54230. }
  54231. return (this.easeInCore(gradient * 2) * 0.5);
  54232. };
  54233. /**
  54234. * Interpolation follows the mathematical formula associated with the easing function.
  54235. */
  54236. EasingFunction.EASINGMODE_EASEIN = 0;
  54237. /**
  54238. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54239. */
  54240. EasingFunction.EASINGMODE_EASEOUT = 1;
  54241. /**
  54242. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54243. */
  54244. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54245. return EasingFunction;
  54246. }());
  54247. BABYLON.EasingFunction = EasingFunction;
  54248. /**
  54249. * Easing function with a circle shape (see link below).
  54250. * @see https://easings.net/#easeInCirc
  54251. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54252. */
  54253. var CircleEase = /** @class */ (function (_super) {
  54254. __extends(CircleEase, _super);
  54255. function CircleEase() {
  54256. return _super !== null && _super.apply(this, arguments) || this;
  54257. }
  54258. /** @hidden */
  54259. CircleEase.prototype.easeInCore = function (gradient) {
  54260. gradient = Math.max(0, Math.min(1, gradient));
  54261. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54262. };
  54263. return CircleEase;
  54264. }(EasingFunction));
  54265. BABYLON.CircleEase = CircleEase;
  54266. /**
  54267. * Easing function with a ease back shape (see link below).
  54268. * @see https://easings.net/#easeInBack
  54269. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54270. */
  54271. var BackEase = /** @class */ (function (_super) {
  54272. __extends(BackEase, _super);
  54273. /**
  54274. * Instantiates a back ease easing
  54275. * @see https://easings.net/#easeInBack
  54276. * @param amplitude Defines the amplitude of the function
  54277. */
  54278. function BackEase(
  54279. /** Defines the amplitude of the function */
  54280. amplitude) {
  54281. if (amplitude === void 0) { amplitude = 1; }
  54282. var _this = _super.call(this) || this;
  54283. _this.amplitude = amplitude;
  54284. return _this;
  54285. }
  54286. /** @hidden */
  54287. BackEase.prototype.easeInCore = function (gradient) {
  54288. var num = Math.max(0, this.amplitude);
  54289. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54290. };
  54291. return BackEase;
  54292. }(EasingFunction));
  54293. BABYLON.BackEase = BackEase;
  54294. /**
  54295. * Easing function with a bouncing shape (see link below).
  54296. * @see https://easings.net/#easeInBounce
  54297. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54298. */
  54299. var BounceEase = /** @class */ (function (_super) {
  54300. __extends(BounceEase, _super);
  54301. /**
  54302. * Instantiates a bounce easing
  54303. * @see https://easings.net/#easeInBounce
  54304. * @param bounces Defines the number of bounces
  54305. * @param bounciness Defines the amplitude of the bounce
  54306. */
  54307. function BounceEase(
  54308. /** Defines the number of bounces */
  54309. bounces,
  54310. /** Defines the amplitude of the bounce */
  54311. bounciness) {
  54312. if (bounces === void 0) { bounces = 3; }
  54313. if (bounciness === void 0) { bounciness = 2; }
  54314. var _this = _super.call(this) || this;
  54315. _this.bounces = bounces;
  54316. _this.bounciness = bounciness;
  54317. return _this;
  54318. }
  54319. /** @hidden */
  54320. BounceEase.prototype.easeInCore = function (gradient) {
  54321. var y = Math.max(0.0, this.bounces);
  54322. var bounciness = this.bounciness;
  54323. if (bounciness <= 1.0) {
  54324. bounciness = 1.001;
  54325. }
  54326. var num9 = Math.pow(bounciness, y);
  54327. var num5 = 1.0 - bounciness;
  54328. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54329. var num15 = gradient * num4;
  54330. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54331. var num3 = Math.floor(num65);
  54332. var num13 = num3 + 1.0;
  54333. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54334. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54335. var num7 = (num8 + num12) * 0.5;
  54336. var num6 = gradient - num7;
  54337. var num2 = num7 - num8;
  54338. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54339. };
  54340. return BounceEase;
  54341. }(EasingFunction));
  54342. BABYLON.BounceEase = BounceEase;
  54343. /**
  54344. * Easing function with a power of 3 shape (see link below).
  54345. * @see https://easings.net/#easeInCubic
  54346. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54347. */
  54348. var CubicEase = /** @class */ (function (_super) {
  54349. __extends(CubicEase, _super);
  54350. function CubicEase() {
  54351. return _super !== null && _super.apply(this, arguments) || this;
  54352. }
  54353. /** @hidden */
  54354. CubicEase.prototype.easeInCore = function (gradient) {
  54355. return (gradient * gradient * gradient);
  54356. };
  54357. return CubicEase;
  54358. }(EasingFunction));
  54359. BABYLON.CubicEase = CubicEase;
  54360. /**
  54361. * Easing function with an elastic shape (see link below).
  54362. * @see https://easings.net/#easeInElastic
  54363. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54364. */
  54365. var ElasticEase = /** @class */ (function (_super) {
  54366. __extends(ElasticEase, _super);
  54367. /**
  54368. * Instantiates an elastic easing function
  54369. * @see https://easings.net/#easeInElastic
  54370. * @param oscillations Defines the number of oscillations
  54371. * @param springiness Defines the amplitude of the oscillations
  54372. */
  54373. function ElasticEase(
  54374. /** Defines the number of oscillations*/
  54375. oscillations,
  54376. /** Defines the amplitude of the oscillations*/
  54377. springiness) {
  54378. if (oscillations === void 0) { oscillations = 3; }
  54379. if (springiness === void 0) { springiness = 3; }
  54380. var _this = _super.call(this) || this;
  54381. _this.oscillations = oscillations;
  54382. _this.springiness = springiness;
  54383. return _this;
  54384. }
  54385. /** @hidden */
  54386. ElasticEase.prototype.easeInCore = function (gradient) {
  54387. var num2;
  54388. var num3 = Math.max(0.0, this.oscillations);
  54389. var num = Math.max(0.0, this.springiness);
  54390. if (num == 0) {
  54391. num2 = gradient;
  54392. }
  54393. else {
  54394. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54395. }
  54396. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54397. };
  54398. return ElasticEase;
  54399. }(EasingFunction));
  54400. BABYLON.ElasticEase = ElasticEase;
  54401. /**
  54402. * Easing function with an exponential shape (see link below).
  54403. * @see https://easings.net/#easeInExpo
  54404. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54405. */
  54406. var ExponentialEase = /** @class */ (function (_super) {
  54407. __extends(ExponentialEase, _super);
  54408. /**
  54409. * Instantiates an exponential easing function
  54410. * @see https://easings.net/#easeInExpo
  54411. * @param exponent Defines the exponent of the function
  54412. */
  54413. function ExponentialEase(
  54414. /** Defines the exponent of the function */
  54415. exponent) {
  54416. if (exponent === void 0) { exponent = 2; }
  54417. var _this = _super.call(this) || this;
  54418. _this.exponent = exponent;
  54419. return _this;
  54420. }
  54421. /** @hidden */
  54422. ExponentialEase.prototype.easeInCore = function (gradient) {
  54423. if (this.exponent <= 0) {
  54424. return gradient;
  54425. }
  54426. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54427. };
  54428. return ExponentialEase;
  54429. }(EasingFunction));
  54430. BABYLON.ExponentialEase = ExponentialEase;
  54431. /**
  54432. * Easing function with a power shape (see link below).
  54433. * @see https://easings.net/#easeInQuad
  54434. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54435. */
  54436. var PowerEase = /** @class */ (function (_super) {
  54437. __extends(PowerEase, _super);
  54438. /**
  54439. * Instantiates an power base easing function
  54440. * @see https://easings.net/#easeInQuad
  54441. * @param power Defines the power of the function
  54442. */
  54443. function PowerEase(
  54444. /** Defines the power of the function */
  54445. power) {
  54446. if (power === void 0) { power = 2; }
  54447. var _this = _super.call(this) || this;
  54448. _this.power = power;
  54449. return _this;
  54450. }
  54451. /** @hidden */
  54452. PowerEase.prototype.easeInCore = function (gradient) {
  54453. var y = Math.max(0.0, this.power);
  54454. return Math.pow(gradient, y);
  54455. };
  54456. return PowerEase;
  54457. }(EasingFunction));
  54458. BABYLON.PowerEase = PowerEase;
  54459. /**
  54460. * Easing function with a power of 2 shape (see link below).
  54461. * @see https://easings.net/#easeInQuad
  54462. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54463. */
  54464. var QuadraticEase = /** @class */ (function (_super) {
  54465. __extends(QuadraticEase, _super);
  54466. function QuadraticEase() {
  54467. return _super !== null && _super.apply(this, arguments) || this;
  54468. }
  54469. /** @hidden */
  54470. QuadraticEase.prototype.easeInCore = function (gradient) {
  54471. return (gradient * gradient);
  54472. };
  54473. return QuadraticEase;
  54474. }(EasingFunction));
  54475. BABYLON.QuadraticEase = QuadraticEase;
  54476. /**
  54477. * Easing function with a power of 4 shape (see link below).
  54478. * @see https://easings.net/#easeInQuart
  54479. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54480. */
  54481. var QuarticEase = /** @class */ (function (_super) {
  54482. __extends(QuarticEase, _super);
  54483. function QuarticEase() {
  54484. return _super !== null && _super.apply(this, arguments) || this;
  54485. }
  54486. /** @hidden */
  54487. QuarticEase.prototype.easeInCore = function (gradient) {
  54488. return (gradient * gradient * gradient * gradient);
  54489. };
  54490. return QuarticEase;
  54491. }(EasingFunction));
  54492. BABYLON.QuarticEase = QuarticEase;
  54493. /**
  54494. * Easing function with a power of 5 shape (see link below).
  54495. * @see https://easings.net/#easeInQuint
  54496. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54497. */
  54498. var QuinticEase = /** @class */ (function (_super) {
  54499. __extends(QuinticEase, _super);
  54500. function QuinticEase() {
  54501. return _super !== null && _super.apply(this, arguments) || this;
  54502. }
  54503. /** @hidden */
  54504. QuinticEase.prototype.easeInCore = function (gradient) {
  54505. return (gradient * gradient * gradient * gradient * gradient);
  54506. };
  54507. return QuinticEase;
  54508. }(EasingFunction));
  54509. BABYLON.QuinticEase = QuinticEase;
  54510. /**
  54511. * Easing function with a sin shape (see link below).
  54512. * @see https://easings.net/#easeInSine
  54513. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54514. */
  54515. var SineEase = /** @class */ (function (_super) {
  54516. __extends(SineEase, _super);
  54517. function SineEase() {
  54518. return _super !== null && _super.apply(this, arguments) || this;
  54519. }
  54520. /** @hidden */
  54521. SineEase.prototype.easeInCore = function (gradient) {
  54522. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54523. };
  54524. return SineEase;
  54525. }(EasingFunction));
  54526. BABYLON.SineEase = SineEase;
  54527. /**
  54528. * Easing function with a bezier shape (see link below).
  54529. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54530. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54531. */
  54532. var BezierCurveEase = /** @class */ (function (_super) {
  54533. __extends(BezierCurveEase, _super);
  54534. /**
  54535. * Instantiates a bezier function
  54536. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54537. * @param x1 Defines the x component of the start tangent in the bezier curve
  54538. * @param y1 Defines the y component of the start tangent in the bezier curve
  54539. * @param x2 Defines the x component of the end tangent in the bezier curve
  54540. * @param y2 Defines the y component of the end tangent in the bezier curve
  54541. */
  54542. function BezierCurveEase(
  54543. /** Defines the x component of the start tangent in the bezier curve */
  54544. x1,
  54545. /** Defines the y component of the start tangent in the bezier curve */
  54546. y1,
  54547. /** Defines the x component of the end tangent in the bezier curve */
  54548. x2,
  54549. /** Defines the y component of the end tangent in the bezier curve */
  54550. y2) {
  54551. if (x1 === void 0) { x1 = 0; }
  54552. if (y1 === void 0) { y1 = 0; }
  54553. if (x2 === void 0) { x2 = 1; }
  54554. if (y2 === void 0) { y2 = 1; }
  54555. var _this = _super.call(this) || this;
  54556. _this.x1 = x1;
  54557. _this.y1 = y1;
  54558. _this.x2 = x2;
  54559. _this.y2 = y2;
  54560. return _this;
  54561. }
  54562. /** @hidden */
  54563. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54564. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54565. };
  54566. return BezierCurveEase;
  54567. }(EasingFunction));
  54568. BABYLON.BezierCurveEase = BezierCurveEase;
  54569. })(BABYLON || (BABYLON = {}));
  54570. //# sourceMappingURL=babylon.easing.js.map
  54571. var BABYLON;
  54572. (function (BABYLON) {
  54573. /**
  54574. * A Condition applied to an Action
  54575. */
  54576. var Condition = /** @class */ (function () {
  54577. /**
  54578. * Creates a new Condition
  54579. * @param actionManager the manager of the action the condition is applied to
  54580. */
  54581. function Condition(actionManager) {
  54582. this._actionManager = actionManager;
  54583. }
  54584. /**
  54585. * Check if the current condition is valid
  54586. * @returns a boolean
  54587. */
  54588. Condition.prototype.isValid = function () {
  54589. return true;
  54590. };
  54591. /**
  54592. * Internal only
  54593. * @hidden
  54594. */
  54595. Condition.prototype._getProperty = function (propertyPath) {
  54596. return this._actionManager._getProperty(propertyPath);
  54597. };
  54598. /**
  54599. * Internal only
  54600. * @hidden
  54601. */
  54602. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54603. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54604. };
  54605. /**
  54606. * Serialize placeholder for child classes
  54607. * @returns the serialized object
  54608. */
  54609. Condition.prototype.serialize = function () {
  54610. };
  54611. /**
  54612. * Internal only
  54613. * @hidden
  54614. */
  54615. Condition.prototype._serialize = function (serializedCondition) {
  54616. return {
  54617. type: 2,
  54618. children: [],
  54619. name: serializedCondition.name,
  54620. properties: serializedCondition.properties
  54621. };
  54622. };
  54623. return Condition;
  54624. }());
  54625. BABYLON.Condition = Condition;
  54626. /**
  54627. * Defines specific conditional operators as extensions of Condition
  54628. */
  54629. var ValueCondition = /** @class */ (function (_super) {
  54630. __extends(ValueCondition, _super);
  54631. /**
  54632. * Creates a new ValueCondition
  54633. * @param actionManager manager for the action the condition applies to
  54634. * @param target for the action
  54635. * @param propertyPath path to specify the property of the target the conditional operator uses
  54636. * @param value the value compared by the conditional operator against the current value of the property
  54637. * @param operator the conditional operator, default ValueCondition.IsEqual
  54638. */
  54639. function ValueCondition(actionManager, target,
  54640. /** path to specify the property of the target the conditional operator uses */
  54641. propertyPath,
  54642. /** the value compared by the conditional operator against the current value of the property */
  54643. value,
  54644. /** the conditional operator, default ValueCondition.IsEqual */
  54645. operator) {
  54646. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54647. var _this = _super.call(this, actionManager) || this;
  54648. _this.propertyPath = propertyPath;
  54649. _this.value = value;
  54650. _this.operator = operator;
  54651. _this._target = target;
  54652. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54653. _this._property = _this._getProperty(_this.propertyPath);
  54654. return _this;
  54655. }
  54656. Object.defineProperty(ValueCondition, "IsEqual", {
  54657. /**
  54658. * returns the number for IsEqual
  54659. */
  54660. get: function () {
  54661. return ValueCondition._IsEqual;
  54662. },
  54663. enumerable: true,
  54664. configurable: true
  54665. });
  54666. Object.defineProperty(ValueCondition, "IsDifferent", {
  54667. /**
  54668. * Returns the number for IsDifferent
  54669. */
  54670. get: function () {
  54671. return ValueCondition._IsDifferent;
  54672. },
  54673. enumerable: true,
  54674. configurable: true
  54675. });
  54676. Object.defineProperty(ValueCondition, "IsGreater", {
  54677. /**
  54678. * Returns the number for IsGreater
  54679. */
  54680. get: function () {
  54681. return ValueCondition._IsGreater;
  54682. },
  54683. enumerable: true,
  54684. configurable: true
  54685. });
  54686. Object.defineProperty(ValueCondition, "IsLesser", {
  54687. /**
  54688. * Returns the number for IsLesser
  54689. */
  54690. get: function () {
  54691. return ValueCondition._IsLesser;
  54692. },
  54693. enumerable: true,
  54694. configurable: true
  54695. });
  54696. /**
  54697. * Compares the given value with the property value for the specified conditional operator
  54698. * @returns the result of the comparison
  54699. */
  54700. ValueCondition.prototype.isValid = function () {
  54701. switch (this.operator) {
  54702. case ValueCondition.IsGreater:
  54703. return this._effectiveTarget[this._property] > this.value;
  54704. case ValueCondition.IsLesser:
  54705. return this._effectiveTarget[this._property] < this.value;
  54706. case ValueCondition.IsEqual:
  54707. case ValueCondition.IsDifferent:
  54708. var check;
  54709. if (this.value.equals) {
  54710. check = this.value.equals(this._effectiveTarget[this._property]);
  54711. }
  54712. else {
  54713. check = this.value === this._effectiveTarget[this._property];
  54714. }
  54715. return this.operator === ValueCondition.IsEqual ? check : !check;
  54716. }
  54717. return false;
  54718. };
  54719. /**
  54720. * Serialize the ValueCondition into a JSON compatible object
  54721. * @returns serialization object
  54722. */
  54723. ValueCondition.prototype.serialize = function () {
  54724. return this._serialize({
  54725. name: "ValueCondition",
  54726. properties: [
  54727. BABYLON.Action._GetTargetProperty(this._target),
  54728. { name: "propertyPath", value: this.propertyPath },
  54729. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54730. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54731. ]
  54732. });
  54733. };
  54734. /**
  54735. * Gets the name of the conditional operator for the ValueCondition
  54736. * @param operator the conditional operator
  54737. * @returns the name
  54738. */
  54739. ValueCondition.GetOperatorName = function (operator) {
  54740. switch (operator) {
  54741. case ValueCondition._IsEqual: return "IsEqual";
  54742. case ValueCondition._IsDifferent: return "IsDifferent";
  54743. case ValueCondition._IsGreater: return "IsGreater";
  54744. case ValueCondition._IsLesser: return "IsLesser";
  54745. default: return "";
  54746. }
  54747. };
  54748. /**
  54749. * Internal only
  54750. * @hidden
  54751. */
  54752. ValueCondition._IsEqual = 0;
  54753. /**
  54754. * Internal only
  54755. * @hidden
  54756. */
  54757. ValueCondition._IsDifferent = 1;
  54758. /**
  54759. * Internal only
  54760. * @hidden
  54761. */
  54762. ValueCondition._IsGreater = 2;
  54763. /**
  54764. * Internal only
  54765. * @hidden
  54766. */
  54767. ValueCondition._IsLesser = 3;
  54768. return ValueCondition;
  54769. }(Condition));
  54770. BABYLON.ValueCondition = ValueCondition;
  54771. /**
  54772. * Defines a predicate condition as an extension of Condition
  54773. */
  54774. var PredicateCondition = /** @class */ (function (_super) {
  54775. __extends(PredicateCondition, _super);
  54776. /**
  54777. * Creates a new PredicateCondition
  54778. * @param actionManager manager for the action the condition applies to
  54779. * @param predicate defines the predicate function used to validate the condition
  54780. */
  54781. function PredicateCondition(actionManager,
  54782. /** defines the predicate function used to validate the condition */
  54783. predicate) {
  54784. var _this = _super.call(this, actionManager) || this;
  54785. _this.predicate = predicate;
  54786. return _this;
  54787. }
  54788. /**
  54789. * @returns the validity of the predicate condition
  54790. */
  54791. PredicateCondition.prototype.isValid = function () {
  54792. return this.predicate();
  54793. };
  54794. return PredicateCondition;
  54795. }(Condition));
  54796. BABYLON.PredicateCondition = PredicateCondition;
  54797. /**
  54798. * Defines a state condition as an extension of Condition
  54799. */
  54800. var StateCondition = /** @class */ (function (_super) {
  54801. __extends(StateCondition, _super);
  54802. /**
  54803. * Creates a new StateCondition
  54804. * @param actionManager manager for the action the condition applies to
  54805. * @param target of the condition
  54806. * @param value to compare with target state
  54807. */
  54808. function StateCondition(actionManager, target,
  54809. /** Value to compare with target state */
  54810. value) {
  54811. var _this = _super.call(this, actionManager) || this;
  54812. _this.value = value;
  54813. _this._target = target;
  54814. return _this;
  54815. }
  54816. /**
  54817. * Gets a boolean indicating if the current condition is met
  54818. * @returns the validity of the state
  54819. */
  54820. StateCondition.prototype.isValid = function () {
  54821. return this._target.state === this.value;
  54822. };
  54823. /**
  54824. * Serialize the StateCondition into a JSON compatible object
  54825. * @returns serialization object
  54826. */
  54827. StateCondition.prototype.serialize = function () {
  54828. return this._serialize({
  54829. name: "StateCondition",
  54830. properties: [
  54831. BABYLON.Action._GetTargetProperty(this._target),
  54832. { name: "value", value: this.value }
  54833. ]
  54834. });
  54835. };
  54836. return StateCondition;
  54837. }(Condition));
  54838. BABYLON.StateCondition = StateCondition;
  54839. })(BABYLON || (BABYLON = {}));
  54840. //# sourceMappingURL=babylon.condition.js.map
  54841. var BABYLON;
  54842. (function (BABYLON) {
  54843. /**
  54844. * The action to be carried out following a trigger
  54845. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54846. */
  54847. var Action = /** @class */ (function () {
  54848. /**
  54849. * Creates a new Action
  54850. * @param triggerOptions the trigger, with or without parameters, for the action
  54851. * @param condition an optional determinant of action
  54852. */
  54853. function Action(
  54854. /** the trigger, with or without parameters, for the action */
  54855. triggerOptions, condition) {
  54856. this.triggerOptions = triggerOptions;
  54857. /**
  54858. * An event triggered prior to action being executed.
  54859. */
  54860. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54861. if (triggerOptions.parameter) {
  54862. this.trigger = triggerOptions.trigger;
  54863. this._triggerParameter = triggerOptions.parameter;
  54864. }
  54865. else if (triggerOptions.trigger) {
  54866. this.trigger = triggerOptions.trigger;
  54867. }
  54868. else {
  54869. this.trigger = triggerOptions;
  54870. }
  54871. this._nextActiveAction = this;
  54872. this._condition = condition;
  54873. }
  54874. /**
  54875. * Internal only
  54876. * @hidden
  54877. */
  54878. Action.prototype._prepare = function () {
  54879. };
  54880. /**
  54881. * Gets the trigger parameters
  54882. * @returns the trigger parameters
  54883. */
  54884. Action.prototype.getTriggerParameter = function () {
  54885. return this._triggerParameter;
  54886. };
  54887. /**
  54888. * Internal only - executes current action event
  54889. * @hidden
  54890. */
  54891. Action.prototype._executeCurrent = function (evt) {
  54892. if (this._nextActiveAction._condition) {
  54893. var condition = this._nextActiveAction._condition;
  54894. var currentRenderId = this._actionManager.getScene().getRenderId();
  54895. // We cache the current evaluation for the current frame
  54896. if (condition._evaluationId === currentRenderId) {
  54897. if (!condition._currentResult) {
  54898. return;
  54899. }
  54900. }
  54901. else {
  54902. condition._evaluationId = currentRenderId;
  54903. if (!condition.isValid()) {
  54904. condition._currentResult = false;
  54905. return;
  54906. }
  54907. condition._currentResult = true;
  54908. }
  54909. }
  54910. this.onBeforeExecuteObservable.notifyObservers(this);
  54911. this._nextActiveAction.execute(evt);
  54912. this.skipToNextActiveAction();
  54913. };
  54914. /**
  54915. * Execute placeholder for child classes
  54916. * @param evt optional action event
  54917. */
  54918. Action.prototype.execute = function (evt) {
  54919. };
  54920. /**
  54921. * Skips to next active action
  54922. */
  54923. Action.prototype.skipToNextActiveAction = function () {
  54924. if (this._nextActiveAction._child) {
  54925. if (!this._nextActiveAction._child._actionManager) {
  54926. this._nextActiveAction._child._actionManager = this._actionManager;
  54927. }
  54928. this._nextActiveAction = this._nextActiveAction._child;
  54929. }
  54930. else {
  54931. this._nextActiveAction = this;
  54932. }
  54933. };
  54934. /**
  54935. * Adds action to chain of actions, may be a DoNothingAction
  54936. * @param action defines the next action to execute
  54937. * @returns The action passed in
  54938. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54939. */
  54940. Action.prototype.then = function (action) {
  54941. this._child = action;
  54942. action._actionManager = this._actionManager;
  54943. action._prepare();
  54944. return action;
  54945. };
  54946. /**
  54947. * Internal only
  54948. * @hidden
  54949. */
  54950. Action.prototype._getProperty = function (propertyPath) {
  54951. return this._actionManager._getProperty(propertyPath);
  54952. };
  54953. /**
  54954. * Internal only
  54955. * @hidden
  54956. */
  54957. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54958. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54959. };
  54960. /**
  54961. * Serialize placeholder for child classes
  54962. * @param parent of child
  54963. * @returns the serialized object
  54964. */
  54965. Action.prototype.serialize = function (parent) {
  54966. };
  54967. /**
  54968. * Internal only called by serialize
  54969. * @hidden
  54970. */
  54971. Action.prototype._serialize = function (serializedAction, parent) {
  54972. var serializationObject = {
  54973. type: 1,
  54974. children: [],
  54975. name: serializedAction.name,
  54976. properties: serializedAction.properties || []
  54977. };
  54978. // Serialize child
  54979. if (this._child) {
  54980. this._child.serialize(serializationObject);
  54981. }
  54982. // Check if "this" has a condition
  54983. if (this._condition) {
  54984. var serializedCondition = this._condition.serialize();
  54985. serializedCondition.children.push(serializationObject);
  54986. if (parent) {
  54987. parent.children.push(serializedCondition);
  54988. }
  54989. return serializedCondition;
  54990. }
  54991. if (parent) {
  54992. parent.children.push(serializationObject);
  54993. }
  54994. return serializationObject;
  54995. };
  54996. /**
  54997. * Internal only
  54998. * @hidden
  54999. */
  55000. Action._SerializeValueAsString = function (value) {
  55001. if (typeof value === "number") {
  55002. return value.toString();
  55003. }
  55004. if (typeof value === "boolean") {
  55005. return value ? "true" : "false";
  55006. }
  55007. if (value instanceof BABYLON.Vector2) {
  55008. return value.x + ", " + value.y;
  55009. }
  55010. if (value instanceof BABYLON.Vector3) {
  55011. return value.x + ", " + value.y + ", " + value.z;
  55012. }
  55013. if (value instanceof BABYLON.Color3) {
  55014. return value.r + ", " + value.g + ", " + value.b;
  55015. }
  55016. if (value instanceof BABYLON.Color4) {
  55017. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  55018. }
  55019. return value; // string
  55020. };
  55021. /**
  55022. * Internal only
  55023. * @hidden
  55024. */
  55025. Action._GetTargetProperty = function (target) {
  55026. return {
  55027. name: "target",
  55028. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55029. : target instanceof BABYLON.Light ? "LightProperties"
  55030. : target instanceof BABYLON.Camera ? "CameraProperties"
  55031. : "SceneProperties",
  55032. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55033. };
  55034. };
  55035. return Action;
  55036. }());
  55037. BABYLON.Action = Action;
  55038. })(BABYLON || (BABYLON = {}));
  55039. //# sourceMappingURL=babylon.action.js.map
  55040. var BABYLON;
  55041. (function (BABYLON) {
  55042. /**
  55043. * ActionEvent is the event being sent when an action is triggered.
  55044. */
  55045. var ActionEvent = /** @class */ (function () {
  55046. /**
  55047. * Creates a new ActionEvent
  55048. * @param source The mesh or sprite that triggered the action
  55049. * @param pointerX The X mouse cursor position at the time of the event
  55050. * @param pointerY The Y mouse cursor position at the time of the event
  55051. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55052. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55053. * @param additionalData additional data for the event
  55054. */
  55055. function ActionEvent(
  55056. /** The mesh or sprite that triggered the action */
  55057. source,
  55058. /** The X mouse cursor position at the time of the event */
  55059. pointerX,
  55060. /** The Y mouse cursor position at the time of the event */
  55061. pointerY,
  55062. /** The mesh that is currently pointed at (can be null) */
  55063. meshUnderPointer,
  55064. /** the original (browser) event that triggered the ActionEvent */
  55065. sourceEvent,
  55066. /** additional data for the event */
  55067. additionalData) {
  55068. this.source = source;
  55069. this.pointerX = pointerX;
  55070. this.pointerY = pointerY;
  55071. this.meshUnderPointer = meshUnderPointer;
  55072. this.sourceEvent = sourceEvent;
  55073. this.additionalData = additionalData;
  55074. }
  55075. /**
  55076. * Helper function to auto-create an ActionEvent from a source mesh.
  55077. * @param source The source mesh that triggered the event
  55078. * @param evt The original (browser) event
  55079. * @param additionalData additional data for the event
  55080. * @returns the new ActionEvent
  55081. */
  55082. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55083. var scene = source.getScene();
  55084. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55085. };
  55086. /**
  55087. * Helper function to auto-create an ActionEvent from a source sprite
  55088. * @param source The source sprite that triggered the event
  55089. * @param scene Scene associated with the sprite
  55090. * @param evt The original (browser) event
  55091. * @param additionalData additional data for the event
  55092. * @returns the new ActionEvent
  55093. */
  55094. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55095. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55096. };
  55097. /**
  55098. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55099. * @param scene the scene where the event occurred
  55100. * @param evt The original (browser) event
  55101. * @returns the new ActionEvent
  55102. */
  55103. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55104. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55105. };
  55106. /**
  55107. * Helper function to auto-create an ActionEvent from a primitive
  55108. * @param prim defines the target primitive
  55109. * @param pointerPos defines the pointer position
  55110. * @param evt The original (browser) event
  55111. * @param additionalData additional data for the event
  55112. * @returns the new ActionEvent
  55113. */
  55114. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55115. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55116. };
  55117. return ActionEvent;
  55118. }());
  55119. BABYLON.ActionEvent = ActionEvent;
  55120. /**
  55121. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55122. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55123. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55124. */
  55125. var ActionManager = /** @class */ (function () {
  55126. /**
  55127. * Creates a new action manager
  55128. * @param scene defines the hosting scene
  55129. */
  55130. function ActionManager(scene) {
  55131. // Members
  55132. /** Gets the list of actions */
  55133. this.actions = new Array();
  55134. /** Gets the cursor to use when hovering items */
  55135. this.hoverCursor = '';
  55136. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55137. scene.actionManagers.push(this);
  55138. }
  55139. // Methods
  55140. /**
  55141. * Releases all associated resources
  55142. */
  55143. ActionManager.prototype.dispose = function () {
  55144. var index = this._scene.actionManagers.indexOf(this);
  55145. for (var i = 0; i < this.actions.length; i++) {
  55146. var action = this.actions[i];
  55147. ActionManager.Triggers[action.trigger]--;
  55148. if (ActionManager.Triggers[action.trigger] === 0) {
  55149. delete ActionManager.Triggers[action.trigger];
  55150. }
  55151. }
  55152. if (index > -1) {
  55153. this._scene.actionManagers.splice(index, 1);
  55154. }
  55155. };
  55156. /**
  55157. * Gets hosting scene
  55158. * @returns the hosting scene
  55159. */
  55160. ActionManager.prototype.getScene = function () {
  55161. return this._scene;
  55162. };
  55163. /**
  55164. * Does this action manager handles actions of any of the given triggers
  55165. * @param triggers defines the triggers to be tested
  55166. * @return a boolean indicating whether one (or more) of the triggers is handled
  55167. */
  55168. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55169. for (var index = 0; index < this.actions.length; index++) {
  55170. var action = this.actions[index];
  55171. if (triggers.indexOf(action.trigger) > -1) {
  55172. return true;
  55173. }
  55174. }
  55175. return false;
  55176. };
  55177. /**
  55178. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55179. * speed.
  55180. * @param triggerA defines the trigger to be tested
  55181. * @param triggerB defines the trigger to be tested
  55182. * @return a boolean indicating whether one (or more) of the triggers is handled
  55183. */
  55184. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55185. for (var index = 0; index < this.actions.length; index++) {
  55186. var action = this.actions[index];
  55187. if (triggerA == action.trigger || triggerB == action.trigger) {
  55188. return true;
  55189. }
  55190. }
  55191. return false;
  55192. };
  55193. /**
  55194. * Does this action manager handles actions of a given trigger
  55195. * @param trigger defines the trigger to be tested
  55196. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55197. * @return whether the trigger is handled
  55198. */
  55199. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55200. for (var index = 0; index < this.actions.length; index++) {
  55201. var action = this.actions[index];
  55202. if (action.trigger === trigger) {
  55203. if (parameterPredicate) {
  55204. if (parameterPredicate(action.getTriggerParameter())) {
  55205. return true;
  55206. }
  55207. }
  55208. else {
  55209. return true;
  55210. }
  55211. }
  55212. }
  55213. return false;
  55214. };
  55215. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55216. /**
  55217. * Does this action manager has pointer triggers
  55218. */
  55219. get: function () {
  55220. for (var index = 0; index < this.actions.length; index++) {
  55221. var action = this.actions[index];
  55222. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55223. return true;
  55224. }
  55225. }
  55226. return false;
  55227. },
  55228. enumerable: true,
  55229. configurable: true
  55230. });
  55231. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55232. /**
  55233. * Does this action manager has pick triggers
  55234. */
  55235. get: function () {
  55236. for (var index = 0; index < this.actions.length; index++) {
  55237. var action = this.actions[index];
  55238. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55239. return true;
  55240. }
  55241. }
  55242. return false;
  55243. },
  55244. enumerable: true,
  55245. configurable: true
  55246. });
  55247. Object.defineProperty(ActionManager, "HasTriggers", {
  55248. /**
  55249. * Does exist one action manager with at least one trigger
  55250. **/
  55251. get: function () {
  55252. for (var t in ActionManager.Triggers) {
  55253. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55254. return true;
  55255. }
  55256. }
  55257. return false;
  55258. },
  55259. enumerable: true,
  55260. configurable: true
  55261. });
  55262. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55263. /**
  55264. * Does exist one action manager with at least one pick trigger
  55265. **/
  55266. get: function () {
  55267. for (var t in ActionManager.Triggers) {
  55268. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55269. var t_int = parseInt(t);
  55270. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55271. return true;
  55272. }
  55273. }
  55274. }
  55275. return false;
  55276. },
  55277. enumerable: true,
  55278. configurable: true
  55279. });
  55280. /**
  55281. * Does exist one action manager that handles actions of a given trigger
  55282. * @param trigger defines the trigger to be tested
  55283. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55284. **/
  55285. ActionManager.HasSpecificTrigger = function (trigger) {
  55286. for (var t in ActionManager.Triggers) {
  55287. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55288. var t_int = parseInt(t);
  55289. if (t_int === trigger) {
  55290. return true;
  55291. }
  55292. }
  55293. }
  55294. return false;
  55295. };
  55296. /**
  55297. * Registers an action to this action manager
  55298. * @param action defines the action to be registered
  55299. * @return the action amended (prepared) after registration
  55300. */
  55301. ActionManager.prototype.registerAction = function (action) {
  55302. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55303. if (this.getScene().actionManager !== this) {
  55304. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55305. return null;
  55306. }
  55307. }
  55308. this.actions.push(action);
  55309. if (ActionManager.Triggers[action.trigger]) {
  55310. ActionManager.Triggers[action.trigger]++;
  55311. }
  55312. else {
  55313. ActionManager.Triggers[action.trigger] = 1;
  55314. }
  55315. action._actionManager = this;
  55316. action._prepare();
  55317. return action;
  55318. };
  55319. /**
  55320. * Unregisters an action to this action manager
  55321. * @param action defines the action to be unregistered
  55322. * @return a boolean indicating whether the action has been unregistered
  55323. */
  55324. ActionManager.prototype.unregisterAction = function (action) {
  55325. var index = this.actions.indexOf(action);
  55326. if (index !== -1) {
  55327. this.actions.splice(index, 1);
  55328. ActionManager.Triggers[action.trigger] -= 1;
  55329. if (ActionManager.Triggers[action.trigger] === 0) {
  55330. delete ActionManager.Triggers[action.trigger];
  55331. }
  55332. delete action._actionManager;
  55333. return true;
  55334. }
  55335. return false;
  55336. };
  55337. /**
  55338. * Process a specific trigger
  55339. * @param trigger defines the trigger to process
  55340. * @param evt defines the event details to be processed
  55341. */
  55342. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55343. for (var index = 0; index < this.actions.length; index++) {
  55344. var action = this.actions[index];
  55345. if (action.trigger === trigger) {
  55346. if (evt) {
  55347. if (trigger === ActionManager.OnKeyUpTrigger
  55348. || trigger === ActionManager.OnKeyDownTrigger) {
  55349. var parameter = action.getTriggerParameter();
  55350. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55351. if (!parameter.toLowerCase) {
  55352. continue;
  55353. }
  55354. var lowerCase = parameter.toLowerCase();
  55355. if (lowerCase !== evt.sourceEvent.key) {
  55356. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55357. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55358. if (actualkey !== lowerCase) {
  55359. continue;
  55360. }
  55361. }
  55362. }
  55363. }
  55364. }
  55365. action._executeCurrent(evt);
  55366. }
  55367. }
  55368. };
  55369. /** @hidden */
  55370. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55371. var properties = propertyPath.split(".");
  55372. for (var index = 0; index < properties.length - 1; index++) {
  55373. target = target[properties[index]];
  55374. }
  55375. return target;
  55376. };
  55377. /** @hidden */
  55378. ActionManager.prototype._getProperty = function (propertyPath) {
  55379. var properties = propertyPath.split(".");
  55380. return properties[properties.length - 1];
  55381. };
  55382. /**
  55383. * Serialize this manager to a JSON object
  55384. * @param name defines the property name to store this manager
  55385. * @returns a JSON representation of this manager
  55386. */
  55387. ActionManager.prototype.serialize = function (name) {
  55388. var root = {
  55389. children: new Array(),
  55390. name: name,
  55391. type: 3,
  55392. properties: new Array() // Empty for root but required
  55393. };
  55394. for (var i = 0; i < this.actions.length; i++) {
  55395. var triggerObject = {
  55396. type: 0,
  55397. children: new Array(),
  55398. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55399. properties: new Array()
  55400. };
  55401. var triggerOptions = this.actions[i].triggerOptions;
  55402. if (triggerOptions && typeof triggerOptions !== "number") {
  55403. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55404. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55405. }
  55406. else {
  55407. var parameter = {};
  55408. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55409. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  55410. parameter._meshId = triggerOptions.parameter.mesh.id;
  55411. }
  55412. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55413. }
  55414. }
  55415. // Serialize child action, recursively
  55416. this.actions[i].serialize(triggerObject);
  55417. // Add serialized trigger
  55418. root.children.push(triggerObject);
  55419. }
  55420. return root;
  55421. };
  55422. /**
  55423. * Creates a new ActionManager from a JSON data
  55424. * @param parsedActions defines the JSON data to read from
  55425. * @param object defines the hosting mesh
  55426. * @param scene defines the hosting scene
  55427. */
  55428. ActionManager.Parse = function (parsedActions, object, scene) {
  55429. var actionManager = new ActionManager(scene);
  55430. if (object === null)
  55431. scene.actionManager = actionManager;
  55432. else
  55433. object.actionManager = actionManager;
  55434. // instanciate a new object
  55435. var instanciate = function (name, params) {
  55436. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55437. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55438. newInstance.constructor.apply(newInstance, params);
  55439. return newInstance;
  55440. };
  55441. var parseParameter = function (name, value, target, propertyPath) {
  55442. if (propertyPath === null) {
  55443. // String, boolean or float
  55444. var floatValue = parseFloat(value);
  55445. if (value === "true" || value === "false")
  55446. return value === "true";
  55447. else
  55448. return isNaN(floatValue) ? value : floatValue;
  55449. }
  55450. var effectiveTarget = propertyPath.split(".");
  55451. var values = value.split(",");
  55452. // Get effective Target
  55453. for (var i = 0; i < effectiveTarget.length; i++) {
  55454. target = target[effectiveTarget[i]];
  55455. }
  55456. // Return appropriate value with its type
  55457. if (typeof (target) === "boolean")
  55458. return values[0] === "true";
  55459. if (typeof (target) === "string")
  55460. return values[0];
  55461. // Parameters with multiple values such as Vector3 etc.
  55462. var split = new Array();
  55463. for (var i = 0; i < values.length; i++)
  55464. split.push(parseFloat(values[i]));
  55465. if (target instanceof BABYLON.Vector3)
  55466. return BABYLON.Vector3.FromArray(split);
  55467. if (target instanceof BABYLON.Vector4)
  55468. return BABYLON.Vector4.FromArray(split);
  55469. if (target instanceof BABYLON.Color3)
  55470. return BABYLON.Color3.FromArray(split);
  55471. if (target instanceof BABYLON.Color4)
  55472. return BABYLON.Color4.FromArray(split);
  55473. return parseFloat(values[0]);
  55474. };
  55475. // traverse graph per trigger
  55476. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55477. if (combineArray === void 0) { combineArray = null; }
  55478. if (parsedAction.detached)
  55479. return;
  55480. var parameters = new Array();
  55481. var target = null;
  55482. var propertyPath = null;
  55483. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55484. // Parameters
  55485. if (parsedAction.type === 2)
  55486. parameters.push(actionManager);
  55487. else
  55488. parameters.push(trigger);
  55489. if (combine) {
  55490. var actions = new Array();
  55491. for (var j = 0; j < parsedAction.combine.length; j++) {
  55492. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55493. }
  55494. parameters.push(actions);
  55495. }
  55496. else {
  55497. for (var i = 0; i < parsedAction.properties.length; i++) {
  55498. var value = parsedAction.properties[i].value;
  55499. var name = parsedAction.properties[i].name;
  55500. var targetType = parsedAction.properties[i].targetType;
  55501. if (name === "target")
  55502. if (targetType !== null && targetType === "SceneProperties")
  55503. value = target = scene;
  55504. else
  55505. value = target = scene.getNodeByName(value);
  55506. else if (name === "parent")
  55507. value = scene.getNodeByName(value);
  55508. else if (name === "sound") {
  55509. // Can not externalize to component, so only checks for the presence off the API.
  55510. if (scene.getSoundByName) {
  55511. value = scene.getSoundByName(value);
  55512. }
  55513. }
  55514. else if (name !== "propertyPath") {
  55515. if (parsedAction.type === 2 && name === "operator")
  55516. value = BABYLON.ValueCondition[value];
  55517. else
  55518. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55519. }
  55520. else {
  55521. propertyPath = value;
  55522. }
  55523. parameters.push(value);
  55524. }
  55525. }
  55526. if (combineArray === null) {
  55527. parameters.push(condition);
  55528. }
  55529. else {
  55530. parameters.push(null);
  55531. }
  55532. // If interpolate value action
  55533. if (parsedAction.name === "InterpolateValueAction") {
  55534. var param = parameters[parameters.length - 2];
  55535. parameters[parameters.length - 1] = param;
  55536. parameters[parameters.length - 2] = condition;
  55537. }
  55538. // Action or condition(s) and not CombineAction
  55539. var newAction = instanciate(parsedAction.name, parameters);
  55540. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55541. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55542. if (action)
  55543. action.then(nothing);
  55544. else
  55545. actionManager.registerAction(nothing);
  55546. action = nothing;
  55547. }
  55548. if (combineArray === null) {
  55549. if (newAction instanceof BABYLON.Condition) {
  55550. condition = newAction;
  55551. newAction = action;
  55552. }
  55553. else {
  55554. condition = null;
  55555. if (action)
  55556. action.then(newAction);
  55557. else
  55558. actionManager.registerAction(newAction);
  55559. }
  55560. }
  55561. else {
  55562. combineArray.push(newAction);
  55563. }
  55564. for (var i = 0; i < parsedAction.children.length; i++)
  55565. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55566. };
  55567. // triggers
  55568. for (var i = 0; i < parsedActions.children.length; i++) {
  55569. var triggerParams;
  55570. var trigger = parsedActions.children[i];
  55571. if (trigger.properties.length > 0) {
  55572. var param = trigger.properties[0].value;
  55573. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55574. if (value._meshId) {
  55575. value.mesh = scene.getMeshByID(value._meshId);
  55576. }
  55577. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55578. }
  55579. else
  55580. triggerParams = ActionManager[trigger.name];
  55581. for (var j = 0; j < trigger.children.length; j++) {
  55582. if (!trigger.detached)
  55583. traverse(trigger.children[j], triggerParams, null, null);
  55584. }
  55585. }
  55586. };
  55587. /**
  55588. * Get a trigger name by index
  55589. * @param trigger defines the trigger index
  55590. * @returns a trigger name
  55591. */
  55592. ActionManager.GetTriggerName = function (trigger) {
  55593. switch (trigger) {
  55594. case 0: return "NothingTrigger";
  55595. case 1: return "OnPickTrigger";
  55596. case 2: return "OnLeftPickTrigger";
  55597. case 3: return "OnRightPickTrigger";
  55598. case 4: return "OnCenterPickTrigger";
  55599. case 5: return "OnPickDownTrigger";
  55600. case 6: return "OnPickUpTrigger";
  55601. case 7: return "OnLongPressTrigger";
  55602. case 8: return "OnPointerOverTrigger";
  55603. case 9: return "OnPointerOutTrigger";
  55604. case 10: return "OnEveryFrameTrigger";
  55605. case 11: return "OnIntersectionEnterTrigger";
  55606. case 12: return "OnIntersectionExitTrigger";
  55607. case 13: return "OnKeyDownTrigger";
  55608. case 14: return "OnKeyUpTrigger";
  55609. case 15: return "OnPickOutTrigger";
  55610. default: return "";
  55611. }
  55612. };
  55613. /**
  55614. * Nothing
  55615. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55616. */
  55617. ActionManager.NothingTrigger = 0;
  55618. /**
  55619. * On pick
  55620. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55621. */
  55622. ActionManager.OnPickTrigger = 1;
  55623. /**
  55624. * On left pick
  55625. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55626. */
  55627. ActionManager.OnLeftPickTrigger = 2;
  55628. /**
  55629. * On right pick
  55630. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55631. */
  55632. ActionManager.OnRightPickTrigger = 3;
  55633. /**
  55634. * On center pick
  55635. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55636. */
  55637. ActionManager.OnCenterPickTrigger = 4;
  55638. /**
  55639. * On pick down
  55640. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55641. */
  55642. ActionManager.OnPickDownTrigger = 5;
  55643. /**
  55644. * On double pick
  55645. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55646. */
  55647. ActionManager.OnDoublePickTrigger = 6;
  55648. /**
  55649. * On pick up
  55650. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55651. */
  55652. ActionManager.OnPickUpTrigger = 7;
  55653. /**
  55654. * On pick out.
  55655. * This trigger will only be raised if you also declared a OnPickDown
  55656. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55657. */
  55658. ActionManager.OnPickOutTrigger = 16;
  55659. /**
  55660. * On long press
  55661. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55662. */
  55663. ActionManager.OnLongPressTrigger = 8;
  55664. /**
  55665. * On pointer over
  55666. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55667. */
  55668. ActionManager.OnPointerOverTrigger = 9;
  55669. /**
  55670. * On pointer out
  55671. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55672. */
  55673. ActionManager.OnPointerOutTrigger = 10;
  55674. /**
  55675. * On every frame
  55676. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55677. */
  55678. ActionManager.OnEveryFrameTrigger = 11;
  55679. /**
  55680. * On intersection enter
  55681. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55682. */
  55683. ActionManager.OnIntersectionEnterTrigger = 12;
  55684. /**
  55685. * On intersection exit
  55686. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55687. */
  55688. ActionManager.OnIntersectionExitTrigger = 13;
  55689. /**
  55690. * On key down
  55691. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55692. */
  55693. ActionManager.OnKeyDownTrigger = 14;
  55694. /**
  55695. * On key up
  55696. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55697. */
  55698. ActionManager.OnKeyUpTrigger = 15;
  55699. /** Gets the list of active triggers */
  55700. ActionManager.Triggers = {};
  55701. return ActionManager;
  55702. }());
  55703. BABYLON.ActionManager = ActionManager;
  55704. })(BABYLON || (BABYLON = {}));
  55705. //# sourceMappingURL=babylon.actionManager.js.map
  55706. var BABYLON;
  55707. (function (BABYLON) {
  55708. /**
  55709. * This defines an action responsible to change the value of a property
  55710. * by interpolating between its current value and the newly set one once triggered.
  55711. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55712. */
  55713. var InterpolateValueAction = /** @class */ (function (_super) {
  55714. __extends(InterpolateValueAction, _super);
  55715. /**
  55716. * Instantiate the action
  55717. * @param triggerOptions defines the trigger options
  55718. * @param target defines the object containing the value to interpolate
  55719. * @param propertyPath defines the path to the property in the target object
  55720. * @param value defines the target value at the end of the interpolation
  55721. * @param duration deines the time it will take for the property to interpolate to the value.
  55722. * @param condition defines the trigger related conditions
  55723. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55724. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55725. */
  55726. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55727. if (duration === void 0) { duration = 1000; }
  55728. var _this = _super.call(this, triggerOptions, condition) || this;
  55729. /**
  55730. * Defines the time it will take for the property to interpolate to the value.
  55731. */
  55732. _this.duration = 1000;
  55733. /**
  55734. * Observable triggered once the interpolation animation has been done.
  55735. */
  55736. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55737. _this.propertyPath = propertyPath;
  55738. _this.value = value;
  55739. _this.duration = duration;
  55740. _this.stopOtherAnimations = stopOtherAnimations;
  55741. _this.onInterpolationDone = onInterpolationDone;
  55742. _this._target = _this._effectiveTarget = target;
  55743. return _this;
  55744. }
  55745. /** @hidden */
  55746. InterpolateValueAction.prototype._prepare = function () {
  55747. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55748. this._property = this._getProperty(this.propertyPath);
  55749. };
  55750. /**
  55751. * Execute the action starts the value interpolation.
  55752. */
  55753. InterpolateValueAction.prototype.execute = function () {
  55754. var _this = this;
  55755. var scene = this._actionManager.getScene();
  55756. var keys = [
  55757. {
  55758. frame: 0,
  55759. value: this._effectiveTarget[this._property]
  55760. }, {
  55761. frame: 100,
  55762. value: this.value
  55763. }
  55764. ];
  55765. var dataType;
  55766. if (typeof this.value === "number") {
  55767. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55768. }
  55769. else if (this.value instanceof BABYLON.Color3) {
  55770. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55771. }
  55772. else if (this.value instanceof BABYLON.Vector3) {
  55773. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55774. }
  55775. else if (this.value instanceof BABYLON.Matrix) {
  55776. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55777. }
  55778. else if (this.value instanceof BABYLON.Quaternion) {
  55779. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55780. }
  55781. else {
  55782. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55783. return;
  55784. }
  55785. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55786. animation.setKeys(keys);
  55787. if (this.stopOtherAnimations) {
  55788. scene.stopAnimation(this._effectiveTarget);
  55789. }
  55790. var wrapper = function () {
  55791. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55792. if (_this.onInterpolationDone) {
  55793. _this.onInterpolationDone();
  55794. }
  55795. };
  55796. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55797. };
  55798. /**
  55799. * Serializes the actions and its related information.
  55800. * @param parent defines the object to serialize in
  55801. * @returns the serialized object
  55802. */
  55803. InterpolateValueAction.prototype.serialize = function (parent) {
  55804. return _super.prototype._serialize.call(this, {
  55805. name: "InterpolateValueAction",
  55806. properties: [
  55807. BABYLON.Action._GetTargetProperty(this._target),
  55808. { name: "propertyPath", value: this.propertyPath },
  55809. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55810. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55811. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55812. ]
  55813. }, parent);
  55814. };
  55815. return InterpolateValueAction;
  55816. }(BABYLON.Action));
  55817. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55818. })(BABYLON || (BABYLON = {}));
  55819. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55820. var BABYLON;
  55821. (function (BABYLON) {
  55822. /**
  55823. * This defines an action responsible to toggle a boolean once triggered.
  55824. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55825. */
  55826. var SwitchBooleanAction = /** @class */ (function (_super) {
  55827. __extends(SwitchBooleanAction, _super);
  55828. /**
  55829. * Instantiate the action
  55830. * @param triggerOptions defines the trigger options
  55831. * @param target defines the object containing the boolean
  55832. * @param propertyPath defines the path to the boolean property in the target object
  55833. * @param condition defines the trigger related conditions
  55834. */
  55835. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55836. var _this = _super.call(this, triggerOptions, condition) || this;
  55837. _this.propertyPath = propertyPath;
  55838. _this._target = _this._effectiveTarget = target;
  55839. return _this;
  55840. }
  55841. /** @hidden */
  55842. SwitchBooleanAction.prototype._prepare = function () {
  55843. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55844. this._property = this._getProperty(this.propertyPath);
  55845. };
  55846. /**
  55847. * Execute the action toggle the boolean value.
  55848. */
  55849. SwitchBooleanAction.prototype.execute = function () {
  55850. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55851. };
  55852. /**
  55853. * Serializes the actions and its related information.
  55854. * @param parent defines the object to serialize in
  55855. * @returns the serialized object
  55856. */
  55857. SwitchBooleanAction.prototype.serialize = function (parent) {
  55858. return _super.prototype._serialize.call(this, {
  55859. name: "SwitchBooleanAction",
  55860. properties: [
  55861. BABYLON.Action._GetTargetProperty(this._target),
  55862. { name: "propertyPath", value: this.propertyPath }
  55863. ]
  55864. }, parent);
  55865. };
  55866. return SwitchBooleanAction;
  55867. }(BABYLON.Action));
  55868. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55869. /**
  55870. * This defines an action responsible to set a the state field of the target
  55871. * to a desired value once triggered.
  55872. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55873. */
  55874. var SetStateAction = /** @class */ (function (_super) {
  55875. __extends(SetStateAction, _super);
  55876. /**
  55877. * Instantiate the action
  55878. * @param triggerOptions defines the trigger options
  55879. * @param target defines the object containing the state property
  55880. * @param value defines the value to store in the state field
  55881. * @param condition defines the trigger related conditions
  55882. */
  55883. function SetStateAction(triggerOptions, target, value, condition) {
  55884. var _this = _super.call(this, triggerOptions, condition) || this;
  55885. _this.value = value;
  55886. _this._target = target;
  55887. return _this;
  55888. }
  55889. /**
  55890. * Execute the action and store the value on the target state property.
  55891. */
  55892. SetStateAction.prototype.execute = function () {
  55893. this._target.state = this.value;
  55894. };
  55895. /**
  55896. * Serializes the actions and its related information.
  55897. * @param parent defines the object to serialize in
  55898. * @returns the serialized object
  55899. */
  55900. SetStateAction.prototype.serialize = function (parent) {
  55901. return _super.prototype._serialize.call(this, {
  55902. name: "SetStateAction",
  55903. properties: [
  55904. BABYLON.Action._GetTargetProperty(this._target),
  55905. { name: "value", value: this.value }
  55906. ]
  55907. }, parent);
  55908. };
  55909. return SetStateAction;
  55910. }(BABYLON.Action));
  55911. BABYLON.SetStateAction = SetStateAction;
  55912. /**
  55913. * This defines an action responsible to set a property of the target
  55914. * to a desired value once triggered.
  55915. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55916. */
  55917. var SetValueAction = /** @class */ (function (_super) {
  55918. __extends(SetValueAction, _super);
  55919. /**
  55920. * Instantiate the action
  55921. * @param triggerOptions defines the trigger options
  55922. * @param target defines the object containing the property
  55923. * @param propertyPath defines the path of the property to set in the target
  55924. * @param value defines the value to set in the property
  55925. * @param condition defines the trigger related conditions
  55926. */
  55927. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55928. var _this = _super.call(this, triggerOptions, condition) || this;
  55929. _this.propertyPath = propertyPath;
  55930. _this.value = value;
  55931. _this._target = _this._effectiveTarget = target;
  55932. return _this;
  55933. }
  55934. /** @hidden */
  55935. SetValueAction.prototype._prepare = function () {
  55936. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55937. this._property = this._getProperty(this.propertyPath);
  55938. };
  55939. /**
  55940. * Execute the action and set the targetted property to the desired value.
  55941. */
  55942. SetValueAction.prototype.execute = function () {
  55943. this._effectiveTarget[this._property] = this.value;
  55944. if (this._target.markAsDirty) {
  55945. this._target.markAsDirty(this._property);
  55946. }
  55947. };
  55948. /**
  55949. * Serializes the actions and its related information.
  55950. * @param parent defines the object to serialize in
  55951. * @returns the serialized object
  55952. */
  55953. SetValueAction.prototype.serialize = function (parent) {
  55954. return _super.prototype._serialize.call(this, {
  55955. name: "SetValueAction",
  55956. properties: [
  55957. BABYLON.Action._GetTargetProperty(this._target),
  55958. { name: "propertyPath", value: this.propertyPath },
  55959. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55960. ]
  55961. }, parent);
  55962. };
  55963. return SetValueAction;
  55964. }(BABYLON.Action));
  55965. BABYLON.SetValueAction = SetValueAction;
  55966. /**
  55967. * This defines an action responsible to increment the target value
  55968. * to a desired value once triggered.
  55969. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55970. */
  55971. var IncrementValueAction = /** @class */ (function (_super) {
  55972. __extends(IncrementValueAction, _super);
  55973. /**
  55974. * Instantiate the action
  55975. * @param triggerOptions defines the trigger options
  55976. * @param target defines the object containing the property
  55977. * @param propertyPath defines the path of the property to increment in the target
  55978. * @param value defines the value value we should increment the property by
  55979. * @param condition defines the trigger related conditions
  55980. */
  55981. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  55982. var _this = _super.call(this, triggerOptions, condition) || this;
  55983. _this.propertyPath = propertyPath;
  55984. _this.value = value;
  55985. _this._target = _this._effectiveTarget = target;
  55986. return _this;
  55987. }
  55988. /** @hidden */
  55989. IncrementValueAction.prototype._prepare = function () {
  55990. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55991. this._property = this._getProperty(this.propertyPath);
  55992. if (typeof this._effectiveTarget[this._property] !== "number") {
  55993. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  55994. }
  55995. };
  55996. /**
  55997. * Execute the action and increment the target of the value amount.
  55998. */
  55999. IncrementValueAction.prototype.execute = function () {
  56000. this._effectiveTarget[this._property] += this.value;
  56001. if (this._target.markAsDirty) {
  56002. this._target.markAsDirty(this._property);
  56003. }
  56004. };
  56005. /**
  56006. * Serializes the actions and its related information.
  56007. * @param parent defines the object to serialize in
  56008. * @returns the serialized object
  56009. */
  56010. IncrementValueAction.prototype.serialize = function (parent) {
  56011. return _super.prototype._serialize.call(this, {
  56012. name: "IncrementValueAction",
  56013. properties: [
  56014. BABYLON.Action._GetTargetProperty(this._target),
  56015. { name: "propertyPath", value: this.propertyPath },
  56016. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56017. ]
  56018. }, parent);
  56019. };
  56020. return IncrementValueAction;
  56021. }(BABYLON.Action));
  56022. BABYLON.IncrementValueAction = IncrementValueAction;
  56023. /**
  56024. * This defines an action responsible to start an animation once triggered.
  56025. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56026. */
  56027. var PlayAnimationAction = /** @class */ (function (_super) {
  56028. __extends(PlayAnimationAction, _super);
  56029. /**
  56030. * Instantiate the action
  56031. * @param triggerOptions defines the trigger options
  56032. * @param target defines the target animation or animation name
  56033. * @param from defines from where the animation should start (animation frame)
  56034. * @param end defines where the animation should stop (animation frame)
  56035. * @param loop defines if the animation should loop or stop after the first play
  56036. * @param condition defines the trigger related conditions
  56037. */
  56038. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56039. var _this = _super.call(this, triggerOptions, condition) || this;
  56040. _this.from = from;
  56041. _this.to = to;
  56042. _this.loop = loop;
  56043. _this._target = target;
  56044. return _this;
  56045. }
  56046. /** @hidden */
  56047. PlayAnimationAction.prototype._prepare = function () {
  56048. };
  56049. /**
  56050. * Execute the action and play the animation.
  56051. */
  56052. PlayAnimationAction.prototype.execute = function () {
  56053. var scene = this._actionManager.getScene();
  56054. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56055. };
  56056. /**
  56057. * Serializes the actions and its related information.
  56058. * @param parent defines the object to serialize in
  56059. * @returns the serialized object
  56060. */
  56061. PlayAnimationAction.prototype.serialize = function (parent) {
  56062. return _super.prototype._serialize.call(this, {
  56063. name: "PlayAnimationAction",
  56064. properties: [
  56065. BABYLON.Action._GetTargetProperty(this._target),
  56066. { name: "from", value: String(this.from) },
  56067. { name: "to", value: String(this.to) },
  56068. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56069. ]
  56070. }, parent);
  56071. };
  56072. return PlayAnimationAction;
  56073. }(BABYLON.Action));
  56074. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56075. /**
  56076. * This defines an action responsible to stop an animation once triggered.
  56077. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56078. */
  56079. var StopAnimationAction = /** @class */ (function (_super) {
  56080. __extends(StopAnimationAction, _super);
  56081. /**
  56082. * Instantiate the action
  56083. * @param triggerOptions defines the trigger options
  56084. * @param target defines the target animation or animation name
  56085. * @param condition defines the trigger related conditions
  56086. */
  56087. function StopAnimationAction(triggerOptions, target, condition) {
  56088. var _this = _super.call(this, triggerOptions, condition) || this;
  56089. _this._target = target;
  56090. return _this;
  56091. }
  56092. /** @hidden */
  56093. StopAnimationAction.prototype._prepare = function () {
  56094. };
  56095. /**
  56096. * Execute the action and stop the animation.
  56097. */
  56098. StopAnimationAction.prototype.execute = function () {
  56099. var scene = this._actionManager.getScene();
  56100. scene.stopAnimation(this._target);
  56101. };
  56102. /**
  56103. * Serializes the actions and its related information.
  56104. * @param parent defines the object to serialize in
  56105. * @returns the serialized object
  56106. */
  56107. StopAnimationAction.prototype.serialize = function (parent) {
  56108. return _super.prototype._serialize.call(this, {
  56109. name: "StopAnimationAction",
  56110. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56111. }, parent);
  56112. };
  56113. return StopAnimationAction;
  56114. }(BABYLON.Action));
  56115. BABYLON.StopAnimationAction = StopAnimationAction;
  56116. /**
  56117. * This defines an action responsible that does nothing once triggered.
  56118. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56119. */
  56120. var DoNothingAction = /** @class */ (function (_super) {
  56121. __extends(DoNothingAction, _super);
  56122. /**
  56123. * Instantiate the action
  56124. * @param triggerOptions defines the trigger options
  56125. * @param condition defines the trigger related conditions
  56126. */
  56127. function DoNothingAction(triggerOptions, condition) {
  56128. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56129. return _super.call(this, triggerOptions, condition) || this;
  56130. }
  56131. /**
  56132. * Execute the action and do nothing.
  56133. */
  56134. DoNothingAction.prototype.execute = function () {
  56135. };
  56136. /**
  56137. * Serializes the actions and its related information.
  56138. * @param parent defines the object to serialize in
  56139. * @returns the serialized object
  56140. */
  56141. DoNothingAction.prototype.serialize = function (parent) {
  56142. return _super.prototype._serialize.call(this, {
  56143. name: "DoNothingAction",
  56144. properties: []
  56145. }, parent);
  56146. };
  56147. return DoNothingAction;
  56148. }(BABYLON.Action));
  56149. BABYLON.DoNothingAction = DoNothingAction;
  56150. /**
  56151. * This defines an action responsible to trigger several actions once triggered.
  56152. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56153. */
  56154. var CombineAction = /** @class */ (function (_super) {
  56155. __extends(CombineAction, _super);
  56156. /**
  56157. * Instantiate the action
  56158. * @param triggerOptions defines the trigger options
  56159. * @param children defines the list of aggregated animations to run
  56160. * @param condition defines the trigger related conditions
  56161. */
  56162. function CombineAction(triggerOptions, children, condition) {
  56163. var _this = _super.call(this, triggerOptions, condition) || this;
  56164. _this.children = children;
  56165. return _this;
  56166. }
  56167. /** @hidden */
  56168. CombineAction.prototype._prepare = function () {
  56169. for (var index = 0; index < this.children.length; index++) {
  56170. this.children[index]._actionManager = this._actionManager;
  56171. this.children[index]._prepare();
  56172. }
  56173. };
  56174. /**
  56175. * Execute the action and executes all the aggregated actions.
  56176. */
  56177. CombineAction.prototype.execute = function (evt) {
  56178. for (var index = 0; index < this.children.length; index++) {
  56179. this.children[index].execute(evt);
  56180. }
  56181. };
  56182. /**
  56183. * Serializes the actions and its related information.
  56184. * @param parent defines the object to serialize in
  56185. * @returns the serialized object
  56186. */
  56187. CombineAction.prototype.serialize = function (parent) {
  56188. var serializationObject = _super.prototype._serialize.call(this, {
  56189. name: "CombineAction",
  56190. properties: [],
  56191. combine: []
  56192. }, parent);
  56193. for (var i = 0; i < this.children.length; i++) {
  56194. serializationObject.combine.push(this.children[i].serialize(null));
  56195. }
  56196. return serializationObject;
  56197. };
  56198. return CombineAction;
  56199. }(BABYLON.Action));
  56200. BABYLON.CombineAction = CombineAction;
  56201. /**
  56202. * This defines an action responsible to run code (external event) once triggered.
  56203. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56204. */
  56205. var ExecuteCodeAction = /** @class */ (function (_super) {
  56206. __extends(ExecuteCodeAction, _super);
  56207. /**
  56208. * Instantiate the action
  56209. * @param triggerOptions defines the trigger options
  56210. * @param func defines the callback function to run
  56211. * @param condition defines the trigger related conditions
  56212. */
  56213. function ExecuteCodeAction(triggerOptions, func, condition) {
  56214. var _this = _super.call(this, triggerOptions, condition) || this;
  56215. _this.func = func;
  56216. return _this;
  56217. }
  56218. /**
  56219. * Execute the action and run the attached code.
  56220. */
  56221. ExecuteCodeAction.prototype.execute = function (evt) {
  56222. this.func(evt);
  56223. };
  56224. return ExecuteCodeAction;
  56225. }(BABYLON.Action));
  56226. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56227. /**
  56228. * This defines an action responsible to set the parent property of the target once triggered.
  56229. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56230. */
  56231. var SetParentAction = /** @class */ (function (_super) {
  56232. __extends(SetParentAction, _super);
  56233. /**
  56234. * Instantiate the action
  56235. * @param triggerOptions defines the trigger options
  56236. * @param target defines the target containing the parent property
  56237. * @param parent defines from where the animation should start (animation frame)
  56238. * @param condition defines the trigger related conditions
  56239. */
  56240. function SetParentAction(triggerOptions, target, parent, condition) {
  56241. var _this = _super.call(this, triggerOptions, condition) || this;
  56242. _this._target = target;
  56243. _this._parent = parent;
  56244. return _this;
  56245. }
  56246. /** @hidden */
  56247. SetParentAction.prototype._prepare = function () {
  56248. };
  56249. /**
  56250. * Execute the action and set the parent property.
  56251. */
  56252. SetParentAction.prototype.execute = function () {
  56253. if (this._target.parent === this._parent) {
  56254. return;
  56255. }
  56256. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56257. invertParentWorldMatrix.invert();
  56258. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56259. this._target.parent = this._parent;
  56260. };
  56261. /**
  56262. * Serializes the actions and its related information.
  56263. * @param parent defines the object to serialize in
  56264. * @returns the serialized object
  56265. */
  56266. SetParentAction.prototype.serialize = function (parent) {
  56267. return _super.prototype._serialize.call(this, {
  56268. name: "SetParentAction",
  56269. properties: [
  56270. BABYLON.Action._GetTargetProperty(this._target),
  56271. BABYLON.Action._GetTargetProperty(this._parent),
  56272. ]
  56273. }, parent);
  56274. };
  56275. return SetParentAction;
  56276. }(BABYLON.Action));
  56277. BABYLON.SetParentAction = SetParentAction;
  56278. })(BABYLON || (BABYLON = {}));
  56279. //# sourceMappingURL=babylon.directActions.js.map
  56280. var BABYLON;
  56281. (function (BABYLON) {
  56282. /**
  56283. * Class used to manage multiple sprites on the same spritesheet
  56284. * @see http://doc.babylonjs.com/babylon101/sprites
  56285. */
  56286. var SpriteManager = /** @class */ (function () {
  56287. /**
  56288. * Creates a new sprite manager
  56289. * @param name defines the manager's name
  56290. * @param imgUrl defines the sprite sheet url
  56291. * @param capacity defines the maximum allowed number of sprites
  56292. * @param cellSize defines the size of a sprite cell
  56293. * @param scene defines the hosting scene
  56294. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56295. * @param samplingMode defines the smapling mode to use with spritesheet
  56296. */
  56297. function SpriteManager(
  56298. /** defines the manager's name */
  56299. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56300. if (epsilon === void 0) { epsilon = 0.01; }
  56301. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56302. this.name = name;
  56303. /** Gets the list of sprites */
  56304. this.sprites = new Array();
  56305. /** Gets or sets the rendering group id (0 by default) */
  56306. this.renderingGroupId = 0;
  56307. /** Gets or sets camera layer mask */
  56308. this.layerMask = 0x0FFFFFFF;
  56309. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56310. this.fogEnabled = true;
  56311. /** Gets or sets a boolean indicating if the sprites are pickable */
  56312. this.isPickable = false;
  56313. /**
  56314. * An event triggered when the manager is disposed.
  56315. */
  56316. this.onDisposeObservable = new BABYLON.Observable();
  56317. this._vertexBuffers = {};
  56318. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56319. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56320. }
  56321. this._capacity = capacity;
  56322. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56323. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56324. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56325. if (cellSize.width && cellSize.height) {
  56326. this.cellWidth = cellSize.width;
  56327. this.cellHeight = cellSize.height;
  56328. }
  56329. else if (cellSize !== undefined) {
  56330. this.cellWidth = cellSize;
  56331. this.cellHeight = cellSize;
  56332. }
  56333. else {
  56334. return;
  56335. }
  56336. this._epsilon = epsilon;
  56337. this._scene = scene;
  56338. this._scene.spriteManagers.push(this);
  56339. var indices = [];
  56340. var index = 0;
  56341. for (var count = 0; count < capacity; count++) {
  56342. indices.push(index);
  56343. indices.push(index + 1);
  56344. indices.push(index + 2);
  56345. indices.push(index);
  56346. indices.push(index + 2);
  56347. indices.push(index + 3);
  56348. index += 4;
  56349. }
  56350. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56351. // VBO
  56352. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56353. this._vertexData = new Float32Array(capacity * 16 * 4);
  56354. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56355. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56356. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56357. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56358. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56359. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56360. this._vertexBuffers["options"] = options;
  56361. this._vertexBuffers["cellInfo"] = cellInfo;
  56362. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56363. // Effects
  56364. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56365. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56366. }
  56367. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56368. /**
  56369. * Callback called when the manager is disposed
  56370. */
  56371. set: function (callback) {
  56372. if (this._onDisposeObserver) {
  56373. this.onDisposeObservable.remove(this._onDisposeObserver);
  56374. }
  56375. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56376. },
  56377. enumerable: true,
  56378. configurable: true
  56379. });
  56380. Object.defineProperty(SpriteManager.prototype, "texture", {
  56381. /**
  56382. * Gets or sets the spritesheet texture
  56383. */
  56384. get: function () {
  56385. return this._spriteTexture;
  56386. },
  56387. set: function (value) {
  56388. this._spriteTexture = value;
  56389. },
  56390. enumerable: true,
  56391. configurable: true
  56392. });
  56393. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56394. var arrayOffset = index * 16;
  56395. if (offsetX === 0)
  56396. offsetX = this._epsilon;
  56397. else if (offsetX === 1)
  56398. offsetX = 1 - this._epsilon;
  56399. if (offsetY === 0)
  56400. offsetY = this._epsilon;
  56401. else if (offsetY === 1)
  56402. offsetY = 1 - this._epsilon;
  56403. this._vertexData[arrayOffset] = sprite.position.x;
  56404. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56405. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56406. this._vertexData[arrayOffset + 3] = sprite.angle;
  56407. this._vertexData[arrayOffset + 4] = sprite.width;
  56408. this._vertexData[arrayOffset + 5] = sprite.height;
  56409. this._vertexData[arrayOffset + 6] = offsetX;
  56410. this._vertexData[arrayOffset + 7] = offsetY;
  56411. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56412. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56413. var offset = (sprite.cellIndex / rowSize) >> 0;
  56414. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56415. this._vertexData[arrayOffset + 11] = offset;
  56416. // Color
  56417. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56418. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56419. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56420. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56421. };
  56422. /**
  56423. * Intersects the sprites with a ray
  56424. * @param ray defines the ray to intersect with
  56425. * @param camera defines the current active camera
  56426. * @param predicate defines a predicate used to select candidate sprites
  56427. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56428. * @returns null if no hit or a PickingInfo
  56429. */
  56430. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56431. var count = Math.min(this._capacity, this.sprites.length);
  56432. var min = BABYLON.Vector3.Zero();
  56433. var max = BABYLON.Vector3.Zero();
  56434. var distance = Number.MAX_VALUE;
  56435. var currentSprite = null;
  56436. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56437. var cameraView = camera.getViewMatrix();
  56438. for (var index = 0; index < count; index++) {
  56439. var sprite = this.sprites[index];
  56440. if (!sprite) {
  56441. continue;
  56442. }
  56443. if (predicate) {
  56444. if (!predicate(sprite)) {
  56445. continue;
  56446. }
  56447. }
  56448. else if (!sprite.isPickable) {
  56449. continue;
  56450. }
  56451. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56452. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56453. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56454. if (ray.intersectsBoxMinMax(min, max)) {
  56455. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56456. if (distance > currentDistance) {
  56457. distance = currentDistance;
  56458. currentSprite = sprite;
  56459. if (fastCheck) {
  56460. break;
  56461. }
  56462. }
  56463. }
  56464. }
  56465. if (currentSprite) {
  56466. var result = new BABYLON.PickingInfo();
  56467. result.hit = true;
  56468. result.pickedSprite = currentSprite;
  56469. result.distance = distance;
  56470. return result;
  56471. }
  56472. return null;
  56473. };
  56474. /**
  56475. * Render all child sprites
  56476. */
  56477. SpriteManager.prototype.render = function () {
  56478. // Check
  56479. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  56480. return;
  56481. var engine = this._scene.getEngine();
  56482. var baseSize = this._spriteTexture.getBaseSize();
  56483. // Sprites
  56484. var deltaTime = engine.getDeltaTime();
  56485. var max = Math.min(this._capacity, this.sprites.length);
  56486. var rowSize = baseSize.width / this.cellWidth;
  56487. var offset = 0;
  56488. for (var index = 0; index < max; index++) {
  56489. var sprite = this.sprites[index];
  56490. if (!sprite || !sprite.isVisible) {
  56491. continue;
  56492. }
  56493. sprite._animate(deltaTime);
  56494. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56495. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56496. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56497. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56498. }
  56499. this._buffer.update(this._vertexData);
  56500. // Render
  56501. var effect = this._effectBase;
  56502. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56503. effect = this._effectFog;
  56504. }
  56505. engine.enableEffect(effect);
  56506. var viewMatrix = this._scene.getViewMatrix();
  56507. effect.setTexture("diffuseSampler", this._spriteTexture);
  56508. effect.setMatrix("view", viewMatrix);
  56509. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56510. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56511. // Fog
  56512. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56513. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56514. effect.setColor3("vFogColor", this._scene.fogColor);
  56515. }
  56516. // VBOs
  56517. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56518. // Draw order
  56519. engine.setDepthFunctionToLessOrEqual();
  56520. effect.setBool("alphaTest", true);
  56521. engine.setColorWrite(false);
  56522. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56523. engine.setColorWrite(true);
  56524. effect.setBool("alphaTest", false);
  56525. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56526. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56527. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56528. };
  56529. /**
  56530. * Release associated resources
  56531. */
  56532. SpriteManager.prototype.dispose = function () {
  56533. if (this._buffer) {
  56534. this._buffer.dispose();
  56535. this._buffer = null;
  56536. }
  56537. if (this._indexBuffer) {
  56538. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56539. this._indexBuffer = null;
  56540. }
  56541. if (this._spriteTexture) {
  56542. this._spriteTexture.dispose();
  56543. this._spriteTexture = null;
  56544. }
  56545. // Remove from scene
  56546. var index = this._scene.spriteManagers.indexOf(this);
  56547. this._scene.spriteManagers.splice(index, 1);
  56548. // Callback
  56549. this.onDisposeObservable.notifyObservers(this);
  56550. this.onDisposeObservable.clear();
  56551. };
  56552. return SpriteManager;
  56553. }());
  56554. BABYLON.SpriteManager = SpriteManager;
  56555. })(BABYLON || (BABYLON = {}));
  56556. //# sourceMappingURL=babylon.spriteManager.js.map
  56557. var BABYLON;
  56558. (function (BABYLON) {
  56559. /**
  56560. * Class used to represent a sprite
  56561. * @see http://doc.babylonjs.com/babylon101/sprites
  56562. */
  56563. var Sprite = /** @class */ (function () {
  56564. /**
  56565. * Creates a new Sprite
  56566. * @param name defines the name
  56567. * @param manager defines the manager
  56568. */
  56569. function Sprite(
  56570. /** defines the name */
  56571. name, manager) {
  56572. this.name = name;
  56573. /** Gets or sets the main color */
  56574. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56575. /** Gets or sets the width */
  56576. this.width = 1.0;
  56577. /** Gets or sets the height */
  56578. this.height = 1.0;
  56579. /** Gets or sets rotation angle */
  56580. this.angle = 0;
  56581. /** Gets or sets the cell index in the sprite sheet */
  56582. this.cellIndex = 0;
  56583. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56584. this.invertU = 0;
  56585. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56586. this.invertV = 0;
  56587. /** Gets the list of attached animations */
  56588. this.animations = new Array();
  56589. /** Gets or sets a boolean indicating if the sprite can be picked */
  56590. this.isPickable = false;
  56591. this._animationStarted = false;
  56592. this._loopAnimation = false;
  56593. this._fromIndex = 0;
  56594. this._toIndex = 0;
  56595. this._delay = 0;
  56596. this._direction = 1;
  56597. this._time = 0;
  56598. /**
  56599. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56600. */
  56601. this.isVisible = true;
  56602. this._manager = manager;
  56603. this._manager.sprites.push(this);
  56604. this.position = BABYLON.Vector3.Zero();
  56605. }
  56606. Object.defineProperty(Sprite.prototype, "size", {
  56607. /**
  56608. * Gets or sets the sprite size
  56609. */
  56610. get: function () {
  56611. return this.width;
  56612. },
  56613. set: function (value) {
  56614. this.width = value;
  56615. this.height = value;
  56616. },
  56617. enumerable: true,
  56618. configurable: true
  56619. });
  56620. /**
  56621. * Starts an animation
  56622. * @param from defines the initial key
  56623. * @param to defines the end key
  56624. * @param loop defines if the animation must loop
  56625. * @param delay defines the start delay (in ms)
  56626. * @param onAnimationEnd defines a callback to call when animation ends
  56627. */
  56628. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56629. this._fromIndex = from;
  56630. this._toIndex = to;
  56631. this._loopAnimation = loop;
  56632. this._delay = delay;
  56633. this._animationStarted = true;
  56634. this._direction = from < to ? 1 : -1;
  56635. this.cellIndex = from;
  56636. this._time = 0;
  56637. this._onAnimationEnd = onAnimationEnd;
  56638. };
  56639. /** Stops current animation (if any) */
  56640. Sprite.prototype.stopAnimation = function () {
  56641. this._animationStarted = false;
  56642. };
  56643. /** @hidden */
  56644. Sprite.prototype._animate = function (deltaTime) {
  56645. if (!this._animationStarted)
  56646. return;
  56647. this._time += deltaTime;
  56648. if (this._time > this._delay) {
  56649. this._time = this._time % this._delay;
  56650. this.cellIndex += this._direction;
  56651. if (this.cellIndex > this._toIndex) {
  56652. if (this._loopAnimation) {
  56653. this.cellIndex = this._fromIndex;
  56654. }
  56655. else {
  56656. this.cellIndex = this._toIndex;
  56657. this._animationStarted = false;
  56658. if (this._onAnimationEnd) {
  56659. this._onAnimationEnd();
  56660. }
  56661. if (this.disposeWhenFinishedAnimating) {
  56662. this.dispose();
  56663. }
  56664. }
  56665. }
  56666. }
  56667. };
  56668. /** Release associated resources */
  56669. Sprite.prototype.dispose = function () {
  56670. for (var i = 0; i < this._manager.sprites.length; i++) {
  56671. if (this._manager.sprites[i] == this) {
  56672. this._manager.sprites.splice(i, 1);
  56673. }
  56674. }
  56675. };
  56676. return Sprite;
  56677. }());
  56678. BABYLON.Sprite = Sprite;
  56679. })(BABYLON || (BABYLON = {}));
  56680. //# sourceMappingURL=babylon.sprite.js.map
  56681. var BABYLON;
  56682. (function (BABYLON) {
  56683. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56684. if (!BABYLON.PickingInfo) {
  56685. return null;
  56686. }
  56687. var pickingInfo = null;
  56688. if (!camera) {
  56689. if (!this.activeCamera) {
  56690. return null;
  56691. }
  56692. camera = this.activeCamera;
  56693. }
  56694. if (this.spriteManagers.length > 0) {
  56695. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56696. var spriteManager = this.spriteManagers[spriteIndex];
  56697. if (!spriteManager.isPickable) {
  56698. continue;
  56699. }
  56700. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56701. if (!result || !result.hit)
  56702. continue;
  56703. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56704. continue;
  56705. pickingInfo = result;
  56706. if (fastCheck) {
  56707. break;
  56708. }
  56709. }
  56710. }
  56711. return pickingInfo || new BABYLON.PickingInfo();
  56712. };
  56713. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56714. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56715. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56716. };
  56717. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56718. if (!this._tempSpritePickingRay) {
  56719. return null;
  56720. }
  56721. if (!camera) {
  56722. if (!this.activeCamera) {
  56723. return null;
  56724. }
  56725. camera = this.activeCamera;
  56726. }
  56727. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56728. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56729. };
  56730. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56731. if (this._pointerOverSprite === sprite) {
  56732. return;
  56733. }
  56734. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56735. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56736. }
  56737. this._pointerOverSprite = sprite;
  56738. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56739. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56740. }
  56741. };
  56742. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56743. return this._pointerOverSprite;
  56744. };
  56745. /**
  56746. * Defines the sprite scene component responsible to manage sprites
  56747. * in a given scene.
  56748. */
  56749. var SpriteSceneComponent = /** @class */ (function () {
  56750. /**
  56751. * Creates a new instance of the component for the given scene
  56752. * @param scene Defines the scene to register the component in
  56753. */
  56754. function SpriteSceneComponent(scene) {
  56755. /**
  56756. * The component name helpfull to identify the component in the list of scene components.
  56757. */
  56758. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56759. this.scene = scene;
  56760. this.scene.spriteManagers = new Array();
  56761. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56762. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56763. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56764. this._spritePredicate = function (sprite) {
  56765. if (!sprite.actionManager) {
  56766. return false;
  56767. }
  56768. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  56769. };
  56770. }
  56771. /**
  56772. * Registers the component in a given scene
  56773. */
  56774. SpriteSceneComponent.prototype.register = function () {
  56775. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56776. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56777. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56778. };
  56779. /**
  56780. * Rebuilds the elements related to this component in case of
  56781. * context lost for instance.
  56782. */
  56783. SpriteSceneComponent.prototype.rebuild = function () {
  56784. /** Nothing to do for sprites */
  56785. };
  56786. /**
  56787. * Disposes the component and the associated ressources.
  56788. */
  56789. SpriteSceneComponent.prototype.dispose = function () {
  56790. this.scene.onBeforeSpritesRenderingObservable.clear();
  56791. this.scene.onAfterSpritesRenderingObservable.clear();
  56792. var spriteManagers = this.scene.spriteManagers;
  56793. while (spriteManagers.length) {
  56794. spriteManagers[0].dispose();
  56795. }
  56796. };
  56797. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56798. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56799. if (result) {
  56800. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56801. }
  56802. return result;
  56803. };
  56804. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56805. var scene = this.scene;
  56806. if (isMeshPicked) {
  56807. scene.setPointerOverSprite(null);
  56808. }
  56809. else {
  56810. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56811. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56812. scene.setPointerOverSprite(pickResult.pickedSprite);
  56813. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56814. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56815. }
  56816. else {
  56817. canvas.style.cursor = scene.hoverCursor;
  56818. }
  56819. }
  56820. else {
  56821. scene.setPointerOverSprite(null);
  56822. }
  56823. }
  56824. return pickResult;
  56825. };
  56826. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56827. var scene = this.scene;
  56828. scene._pickedDownSprite = null;
  56829. if (scene.spriteManagers.length > 0) {
  56830. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56831. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56832. if (pickResult.pickedSprite.actionManager) {
  56833. scene._pickedDownSprite = pickResult.pickedSprite;
  56834. switch (evt.button) {
  56835. case 0:
  56836. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56837. break;
  56838. case 1:
  56839. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56840. break;
  56841. case 2:
  56842. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56843. break;
  56844. }
  56845. if (pickResult.pickedSprite.actionManager) {
  56846. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56847. }
  56848. }
  56849. }
  56850. }
  56851. return pickResult;
  56852. };
  56853. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56854. var scene = this.scene;
  56855. if (scene.spriteManagers.length > 0) {
  56856. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56857. if (spritePickResult) {
  56858. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56859. if (spritePickResult.pickedSprite.actionManager) {
  56860. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56861. if (spritePickResult.pickedSprite.actionManager) {
  56862. if (!this.scene._isPointerSwiping()) {
  56863. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56864. }
  56865. }
  56866. }
  56867. }
  56868. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56869. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56870. }
  56871. }
  56872. }
  56873. return pickResult;
  56874. };
  56875. return SpriteSceneComponent;
  56876. }());
  56877. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56878. })(BABYLON || (BABYLON = {}));
  56879. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56880. var BABYLON;
  56881. (function (BABYLON) {
  56882. /**
  56883. * @hidden
  56884. */
  56885. var IntersectionInfo = /** @class */ (function () {
  56886. function IntersectionInfo(bu, bv, distance) {
  56887. this.bu = bu;
  56888. this.bv = bv;
  56889. this.distance = distance;
  56890. this.faceId = 0;
  56891. this.subMeshId = 0;
  56892. }
  56893. return IntersectionInfo;
  56894. }());
  56895. BABYLON.IntersectionInfo = IntersectionInfo;
  56896. /**
  56897. * Information about the result of picking within a scene
  56898. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56899. */
  56900. var PickingInfo = /** @class */ (function () {
  56901. function PickingInfo() {
  56902. /**
  56903. * If the pick collided with an object
  56904. */
  56905. this.hit = false;
  56906. /**
  56907. * Distance away where the pick collided
  56908. */
  56909. this.distance = 0;
  56910. /**
  56911. * The location of pick collision
  56912. */
  56913. this.pickedPoint = null;
  56914. /**
  56915. * The mesh corresponding the the pick collision
  56916. */
  56917. this.pickedMesh = null;
  56918. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56919. this.bu = 0;
  56920. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56921. this.bv = 0;
  56922. /** The id of the face on the mesh that was picked */
  56923. this.faceId = -1;
  56924. /** Id of the the submesh that was picked */
  56925. this.subMeshId = 0;
  56926. /** If a sprite was picked, this will be the sprite the pick collided with */
  56927. this.pickedSprite = null;
  56928. /**
  56929. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56930. */
  56931. this.originMesh = null;
  56932. /**
  56933. * The ray that was used to perform the picking.
  56934. */
  56935. this.ray = null;
  56936. }
  56937. /**
  56938. * Gets the normal correspodning to the face the pick collided with
  56939. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56940. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56941. * @returns The normal correspodning to the face the pick collided with
  56942. */
  56943. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56944. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56945. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56946. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56947. return null;
  56948. }
  56949. var indices = this.pickedMesh.getIndices();
  56950. if (!indices) {
  56951. return null;
  56952. }
  56953. var result;
  56954. if (useVerticesNormals) {
  56955. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56956. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56957. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56958. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56959. normal0 = normal0.scale(this.bu);
  56960. normal1 = normal1.scale(this.bv);
  56961. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56962. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56963. }
  56964. else {
  56965. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56966. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56967. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56968. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56969. var p1p2 = vertex1.subtract(vertex2);
  56970. var p3p2 = vertex3.subtract(vertex2);
  56971. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56972. }
  56973. if (useWorldCoordinates) {
  56974. var wm = this.pickedMesh.getWorldMatrix();
  56975. if (this.pickedMesh.nonUniformScaling) {
  56976. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  56977. wm = BABYLON.Tmp.Matrix[0];
  56978. wm.setTranslationFromFloats(0, 0, 0);
  56979. wm.invert();
  56980. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  56981. wm = BABYLON.Tmp.Matrix[1];
  56982. }
  56983. result = BABYLON.Vector3.TransformNormal(result, wm);
  56984. }
  56985. result.normalize();
  56986. return result;
  56987. };
  56988. /**
  56989. * Gets the texture coordinates of where the pick occured
  56990. * @returns the vector containing the coordnates of the texture
  56991. */
  56992. PickingInfo.prototype.getTextureCoordinates = function () {
  56993. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56994. return null;
  56995. }
  56996. var indices = this.pickedMesh.getIndices();
  56997. if (!indices) {
  56998. return null;
  56999. }
  57000. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57001. if (!uvs) {
  57002. return null;
  57003. }
  57004. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  57005. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  57006. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  57007. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  57008. uv1 = uv1.scale(this.bu);
  57009. uv2 = uv2.scale(this.bv);
  57010. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  57011. };
  57012. return PickingInfo;
  57013. }());
  57014. BABYLON.PickingInfo = PickingInfo;
  57015. })(BABYLON || (BABYLON = {}));
  57016. //# sourceMappingURL=babylon.pickingInfo.js.map
  57017. var BABYLON;
  57018. (function (BABYLON) {
  57019. /**
  57020. * Class representing a ray with position and direction
  57021. */
  57022. var Ray = /** @class */ (function () {
  57023. /**
  57024. * Creates a new ray
  57025. * @param origin origin point
  57026. * @param direction direction
  57027. * @param length length of the ray
  57028. */
  57029. function Ray(
  57030. /** origin point */
  57031. origin,
  57032. /** direction */
  57033. direction,
  57034. /** length of the ray */
  57035. length) {
  57036. if (length === void 0) { length = Number.MAX_VALUE; }
  57037. this.origin = origin;
  57038. this.direction = direction;
  57039. this.length = length;
  57040. }
  57041. // Methods
  57042. /**
  57043. * Checks if the ray intersects a box
  57044. * @param minimum bound of the box
  57045. * @param maximum bound of the box
  57046. * @returns if the box was hit
  57047. */
  57048. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57049. var d = 0.0;
  57050. var maxValue = Number.MAX_VALUE;
  57051. var inv;
  57052. var min;
  57053. var max;
  57054. var temp;
  57055. if (Math.abs(this.direction.x) < 0.0000001) {
  57056. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57057. return false;
  57058. }
  57059. }
  57060. else {
  57061. inv = 1.0 / this.direction.x;
  57062. min = (minimum.x - this.origin.x) * inv;
  57063. max = (maximum.x - this.origin.x) * inv;
  57064. if (max === -Infinity) {
  57065. max = Infinity;
  57066. }
  57067. if (min > max) {
  57068. temp = min;
  57069. min = max;
  57070. max = temp;
  57071. }
  57072. d = Math.max(min, d);
  57073. maxValue = Math.min(max, maxValue);
  57074. if (d > maxValue) {
  57075. return false;
  57076. }
  57077. }
  57078. if (Math.abs(this.direction.y) < 0.0000001) {
  57079. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57080. return false;
  57081. }
  57082. }
  57083. else {
  57084. inv = 1.0 / this.direction.y;
  57085. min = (minimum.y - this.origin.y) * inv;
  57086. max = (maximum.y - this.origin.y) * inv;
  57087. if (max === -Infinity) {
  57088. max = Infinity;
  57089. }
  57090. if (min > max) {
  57091. temp = min;
  57092. min = max;
  57093. max = temp;
  57094. }
  57095. d = Math.max(min, d);
  57096. maxValue = Math.min(max, maxValue);
  57097. if (d > maxValue) {
  57098. return false;
  57099. }
  57100. }
  57101. if (Math.abs(this.direction.z) < 0.0000001) {
  57102. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57103. return false;
  57104. }
  57105. }
  57106. else {
  57107. inv = 1.0 / this.direction.z;
  57108. min = (minimum.z - this.origin.z) * inv;
  57109. max = (maximum.z - this.origin.z) * inv;
  57110. if (max === -Infinity) {
  57111. max = Infinity;
  57112. }
  57113. if (min > max) {
  57114. temp = min;
  57115. min = max;
  57116. max = temp;
  57117. }
  57118. d = Math.max(min, d);
  57119. maxValue = Math.min(max, maxValue);
  57120. if (d > maxValue) {
  57121. return false;
  57122. }
  57123. }
  57124. return true;
  57125. };
  57126. /**
  57127. * Checks if the ray intersects a box
  57128. * @param box the bounding box to check
  57129. * @returns if the box was hit
  57130. */
  57131. Ray.prototype.intersectsBox = function (box) {
  57132. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57133. };
  57134. /**
  57135. * If the ray hits a sphere
  57136. * @param sphere the bounding sphere to check
  57137. * @returns true if it hits the sphere
  57138. */
  57139. Ray.prototype.intersectsSphere = function (sphere) {
  57140. var x = sphere.center.x - this.origin.x;
  57141. var y = sphere.center.y - this.origin.y;
  57142. var z = sphere.center.z - this.origin.z;
  57143. var pyth = (x * x) + (y * y) + (z * z);
  57144. var rr = sphere.radius * sphere.radius;
  57145. if (pyth <= rr) {
  57146. return true;
  57147. }
  57148. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57149. if (dot < 0.0) {
  57150. return false;
  57151. }
  57152. var temp = pyth - (dot * dot);
  57153. return temp <= rr;
  57154. };
  57155. /**
  57156. * If the ray hits a triange
  57157. * @param vertex0 triangle vertex
  57158. * @param vertex1 triangle vertex
  57159. * @param vertex2 triangle vertex
  57160. * @returns intersection information if hit
  57161. */
  57162. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57163. if (!this._edge1) {
  57164. this._edge1 = BABYLON.Vector3.Zero();
  57165. this._edge2 = BABYLON.Vector3.Zero();
  57166. this._pvec = BABYLON.Vector3.Zero();
  57167. this._tvec = BABYLON.Vector3.Zero();
  57168. this._qvec = BABYLON.Vector3.Zero();
  57169. }
  57170. vertex1.subtractToRef(vertex0, this._edge1);
  57171. vertex2.subtractToRef(vertex0, this._edge2);
  57172. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57173. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57174. if (det === 0) {
  57175. return null;
  57176. }
  57177. var invdet = 1 / det;
  57178. this.origin.subtractToRef(vertex0, this._tvec);
  57179. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57180. if (bu < 0 || bu > 1.0) {
  57181. return null;
  57182. }
  57183. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57184. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57185. if (bv < 0 || bu + bv > 1.0) {
  57186. return null;
  57187. }
  57188. //check if the distance is longer than the predefined length.
  57189. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57190. if (distance > this.length) {
  57191. return null;
  57192. }
  57193. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57194. };
  57195. /**
  57196. * Checks if ray intersects a plane
  57197. * @param plane the plane to check
  57198. * @returns the distance away it was hit
  57199. */
  57200. Ray.prototype.intersectsPlane = function (plane) {
  57201. var distance;
  57202. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57203. if (Math.abs(result1) < 9.99999997475243E-07) {
  57204. return null;
  57205. }
  57206. else {
  57207. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57208. distance = (-plane.d - result2) / result1;
  57209. if (distance < 0.0) {
  57210. if (distance < -9.99999997475243E-07) {
  57211. return null;
  57212. }
  57213. else {
  57214. return 0;
  57215. }
  57216. }
  57217. return distance;
  57218. }
  57219. };
  57220. /**
  57221. * Checks if ray intersects a mesh
  57222. * @param mesh the mesh to check
  57223. * @param fastCheck if only the bounding box should checked
  57224. * @returns picking info of the intersecton
  57225. */
  57226. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57227. var tm = BABYLON.Tmp.Matrix[0];
  57228. mesh.getWorldMatrix().invertToRef(tm);
  57229. if (this._tmpRay) {
  57230. Ray.TransformToRef(this, tm, this._tmpRay);
  57231. }
  57232. else {
  57233. this._tmpRay = Ray.Transform(this, tm);
  57234. }
  57235. return mesh.intersects(this._tmpRay, fastCheck);
  57236. };
  57237. /**
  57238. * Checks if ray intersects a mesh
  57239. * @param meshes the meshes to check
  57240. * @param fastCheck if only the bounding box should checked
  57241. * @param results array to store result in
  57242. * @returns Array of picking infos
  57243. */
  57244. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57245. if (results) {
  57246. results.length = 0;
  57247. }
  57248. else {
  57249. results = [];
  57250. }
  57251. for (var i = 0; i < meshes.length; i++) {
  57252. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57253. if (pickInfo.hit) {
  57254. results.push(pickInfo);
  57255. }
  57256. }
  57257. results.sort(this._comparePickingInfo);
  57258. return results;
  57259. };
  57260. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57261. if (pickingInfoA.distance < pickingInfoB.distance) {
  57262. return -1;
  57263. }
  57264. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57265. return 1;
  57266. }
  57267. else {
  57268. return 0;
  57269. }
  57270. };
  57271. /**
  57272. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57273. * @param sega the first point of the segment to test the intersection against
  57274. * @param segb the second point of the segment to test the intersection against
  57275. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57276. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57277. */
  57278. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57279. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57280. var u = segb.subtract(sega);
  57281. var v = rsegb.subtract(this.origin);
  57282. var w = sega.subtract(this.origin);
  57283. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57284. var b = BABYLON.Vector3.Dot(u, v);
  57285. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57286. var d = BABYLON.Vector3.Dot(u, w);
  57287. var e = BABYLON.Vector3.Dot(v, w);
  57288. var D = a * c - b * b; // always >= 0
  57289. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57290. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57291. // compute the line parameters of the two closest points
  57292. if (D < Ray.smallnum) { // the lines are almost parallel
  57293. sN = 0.0; // force using point P0 on segment S1
  57294. sD = 1.0; // to prevent possible division by 0.0 later
  57295. tN = e;
  57296. tD = c;
  57297. }
  57298. else { // get the closest points on the infinite lines
  57299. sN = (b * e - c * d);
  57300. tN = (a * e - b * d);
  57301. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57302. sN = 0.0;
  57303. tN = e;
  57304. tD = c;
  57305. }
  57306. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57307. sN = sD;
  57308. tN = e + b;
  57309. tD = c;
  57310. }
  57311. }
  57312. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57313. tN = 0.0;
  57314. // recompute sc for this edge
  57315. if (-d < 0.0) {
  57316. sN = 0.0;
  57317. }
  57318. else if (-d > a)
  57319. sN = sD;
  57320. else {
  57321. sN = -d;
  57322. sD = a;
  57323. }
  57324. }
  57325. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57326. tN = tD;
  57327. // recompute sc for this edge
  57328. if ((-d + b) < 0.0) {
  57329. sN = 0;
  57330. }
  57331. else if ((-d + b) > a) {
  57332. sN = sD;
  57333. }
  57334. else {
  57335. sN = (-d + b);
  57336. sD = a;
  57337. }
  57338. }
  57339. // finally do the division to get sc and tc
  57340. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57341. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57342. // get the difference of the two closest points
  57343. var qtc = v.multiplyByFloats(tc, tc, tc);
  57344. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57345. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57346. if (isIntersected) {
  57347. return qtc.length();
  57348. }
  57349. return -1;
  57350. };
  57351. /**
  57352. * Update the ray from viewport position
  57353. * @param x position
  57354. * @param y y position
  57355. * @param viewportWidth viewport width
  57356. * @param viewportHeight viewport height
  57357. * @param world world matrix
  57358. * @param view view matrix
  57359. * @param projection projection matrix
  57360. * @returns this ray updated
  57361. */
  57362. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57363. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57364. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57365. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57366. this.direction.normalize();
  57367. return this;
  57368. };
  57369. // Statics
  57370. /**
  57371. * Creates a ray with origin and direction of 0,0,0
  57372. * @returns the new ray
  57373. */
  57374. Ray.Zero = function () {
  57375. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57376. };
  57377. /**
  57378. * Creates a new ray from screen space and viewport
  57379. * @param x position
  57380. * @param y y position
  57381. * @param viewportWidth viewport width
  57382. * @param viewportHeight viewport height
  57383. * @param world world matrix
  57384. * @param view view matrix
  57385. * @param projection projection matrix
  57386. * @returns new ray
  57387. */
  57388. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57389. var result = Ray.Zero();
  57390. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57391. };
  57392. /**
  57393. * 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
  57394. * transformed to the given world matrix.
  57395. * @param origin The origin point
  57396. * @param end The end point
  57397. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57398. * @returns the new ray
  57399. */
  57400. Ray.CreateNewFromTo = function (origin, end, world) {
  57401. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57402. var direction = end.subtract(origin);
  57403. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57404. direction.normalize();
  57405. return Ray.Transform(new Ray(origin, direction, length), world);
  57406. };
  57407. /**
  57408. * Transforms a ray by a matrix
  57409. * @param ray ray to transform
  57410. * @param matrix matrix to apply
  57411. * @returns the resulting new ray
  57412. */
  57413. Ray.Transform = function (ray, matrix) {
  57414. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57415. Ray.TransformToRef(ray, matrix, result);
  57416. return result;
  57417. };
  57418. /**
  57419. * Transforms a ray by a matrix
  57420. * @param ray ray to transform
  57421. * @param matrix matrix to apply
  57422. * @param result ray to store result in
  57423. */
  57424. Ray.TransformToRef = function (ray, matrix, result) {
  57425. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57426. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57427. result.length = ray.length;
  57428. var dir = result.direction;
  57429. var len = dir.length();
  57430. if (!(len === 0 || len === 1)) {
  57431. var num = 1.0 / len;
  57432. dir.x *= num;
  57433. dir.y *= num;
  57434. dir.z *= num;
  57435. result.length *= len;
  57436. }
  57437. };
  57438. Ray.smallnum = 0.00000001;
  57439. Ray.rayl = 10e8;
  57440. return Ray;
  57441. }());
  57442. BABYLON.Ray = Ray;
  57443. })(BABYLON || (BABYLON = {}));
  57444. //# sourceMappingURL=babylon.ray.js.map
  57445. var BABYLON;
  57446. (function (BABYLON) {
  57447. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57448. if (boxMin.x > sphereCenter.x + sphereRadius)
  57449. return false;
  57450. if (sphereCenter.x - sphereRadius > boxMax.x)
  57451. return false;
  57452. if (boxMin.y > sphereCenter.y + sphereRadius)
  57453. return false;
  57454. if (sphereCenter.y - sphereRadius > boxMax.y)
  57455. return false;
  57456. if (boxMin.z > sphereCenter.z + sphereRadius)
  57457. return false;
  57458. if (sphereCenter.z - sphereRadius > boxMax.z)
  57459. return false;
  57460. return true;
  57461. };
  57462. var getLowestRoot = (function () {
  57463. var result = { root: 0, found: false };
  57464. return function (a, b, c, maxR) {
  57465. result.root = 0;
  57466. result.found = false;
  57467. var determinant = b * b - 4.0 * a * c;
  57468. if (determinant < 0)
  57469. return result;
  57470. var sqrtD = Math.sqrt(determinant);
  57471. var r1 = (-b - sqrtD) / (2.0 * a);
  57472. var r2 = (-b + sqrtD) / (2.0 * a);
  57473. if (r1 > r2) {
  57474. var temp = r2;
  57475. r2 = r1;
  57476. r1 = temp;
  57477. }
  57478. if (r1 > 0 && r1 < maxR) {
  57479. result.root = r1;
  57480. result.found = true;
  57481. return result;
  57482. }
  57483. if (r2 > 0 && r2 < maxR) {
  57484. result.root = r2;
  57485. result.found = true;
  57486. return result;
  57487. }
  57488. return result;
  57489. };
  57490. })();
  57491. /** @hidden */
  57492. var Collider = /** @class */ (function () {
  57493. function Collider() {
  57494. this._collisionPoint = BABYLON.Vector3.Zero();
  57495. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57496. this._tempVector = BABYLON.Vector3.Zero();
  57497. this._tempVector2 = BABYLON.Vector3.Zero();
  57498. this._tempVector3 = BABYLON.Vector3.Zero();
  57499. this._tempVector4 = BABYLON.Vector3.Zero();
  57500. this._edge = BABYLON.Vector3.Zero();
  57501. this._baseToVertex = BABYLON.Vector3.Zero();
  57502. this._destinationPoint = BABYLON.Vector3.Zero();
  57503. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57504. this._displacementVector = BABYLON.Vector3.Zero();
  57505. /** @hidden */
  57506. this._radius = BABYLON.Vector3.One();
  57507. /** @hidden */
  57508. this._retry = 0;
  57509. /** @hidden */
  57510. this._basePointWorld = BABYLON.Vector3.Zero();
  57511. this._velocityWorld = BABYLON.Vector3.Zero();
  57512. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57513. this._collisionMask = -1;
  57514. }
  57515. Object.defineProperty(Collider.prototype, "collisionMask", {
  57516. get: function () {
  57517. return this._collisionMask;
  57518. },
  57519. set: function (mask) {
  57520. this._collisionMask = !isNaN(mask) ? mask : -1;
  57521. },
  57522. enumerable: true,
  57523. configurable: true
  57524. });
  57525. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57526. /**
  57527. * Gets the plane normal used to compute the sliding response (in local space)
  57528. */
  57529. get: function () {
  57530. return this._slidePlaneNormal;
  57531. },
  57532. enumerable: true,
  57533. configurable: true
  57534. });
  57535. // Methods
  57536. /** @hidden */
  57537. Collider.prototype._initialize = function (source, dir, e) {
  57538. this._velocity = dir;
  57539. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57540. this._basePoint = source;
  57541. source.multiplyToRef(this._radius, this._basePointWorld);
  57542. dir.multiplyToRef(this._radius, this._velocityWorld);
  57543. this._velocityWorldLength = this._velocityWorld.length();
  57544. this._epsilon = e;
  57545. this.collisionFound = false;
  57546. };
  57547. /** @hidden */
  57548. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57549. pa.subtractToRef(point, this._tempVector);
  57550. pb.subtractToRef(point, this._tempVector2);
  57551. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57552. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57553. if (d < 0)
  57554. return false;
  57555. pc.subtractToRef(point, this._tempVector3);
  57556. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57557. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57558. if (d < 0)
  57559. return false;
  57560. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57561. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57562. return d >= 0;
  57563. };
  57564. /** @hidden */
  57565. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57566. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57567. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57568. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57569. return false;
  57570. }
  57571. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  57572. return false;
  57573. return true;
  57574. };
  57575. /** @hidden */
  57576. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57577. var t0;
  57578. var embeddedInPlane = false;
  57579. //defensive programming, actually not needed.
  57580. if (!trianglePlaneArray) {
  57581. trianglePlaneArray = [];
  57582. }
  57583. if (!trianglePlaneArray[faceIndex]) {
  57584. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57585. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57586. }
  57587. var trianglePlane = trianglePlaneArray[faceIndex];
  57588. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  57589. return;
  57590. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57591. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57592. if (normalDotVelocity == 0) {
  57593. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  57594. return;
  57595. embeddedInPlane = true;
  57596. t0 = 0;
  57597. }
  57598. else {
  57599. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57600. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57601. if (t0 > t1) {
  57602. var temp = t1;
  57603. t1 = t0;
  57604. t0 = temp;
  57605. }
  57606. if (t0 > 1.0 || t1 < 0.0)
  57607. return;
  57608. if (t0 < 0)
  57609. t0 = 0;
  57610. if (t0 > 1.0)
  57611. t0 = 1.0;
  57612. }
  57613. this._collisionPoint.copyFromFloats(0, 0, 0);
  57614. var found = false;
  57615. var t = 1.0;
  57616. if (!embeddedInPlane) {
  57617. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57618. this._velocity.scaleToRef(t0, this._tempVector);
  57619. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57620. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57621. found = true;
  57622. t = t0;
  57623. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57624. }
  57625. }
  57626. if (!found) {
  57627. var velocitySquaredLength = this._velocity.lengthSquared();
  57628. var a = velocitySquaredLength;
  57629. this._basePoint.subtractToRef(p1, this._tempVector);
  57630. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57631. var c = this._tempVector.lengthSquared() - 1.0;
  57632. var lowestRoot = getLowestRoot(a, b, c, t);
  57633. if (lowestRoot.found) {
  57634. t = lowestRoot.root;
  57635. found = true;
  57636. this._collisionPoint.copyFrom(p1);
  57637. }
  57638. this._basePoint.subtractToRef(p2, this._tempVector);
  57639. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57640. c = this._tempVector.lengthSquared() - 1.0;
  57641. lowestRoot = getLowestRoot(a, b, c, t);
  57642. if (lowestRoot.found) {
  57643. t = lowestRoot.root;
  57644. found = true;
  57645. this._collisionPoint.copyFrom(p2);
  57646. }
  57647. this._basePoint.subtractToRef(p3, this._tempVector);
  57648. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57649. c = this._tempVector.lengthSquared() - 1.0;
  57650. lowestRoot = getLowestRoot(a, b, c, t);
  57651. if (lowestRoot.found) {
  57652. t = lowestRoot.root;
  57653. found = true;
  57654. this._collisionPoint.copyFrom(p3);
  57655. }
  57656. p2.subtractToRef(p1, this._edge);
  57657. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57658. var edgeSquaredLength = this._edge.lengthSquared();
  57659. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57660. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57661. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57662. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57663. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57664. lowestRoot = getLowestRoot(a, b, c, t);
  57665. if (lowestRoot.found) {
  57666. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57667. if (f >= 0.0 && f <= 1.0) {
  57668. t = lowestRoot.root;
  57669. found = true;
  57670. this._edge.scaleInPlace(f);
  57671. p1.addToRef(this._edge, this._collisionPoint);
  57672. }
  57673. }
  57674. p3.subtractToRef(p2, this._edge);
  57675. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57676. edgeSquaredLength = this._edge.lengthSquared();
  57677. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57678. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57679. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57680. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57681. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57682. lowestRoot = getLowestRoot(a, b, c, t);
  57683. if (lowestRoot.found) {
  57684. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57685. if (f >= 0.0 && f <= 1.0) {
  57686. t = lowestRoot.root;
  57687. found = true;
  57688. this._edge.scaleInPlace(f);
  57689. p2.addToRef(this._edge, this._collisionPoint);
  57690. }
  57691. }
  57692. p1.subtractToRef(p3, this._edge);
  57693. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57694. edgeSquaredLength = this._edge.lengthSquared();
  57695. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57696. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57697. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57698. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57699. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57700. lowestRoot = getLowestRoot(a, b, c, t);
  57701. if (lowestRoot.found) {
  57702. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57703. if (f >= 0.0 && f <= 1.0) {
  57704. t = lowestRoot.root;
  57705. found = true;
  57706. this._edge.scaleInPlace(f);
  57707. p3.addToRef(this._edge, this._collisionPoint);
  57708. }
  57709. }
  57710. }
  57711. if (found) {
  57712. var distToCollision = t * this._velocity.length();
  57713. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57714. if (!this.intersectionPoint) {
  57715. this.intersectionPoint = this._collisionPoint.clone();
  57716. }
  57717. else {
  57718. this.intersectionPoint.copyFrom(this._collisionPoint);
  57719. }
  57720. this._nearestDistance = distToCollision;
  57721. this.collisionFound = true;
  57722. }
  57723. }
  57724. };
  57725. /** @hidden */
  57726. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57727. for (var i = indexStart; i < indexEnd; i += 3) {
  57728. var p1 = pts[indices[i] - decal];
  57729. var p2 = pts[indices[i + 1] - decal];
  57730. var p3 = pts[indices[i + 2] - decal];
  57731. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57732. }
  57733. };
  57734. /** @hidden */
  57735. Collider.prototype._getResponse = function (pos, vel) {
  57736. pos.addToRef(vel, this._destinationPoint);
  57737. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57738. this._basePoint.addToRef(vel, pos);
  57739. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57740. this._slidePlaneNormal.normalize();
  57741. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57742. pos.addInPlace(this._displacementVector);
  57743. this.intersectionPoint.addInPlace(this._displacementVector);
  57744. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57745. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57746. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57747. };
  57748. return Collider;
  57749. }());
  57750. BABYLON.Collider = Collider;
  57751. })(BABYLON || (BABYLON = {}));
  57752. //# sourceMappingURL=babylon.collider.js.map
  57753. var BABYLON;
  57754. (function (BABYLON) {
  57755. //WebWorker code will be inserted to this variable.
  57756. /** @hidden */
  57757. BABYLON.CollisionWorker = "";
  57758. /** Defines supported task for worker process */
  57759. var WorkerTaskType;
  57760. (function (WorkerTaskType) {
  57761. /** Initialization */
  57762. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57763. /** Update of geometry */
  57764. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57765. /** Evaluate collision */
  57766. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57767. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57768. /** Defines kind of replies returned by worker */
  57769. var WorkerReplyType;
  57770. (function (WorkerReplyType) {
  57771. /** Success */
  57772. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57773. /** Unkown error */
  57774. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57775. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57776. /** @hidden */
  57777. var CollisionCoordinatorWorker = /** @class */ (function () {
  57778. function CollisionCoordinatorWorker() {
  57779. var _this = this;
  57780. this._scaledPosition = BABYLON.Vector3.Zero();
  57781. this._scaledVelocity = BABYLON.Vector3.Zero();
  57782. this.onMeshUpdated = function (transformNode) {
  57783. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57784. };
  57785. this.onGeometryUpdated = function (geometry) {
  57786. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57787. };
  57788. this._afterRender = function () {
  57789. if (!_this._init)
  57790. return;
  57791. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57792. return;
  57793. }
  57794. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57795. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57796. if (_this._runningUpdated > 4) {
  57797. return;
  57798. }
  57799. ++_this._runningUpdated;
  57800. var payload = {
  57801. updatedMeshes: _this._addUpdateMeshesList,
  57802. updatedGeometries: _this._addUpdateGeometriesList,
  57803. removedGeometries: _this._toRemoveGeometryArray,
  57804. removedMeshes: _this._toRemoveMeshesArray
  57805. };
  57806. var message = {
  57807. payload: payload,
  57808. taskType: WorkerTaskType.UPDATE
  57809. };
  57810. var serializable = [];
  57811. for (var id in payload.updatedGeometries) {
  57812. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57813. //prepare transferables
  57814. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57815. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57816. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57817. }
  57818. }
  57819. _this._worker.postMessage(message, serializable);
  57820. _this._addUpdateMeshesList = {};
  57821. _this._addUpdateGeometriesList = {};
  57822. _this._toRemoveGeometryArray = [];
  57823. _this._toRemoveMeshesArray = [];
  57824. };
  57825. this._onMessageFromWorker = function (e) {
  57826. var returnData = e.data;
  57827. if (returnData.error != WorkerReplyType.SUCCESS) {
  57828. //TODO what errors can be returned from the worker?
  57829. BABYLON.Tools.Warn("error returned from worker!");
  57830. return;
  57831. }
  57832. switch (returnData.taskType) {
  57833. case WorkerTaskType.INIT:
  57834. _this._init = true;
  57835. //Update the worked with ALL of the scene's current state
  57836. _this._scene.meshes.forEach(function (mesh) {
  57837. _this.onMeshAdded(mesh);
  57838. });
  57839. _this._scene.getGeometries().forEach(function (geometry) {
  57840. _this.onGeometryAdded(geometry);
  57841. });
  57842. break;
  57843. case WorkerTaskType.UPDATE:
  57844. _this._runningUpdated--;
  57845. break;
  57846. case WorkerTaskType.COLLIDE:
  57847. var returnPayload = returnData.payload;
  57848. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57849. return;
  57850. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57851. if (callback) {
  57852. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57853. if (mesh) {
  57854. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57855. }
  57856. }
  57857. //cleanup
  57858. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57859. break;
  57860. }
  57861. };
  57862. this._collisionsCallbackArray = [];
  57863. this._init = false;
  57864. this._runningUpdated = 0;
  57865. this._addUpdateMeshesList = {};
  57866. this._addUpdateGeometriesList = {};
  57867. this._toRemoveGeometryArray = [];
  57868. this._toRemoveMeshesArray = [];
  57869. }
  57870. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57871. if (!this._init)
  57872. return;
  57873. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57874. return;
  57875. position.divideToRef(collider._radius, this._scaledPosition);
  57876. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57877. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57878. var payload = {
  57879. collider: {
  57880. position: this._scaledPosition.asArray(),
  57881. velocity: this._scaledVelocity.asArray(),
  57882. radius: collider._radius.asArray()
  57883. },
  57884. collisionId: collisionIndex,
  57885. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57886. maximumRetry: maximumRetry
  57887. };
  57888. var message = {
  57889. payload: payload,
  57890. taskType: WorkerTaskType.COLLIDE
  57891. };
  57892. this._worker.postMessage(message);
  57893. };
  57894. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57895. this._scene = scene;
  57896. this._scene.registerAfterRender(this._afterRender);
  57897. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57898. this._worker = new Worker(workerUrl);
  57899. this._worker.onmessage = this._onMessageFromWorker;
  57900. var message = {
  57901. payload: {},
  57902. taskType: WorkerTaskType.INIT
  57903. };
  57904. this._worker.postMessage(message);
  57905. };
  57906. CollisionCoordinatorWorker.prototype.destroy = function () {
  57907. this._scene.unregisterAfterRender(this._afterRender);
  57908. this._worker.terminate();
  57909. };
  57910. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57911. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57912. this.onMeshUpdated(mesh);
  57913. };
  57914. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57915. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57916. };
  57917. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57918. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57919. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57920. this.onGeometryUpdated(geometry);
  57921. };
  57922. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57923. this._toRemoveGeometryArray.push(geometry.id);
  57924. };
  57925. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57926. var submeshes = [];
  57927. if (mesh.subMeshes) {
  57928. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57929. var boundingInfo = sm.getBoundingInfo();
  57930. return {
  57931. position: idx,
  57932. verticesStart: sm.verticesStart,
  57933. verticesCount: sm.verticesCount,
  57934. indexStart: sm.indexStart,
  57935. indexCount: sm.indexCount,
  57936. hasMaterial: !!sm.getMaterial(),
  57937. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57938. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57939. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57940. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57941. };
  57942. });
  57943. }
  57944. var geometryId = null;
  57945. if (mesh instanceof BABYLON.Mesh) {
  57946. var geometry = mesh.geometry;
  57947. geometryId = geometry ? geometry.id : null;
  57948. }
  57949. else if (mesh instanceof BABYLON.InstancedMesh) {
  57950. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57951. geometryId = geometry ? geometry.id : null;
  57952. }
  57953. var boundingInfo = mesh.getBoundingInfo();
  57954. return {
  57955. uniqueId: mesh.uniqueId,
  57956. id: mesh.id,
  57957. name: mesh.name,
  57958. geometryId: geometryId,
  57959. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57960. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57961. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57962. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57963. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57964. subMeshes: submeshes,
  57965. checkCollisions: mesh.checkCollisions
  57966. };
  57967. };
  57968. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57969. return {
  57970. id: geometry.id,
  57971. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57972. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  57973. indices: new Uint32Array(geometry.getIndices() || []),
  57974. };
  57975. };
  57976. return CollisionCoordinatorWorker;
  57977. }());
  57978. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  57979. /** @hidden */
  57980. var CollisionCoordinatorLegacy = /** @class */ (function () {
  57981. function CollisionCoordinatorLegacy() {
  57982. this._scaledPosition = BABYLON.Vector3.Zero();
  57983. this._scaledVelocity = BABYLON.Vector3.Zero();
  57984. this._finalPosition = BABYLON.Vector3.Zero();
  57985. }
  57986. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57987. position.divideToRef(collider._radius, this._scaledPosition);
  57988. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57989. collider.collidedMesh = null;
  57990. collider._retry = 0;
  57991. collider._initialVelocity = this._scaledVelocity;
  57992. collider._initialPosition = this._scaledPosition;
  57993. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  57994. this._finalPosition.multiplyInPlace(collider._radius);
  57995. //run the callback
  57996. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  57997. };
  57998. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  57999. this._scene = scene;
  58000. };
  58001. CollisionCoordinatorLegacy.prototype.destroy = function () {
  58002. //Legacy need no destruction method.
  58003. };
  58004. //No update in legacy mode
  58005. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  58006. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  58007. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  58008. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  58009. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  58010. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  58011. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  58012. if (excludedMesh === void 0) { excludedMesh = null; }
  58013. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  58014. if (collider._retry >= maximumRetry) {
  58015. finalPosition.copyFrom(position);
  58016. return;
  58017. }
  58018. // Check if this is a mesh else camera or -1
  58019. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  58020. collider._initialize(position, velocity, closeDistance);
  58021. // Check all meshes
  58022. for (var index = 0; index < this._scene.meshes.length; index++) {
  58023. var mesh = this._scene.meshes[index];
  58024. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58025. mesh._checkCollision(collider);
  58026. }
  58027. }
  58028. if (!collider.collisionFound) {
  58029. position.addToRef(velocity, finalPosition);
  58030. return;
  58031. }
  58032. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58033. collider._getResponse(position, velocity);
  58034. }
  58035. if (velocity.length() <= closeDistance) {
  58036. finalPosition.copyFrom(position);
  58037. return;
  58038. }
  58039. collider._retry++;
  58040. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58041. };
  58042. return CollisionCoordinatorLegacy;
  58043. }());
  58044. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58045. })(BABYLON || (BABYLON = {}));
  58046. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58047. var BABYLON;
  58048. (function (BABYLON) {
  58049. /**
  58050. * A particle represents one of the element emitted by a particle system.
  58051. * This is mainly define by its coordinates, direction, velocity and age.
  58052. */
  58053. var Particle = /** @class */ (function () {
  58054. /**
  58055. * Creates a new instance Particle
  58056. * @param particleSystem the particle system the particle belongs to
  58057. */
  58058. function Particle(
  58059. /**
  58060. * The particle system the particle belongs to.
  58061. */
  58062. particleSystem) {
  58063. this.particleSystem = particleSystem;
  58064. /**
  58065. * The world position of the particle in the scene.
  58066. */
  58067. this.position = BABYLON.Vector3.Zero();
  58068. /**
  58069. * The world direction of the particle in the scene.
  58070. */
  58071. this.direction = BABYLON.Vector3.Zero();
  58072. /**
  58073. * The color of the particle.
  58074. */
  58075. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58076. /**
  58077. * The color change of the particle per step.
  58078. */
  58079. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58080. /**
  58081. * Defines how long will the life of the particle be.
  58082. */
  58083. this.lifeTime = 1.0;
  58084. /**
  58085. * The current age of the particle.
  58086. */
  58087. this.age = 0;
  58088. /**
  58089. * The current size of the particle.
  58090. */
  58091. this.size = 0;
  58092. /**
  58093. * The current scale of the particle.
  58094. */
  58095. this.scale = new BABYLON.Vector2(1, 1);
  58096. /**
  58097. * The current angle of the particle.
  58098. */
  58099. this.angle = 0;
  58100. /**
  58101. * Defines how fast is the angle changing.
  58102. */
  58103. this.angularSpeed = 0;
  58104. /**
  58105. * Defines the cell index used by the particle to be rendered from a sprite.
  58106. */
  58107. this.cellIndex = 0;
  58108. /** @hidden */
  58109. this._attachedSubEmitters = null;
  58110. /** @hidden */
  58111. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58112. /** @hidden */
  58113. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58114. /** @hidden */
  58115. this._currentSize1 = 0;
  58116. /** @hidden */
  58117. this._currentSize2 = 0;
  58118. /** @hidden */
  58119. this._currentAngularSpeed1 = 0;
  58120. /** @hidden */
  58121. this._currentAngularSpeed2 = 0;
  58122. /** @hidden */
  58123. this._currentVelocity1 = 0;
  58124. /** @hidden */
  58125. this._currentVelocity2 = 0;
  58126. /** @hidden */
  58127. this._currentLimitVelocity1 = 0;
  58128. /** @hidden */
  58129. this._currentLimitVelocity2 = 0;
  58130. /** @hidden */
  58131. this._currentDrag1 = 0;
  58132. /** @hidden */
  58133. this._currentDrag2 = 0;
  58134. this.id = Particle._Count++;
  58135. if (!this.particleSystem.isAnimationSheetEnabled) {
  58136. return;
  58137. }
  58138. this.updateCellInfoFromSystem();
  58139. }
  58140. Particle.prototype.updateCellInfoFromSystem = function () {
  58141. this.cellIndex = this.particleSystem.startSpriteCellID;
  58142. };
  58143. /**
  58144. * Defines how the sprite cell index is updated for the particle
  58145. */
  58146. Particle.prototype.updateCellIndex = function () {
  58147. var offsetAge = this.age;
  58148. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58149. if (this.particleSystem.spriteRandomStartCell) {
  58150. if (this._randomCellOffset === undefined) {
  58151. this._randomCellOffset = Math.random() * this.lifeTime;
  58152. }
  58153. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58154. changeSpeed = 1;
  58155. offsetAge = this._randomCellOffset;
  58156. }
  58157. else {
  58158. offsetAge += this._randomCellOffset;
  58159. }
  58160. }
  58161. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58162. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58163. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58164. };
  58165. /** @hidden */
  58166. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58167. if (subEmitter.particleSystem.emitter.position) {
  58168. var emitterMesh = subEmitter.particleSystem.emitter;
  58169. emitterMesh.position.copyFrom(this.position);
  58170. if (subEmitter.inheritDirection) {
  58171. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58172. // Look at using Y as forward
  58173. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58174. }
  58175. }
  58176. else {
  58177. var emitterPosition = subEmitter.particleSystem.emitter;
  58178. emitterPosition.copyFrom(this.position);
  58179. }
  58180. // Set inheritedVelocityOffset to be used when new particles are created
  58181. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58182. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58183. };
  58184. /** @hidden */
  58185. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58186. var _this = this;
  58187. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58188. this._attachedSubEmitters.forEach(function (subEmitter) {
  58189. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58190. });
  58191. }
  58192. };
  58193. /** @hidden */
  58194. Particle.prototype._reset = function () {
  58195. this.age = 0;
  58196. this._currentColorGradient = null;
  58197. this._currentSizeGradient = null;
  58198. this._currentAngularSpeedGradient = null;
  58199. this._currentVelocityGradient = null;
  58200. this._currentLimitVelocityGradient = null;
  58201. this._currentDragGradient = null;
  58202. this.cellIndex = this.particleSystem.startSpriteCellID;
  58203. this._randomCellOffset = undefined;
  58204. };
  58205. /**
  58206. * Copy the properties of particle to another one.
  58207. * @param other the particle to copy the information to.
  58208. */
  58209. Particle.prototype.copyTo = function (other) {
  58210. other.position.copyFrom(this.position);
  58211. if (this._initialDirection) {
  58212. if (other._initialDirection) {
  58213. other._initialDirection.copyFrom(this._initialDirection);
  58214. }
  58215. else {
  58216. other._initialDirection = this._initialDirection.clone();
  58217. }
  58218. }
  58219. else {
  58220. other._initialDirection = null;
  58221. }
  58222. other.direction.copyFrom(this.direction);
  58223. other.color.copyFrom(this.color);
  58224. other.colorStep.copyFrom(this.colorStep);
  58225. other.lifeTime = this.lifeTime;
  58226. other.age = this.age;
  58227. other._randomCellOffset = this._randomCellOffset;
  58228. other.size = this.size;
  58229. other.scale.copyFrom(this.scale);
  58230. other.angle = this.angle;
  58231. other.angularSpeed = this.angularSpeed;
  58232. other.particleSystem = this.particleSystem;
  58233. other.cellIndex = this.cellIndex;
  58234. other.id = this.id;
  58235. other._attachedSubEmitters = this._attachedSubEmitters;
  58236. if (this._currentColorGradient) {
  58237. other._currentColorGradient = this._currentColorGradient;
  58238. other._currentColor1.copyFrom(this._currentColor1);
  58239. other._currentColor2.copyFrom(this._currentColor2);
  58240. }
  58241. if (this._currentSizeGradient) {
  58242. other._currentSizeGradient = this._currentSizeGradient;
  58243. other._currentSize1 = this._currentSize1;
  58244. other._currentSize2 = this._currentSize2;
  58245. }
  58246. if (this._currentAngularSpeedGradient) {
  58247. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58248. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58249. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58250. }
  58251. if (this._currentVelocityGradient) {
  58252. other._currentVelocityGradient = this._currentVelocityGradient;
  58253. other._currentVelocity1 = this._currentVelocity1;
  58254. other._currentVelocity2 = this._currentVelocity2;
  58255. }
  58256. if (this._currentLimitVelocityGradient) {
  58257. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58258. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58259. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58260. }
  58261. if (this._currentDragGradient) {
  58262. other._currentDragGradient = this._currentDragGradient;
  58263. other._currentDrag1 = this._currentDrag1;
  58264. other._currentDrag2 = this._currentDrag2;
  58265. }
  58266. if (this.particleSystem.isAnimationSheetEnabled) {
  58267. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58268. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58269. }
  58270. if (this.particleSystem.useRampGradients) {
  58271. other.remapData.copyFrom(this.remapData);
  58272. }
  58273. if (this._randomNoiseCoordinates1) {
  58274. if (other._randomNoiseCoordinates1) {
  58275. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58276. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58277. }
  58278. else {
  58279. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58280. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58281. }
  58282. }
  58283. };
  58284. Particle._Count = 0;
  58285. return Particle;
  58286. }());
  58287. BABYLON.Particle = Particle;
  58288. })(BABYLON || (BABYLON = {}));
  58289. //# sourceMappingURL=babylon.particle.js.map
  58290. var BABYLON;
  58291. (function (BABYLON) {
  58292. /**
  58293. * This represents the base class for particle system in Babylon.
  58294. * 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.
  58295. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58296. * @example https://doc.babylonjs.com/babylon101/particles
  58297. */
  58298. var BaseParticleSystem = /** @class */ (function () {
  58299. /**
  58300. * Instantiates a particle system.
  58301. * 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.
  58302. * @param name The name of the particle system
  58303. */
  58304. function BaseParticleSystem(name) {
  58305. /**
  58306. * List of animations used by the particle system.
  58307. */
  58308. this.animations = [];
  58309. /**
  58310. * The rendering group used by the Particle system to chose when to render.
  58311. */
  58312. this.renderingGroupId = 0;
  58313. /**
  58314. * The emitter represents the Mesh or position we are attaching the particle system to.
  58315. */
  58316. this.emitter = null;
  58317. /**
  58318. * The maximum number of particles to emit per frame
  58319. */
  58320. this.emitRate = 10;
  58321. /**
  58322. * If you want to launch only a few particles at once, that can be done, as well.
  58323. */
  58324. this.manualEmitCount = -1;
  58325. /**
  58326. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58327. */
  58328. this.updateSpeed = 0.01;
  58329. /**
  58330. * The amount of time the particle system is running (depends of the overall update speed).
  58331. */
  58332. this.targetStopDuration = 0;
  58333. /**
  58334. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58335. */
  58336. this.disposeOnStop = false;
  58337. /**
  58338. * Minimum power of emitting particles.
  58339. */
  58340. this.minEmitPower = 1;
  58341. /**
  58342. * Maximum power of emitting particles.
  58343. */
  58344. this.maxEmitPower = 1;
  58345. /**
  58346. * Minimum life time of emitting particles.
  58347. */
  58348. this.minLifeTime = 1;
  58349. /**
  58350. * Maximum life time of emitting particles.
  58351. */
  58352. this.maxLifeTime = 1;
  58353. /**
  58354. * Minimum Size of emitting particles.
  58355. */
  58356. this.minSize = 1;
  58357. /**
  58358. * Maximum Size of emitting particles.
  58359. */
  58360. this.maxSize = 1;
  58361. /**
  58362. * Minimum scale of emitting particles on X axis.
  58363. */
  58364. this.minScaleX = 1;
  58365. /**
  58366. * Maximum scale of emitting particles on X axis.
  58367. */
  58368. this.maxScaleX = 1;
  58369. /**
  58370. * Minimum scale of emitting particles on Y axis.
  58371. */
  58372. this.minScaleY = 1;
  58373. /**
  58374. * Maximum scale of emitting particles on Y axis.
  58375. */
  58376. this.maxScaleY = 1;
  58377. /**
  58378. * Gets or sets the minimal initial rotation in radians.
  58379. */
  58380. this.minInitialRotation = 0;
  58381. /**
  58382. * Gets or sets the maximal initial rotation in radians.
  58383. */
  58384. this.maxInitialRotation = 0;
  58385. /**
  58386. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58387. */
  58388. this.minAngularSpeed = 0;
  58389. /**
  58390. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58391. */
  58392. this.maxAngularSpeed = 0;
  58393. /**
  58394. * The layer mask we are rendering the particles through.
  58395. */
  58396. this.layerMask = 0x0FFFFFFF;
  58397. /**
  58398. * This can help using your own shader to render the particle system.
  58399. * The according effect will be created
  58400. */
  58401. this.customShader = null;
  58402. /**
  58403. * By default particle system starts as soon as they are created. This prevents the
  58404. * automatic start to happen and let you decide when to start emitting particles.
  58405. */
  58406. this.preventAutoStart = false;
  58407. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58408. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58409. /**
  58410. * Callback triggered when the particle animation is ending.
  58411. */
  58412. this.onAnimationEnd = null;
  58413. /**
  58414. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58415. */
  58416. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58417. /**
  58418. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58419. * to override the particles.
  58420. */
  58421. this.forceDepthWrite = false;
  58422. /** 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 */
  58423. this.preWarmCycles = 0;
  58424. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58425. this.preWarmStepOffset = 1;
  58426. /**
  58427. * 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)
  58428. */
  58429. this.spriteCellChangeSpeed = 1;
  58430. /**
  58431. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58432. */
  58433. this.startSpriteCellID = 0;
  58434. /**
  58435. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58436. */
  58437. this.endSpriteCellID = 0;
  58438. /**
  58439. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58440. */
  58441. this.spriteCellWidth = 0;
  58442. /**
  58443. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58444. */
  58445. this.spriteCellHeight = 0;
  58446. /**
  58447. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58448. */
  58449. this.spriteRandomStartCell = false;
  58450. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58451. this.translationPivot = new BABYLON.Vector2(0, 0);
  58452. /**
  58453. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58454. */
  58455. this.beginAnimationOnStart = false;
  58456. /**
  58457. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58458. */
  58459. this.beginAnimationFrom = 0;
  58460. /**
  58461. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58462. */
  58463. this.beginAnimationTo = 60;
  58464. /**
  58465. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58466. */
  58467. this.beginAnimationLoop = false;
  58468. /**
  58469. * You can use gravity if you want to give an orientation to your particles.
  58470. */
  58471. this.gravity = BABYLON.Vector3.Zero();
  58472. this._colorGradients = null;
  58473. this._sizeGradients = null;
  58474. this._lifeTimeGradients = null;
  58475. this._angularSpeedGradients = null;
  58476. this._velocityGradients = null;
  58477. this._limitVelocityGradients = null;
  58478. this._dragGradients = null;
  58479. this._emitRateGradients = null;
  58480. this._startSizeGradients = null;
  58481. this._rampGradients = null;
  58482. this._colorRemapGradients = null;
  58483. this._alphaRemapGradients = null;
  58484. /**
  58485. * Defines the delay in milliseconds before starting the system (0 by default)
  58486. */
  58487. this.startDelay = 0;
  58488. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58489. this.limitVelocityDamping = 0.4;
  58490. /**
  58491. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58492. */
  58493. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58494. /**
  58495. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58496. */
  58497. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58498. /**
  58499. * Color the particle will have at the end of its lifetime
  58500. */
  58501. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58502. /**
  58503. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58504. */
  58505. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58506. /** @hidden */
  58507. this._isSubEmitter = false;
  58508. /**
  58509. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58510. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58511. */
  58512. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58513. this._isBillboardBased = true;
  58514. /**
  58515. * Local cache of defines for image processing.
  58516. */
  58517. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58518. this.id = name;
  58519. this.name = name;
  58520. }
  58521. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58522. /**
  58523. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58524. */
  58525. get: function () {
  58526. return this._isAnimationSheetEnabled;
  58527. },
  58528. set: function (value) {
  58529. if (this._isAnimationSheetEnabled == value) {
  58530. return;
  58531. }
  58532. this._isAnimationSheetEnabled = value;
  58533. this._reset();
  58534. },
  58535. enumerable: true,
  58536. configurable: true
  58537. });
  58538. /**
  58539. * Get hosting scene
  58540. * @returns the scene
  58541. */
  58542. BaseParticleSystem.prototype.getScene = function () {
  58543. return this._scene;
  58544. };
  58545. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58546. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58547. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58548. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58549. };
  58550. /**
  58551. * Gets the current list of drag gradients.
  58552. * You must use addDragGradient and removeDragGradient to udpate this list
  58553. * @returns the list of drag gradients
  58554. */
  58555. BaseParticleSystem.prototype.getDragGradients = function () {
  58556. return this._dragGradients;
  58557. };
  58558. /**
  58559. * Gets the current list of limit velocity gradients.
  58560. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58561. * @returns the list of limit velocity gradients
  58562. */
  58563. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58564. return this._limitVelocityGradients;
  58565. };
  58566. /**
  58567. * Gets the current list of color gradients.
  58568. * You must use addColorGradient and removeColorGradient to udpate this list
  58569. * @returns the list of color gradients
  58570. */
  58571. BaseParticleSystem.prototype.getColorGradients = function () {
  58572. return this._colorGradients;
  58573. };
  58574. /**
  58575. * Gets the current list of size gradients.
  58576. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58577. * @returns the list of size gradients
  58578. */
  58579. BaseParticleSystem.prototype.getSizeGradients = function () {
  58580. return this._sizeGradients;
  58581. };
  58582. /**
  58583. * Gets the current list of color remap gradients.
  58584. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58585. * @returns the list of color remap gradients
  58586. */
  58587. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58588. return this._colorRemapGradients;
  58589. };
  58590. /**
  58591. * Gets the current list of alpha remap gradients.
  58592. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58593. * @returns the list of alpha remap gradients
  58594. */
  58595. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58596. return this._alphaRemapGradients;
  58597. };
  58598. /**
  58599. * Gets the current list of life time gradients.
  58600. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58601. * @returns the list of life time gradients
  58602. */
  58603. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58604. return this._lifeTimeGradients;
  58605. };
  58606. /**
  58607. * Gets the current list of angular speed gradients.
  58608. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58609. * @returns the list of angular speed gradients
  58610. */
  58611. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58612. return this._angularSpeedGradients;
  58613. };
  58614. /**
  58615. * Gets the current list of velocity gradients.
  58616. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58617. * @returns the list of velocity gradients
  58618. */
  58619. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58620. return this._velocityGradients;
  58621. };
  58622. /**
  58623. * Gets the current list of start size gradients.
  58624. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58625. * @returns the list of start size gradients
  58626. */
  58627. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58628. return this._startSizeGradients;
  58629. };
  58630. /**
  58631. * Gets the current list of emit rate gradients.
  58632. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58633. * @returns the list of emit rate gradients
  58634. */
  58635. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58636. return this._emitRateGradients;
  58637. };
  58638. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58639. /**
  58640. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58641. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58642. */
  58643. get: function () {
  58644. if (this.particleEmitterType.direction1) {
  58645. return this.particleEmitterType.direction1;
  58646. }
  58647. return BABYLON.Vector3.Zero();
  58648. },
  58649. set: function (value) {
  58650. if (this.particleEmitterType.direction1) {
  58651. this.particleEmitterType.direction1 = value;
  58652. }
  58653. },
  58654. enumerable: true,
  58655. configurable: true
  58656. });
  58657. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58658. /**
  58659. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58660. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58661. */
  58662. get: function () {
  58663. if (this.particleEmitterType.direction2) {
  58664. return this.particleEmitterType.direction2;
  58665. }
  58666. return BABYLON.Vector3.Zero();
  58667. },
  58668. set: function (value) {
  58669. if (this.particleEmitterType.direction2) {
  58670. this.particleEmitterType.direction2 = value;
  58671. }
  58672. },
  58673. enumerable: true,
  58674. configurable: true
  58675. });
  58676. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58677. /**
  58678. * 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.
  58679. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58680. */
  58681. get: function () {
  58682. if (this.particleEmitterType.minEmitBox) {
  58683. return this.particleEmitterType.minEmitBox;
  58684. }
  58685. return BABYLON.Vector3.Zero();
  58686. },
  58687. set: function (value) {
  58688. if (this.particleEmitterType.minEmitBox) {
  58689. this.particleEmitterType.minEmitBox = value;
  58690. }
  58691. },
  58692. enumerable: true,
  58693. configurable: true
  58694. });
  58695. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58696. /**
  58697. * 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.
  58698. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58699. */
  58700. get: function () {
  58701. if (this.particleEmitterType.maxEmitBox) {
  58702. return this.particleEmitterType.maxEmitBox;
  58703. }
  58704. return BABYLON.Vector3.Zero();
  58705. },
  58706. set: function (value) {
  58707. if (this.particleEmitterType.maxEmitBox) {
  58708. this.particleEmitterType.maxEmitBox = value;
  58709. }
  58710. },
  58711. enumerable: true,
  58712. configurable: true
  58713. });
  58714. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58715. /**
  58716. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58717. */
  58718. get: function () {
  58719. return this._isBillboardBased;
  58720. },
  58721. set: function (value) {
  58722. if (this._isBillboardBased === value) {
  58723. return;
  58724. }
  58725. this._isBillboardBased = value;
  58726. this._reset();
  58727. },
  58728. enumerable: true,
  58729. configurable: true
  58730. });
  58731. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58732. /**
  58733. * Gets the image processing configuration used either in this material.
  58734. */
  58735. get: function () {
  58736. return this._imageProcessingConfiguration;
  58737. },
  58738. /**
  58739. * Sets the Default image processing configuration used either in the this material.
  58740. *
  58741. * If sets to null, the scene one is in use.
  58742. */
  58743. set: function (value) {
  58744. this._attachImageProcessingConfiguration(value);
  58745. },
  58746. enumerable: true,
  58747. configurable: true
  58748. });
  58749. /**
  58750. * Attaches a new image processing configuration to the Standard Material.
  58751. * @param configuration
  58752. */
  58753. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58754. if (configuration === this._imageProcessingConfiguration) {
  58755. return;
  58756. }
  58757. // Pick the scene configuration if needed.
  58758. if (!configuration) {
  58759. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58760. }
  58761. else {
  58762. this._imageProcessingConfiguration = configuration;
  58763. }
  58764. };
  58765. /** @hidden */
  58766. BaseParticleSystem.prototype._reset = function () {
  58767. };
  58768. /** @hidden */
  58769. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58770. if (!gradients) {
  58771. return this;
  58772. }
  58773. var index = 0;
  58774. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58775. var valueGradient = gradients_1[_i];
  58776. if (valueGradient.gradient === gradient) {
  58777. gradients.splice(index, 1);
  58778. break;
  58779. }
  58780. index++;
  58781. }
  58782. if (texture) {
  58783. texture.dispose();
  58784. }
  58785. return this;
  58786. };
  58787. /**
  58788. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58789. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58790. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58791. * @returns the emitter
  58792. */
  58793. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58794. var particleEmitter = new BABYLON.PointParticleEmitter();
  58795. particleEmitter.direction1 = direction1;
  58796. particleEmitter.direction2 = direction2;
  58797. this.particleEmitterType = particleEmitter;
  58798. return particleEmitter;
  58799. };
  58800. /**
  58801. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58802. * @param radius The radius of the hemisphere to emit from
  58803. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58804. * @returns the emitter
  58805. */
  58806. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58807. if (radius === void 0) { radius = 1; }
  58808. if (radiusRange === void 0) { radiusRange = 1; }
  58809. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58810. this.particleEmitterType = particleEmitter;
  58811. return particleEmitter;
  58812. };
  58813. /**
  58814. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58815. * @param radius The radius of the sphere to emit from
  58816. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58817. * @returns the emitter
  58818. */
  58819. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58820. if (radius === void 0) { radius = 1; }
  58821. if (radiusRange === void 0) { radiusRange = 1; }
  58822. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58823. this.particleEmitterType = particleEmitter;
  58824. return particleEmitter;
  58825. };
  58826. /**
  58827. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58828. * @param radius The radius of the sphere to emit from
  58829. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58830. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58831. * @returns the emitter
  58832. */
  58833. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58834. if (radius === void 0) { radius = 1; }
  58835. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58836. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58837. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58838. this.particleEmitterType = particleEmitter;
  58839. return particleEmitter;
  58840. };
  58841. /**
  58842. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58843. * @param radius The radius of the emission cylinder
  58844. * @param height The height of the emission cylinder
  58845. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58846. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58847. * @returns the emitter
  58848. */
  58849. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58850. if (radius === void 0) { radius = 1; }
  58851. if (height === void 0) { height = 1; }
  58852. if (radiusRange === void 0) { radiusRange = 1; }
  58853. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58854. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58855. this.particleEmitterType = particleEmitter;
  58856. return particleEmitter;
  58857. };
  58858. /**
  58859. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58860. * @param radius The radius of the cylinder to emit from
  58861. * @param height The height of the emission cylinder
  58862. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58863. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58864. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58865. * @returns the emitter
  58866. */
  58867. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58868. if (radius === void 0) { radius = 1; }
  58869. if (height === void 0) { height = 1; }
  58870. if (radiusRange === void 0) { radiusRange = 1; }
  58871. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58872. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58873. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58874. this.particleEmitterType = particleEmitter;
  58875. return particleEmitter;
  58876. };
  58877. /**
  58878. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58879. * @param radius The radius of the cone to emit from
  58880. * @param angle The base angle of the cone
  58881. * @returns the emitter
  58882. */
  58883. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58884. if (radius === void 0) { radius = 1; }
  58885. if (angle === void 0) { angle = Math.PI / 4; }
  58886. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58887. this.particleEmitterType = particleEmitter;
  58888. return particleEmitter;
  58889. };
  58890. /**
  58891. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58892. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58893. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58894. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58895. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58896. * @returns the emitter
  58897. */
  58898. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58899. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58900. this.particleEmitterType = particleEmitter;
  58901. this.direction1 = direction1;
  58902. this.direction2 = direction2;
  58903. this.minEmitBox = minEmitBox;
  58904. this.maxEmitBox = maxEmitBox;
  58905. return particleEmitter;
  58906. };
  58907. /**
  58908. * Source color is added to the destination color without alpha affecting the result
  58909. */
  58910. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58911. /**
  58912. * Blend current color and particle color using particle’s alpha
  58913. */
  58914. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58915. /**
  58916. * Add current color and particle color multiplied by particle’s alpha
  58917. */
  58918. BaseParticleSystem.BLENDMODE_ADD = 2;
  58919. /**
  58920. * Multiply current color with particle color
  58921. */
  58922. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58923. /**
  58924. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58925. */
  58926. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58927. return BaseParticleSystem;
  58928. }());
  58929. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58930. })(BABYLON || (BABYLON = {}));
  58931. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58932. var BABYLON;
  58933. (function (BABYLON) {
  58934. /**
  58935. * This represents a particle system in Babylon.
  58936. * 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.
  58937. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58938. * @example https://doc.babylonjs.com/babylon101/particles
  58939. */
  58940. var ParticleSystem = /** @class */ (function (_super) {
  58941. __extends(ParticleSystem, _super);
  58942. /**
  58943. * Instantiates a particle system.
  58944. * 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.
  58945. * @param name The name of the particle system
  58946. * @param capacity The max number of particles alive at the same time
  58947. * @param scene The scene the particle system belongs to
  58948. * @param customEffect a custom effect used to change the way particles are rendered by default
  58949. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58950. * @param epsilon Offset used to render the particles
  58951. */
  58952. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58953. if (customEffect === void 0) { customEffect = null; }
  58954. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58955. if (epsilon === void 0) { epsilon = 0.01; }
  58956. var _this = _super.call(this, name) || this;
  58957. /**
  58958. * @hidden
  58959. */
  58960. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58961. /**
  58962. * An event triggered when the system is disposed
  58963. */
  58964. _this.onDisposeObservable = new BABYLON.Observable();
  58965. _this._particles = new Array();
  58966. _this._stockParticles = new Array();
  58967. _this._newPartsExcess = 0;
  58968. _this._vertexBuffers = {};
  58969. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58970. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58971. _this._scaledDirection = BABYLON.Vector3.Zero();
  58972. _this._scaledGravity = BABYLON.Vector3.Zero();
  58973. _this._currentRenderId = -1;
  58974. _this._useInstancing = false;
  58975. _this._started = false;
  58976. _this._stopped = false;
  58977. _this._actualFrame = 0;
  58978. /** @hidden */
  58979. _this._currentEmitRate1 = 0;
  58980. /** @hidden */
  58981. _this._currentEmitRate2 = 0;
  58982. /** @hidden */
  58983. _this._currentStartSize1 = 0;
  58984. /** @hidden */
  58985. _this._currentStartSize2 = 0;
  58986. _this._rawTextureWidth = 256;
  58987. _this._useRampGradients = false;
  58988. /**
  58989. * @hidden
  58990. * If the particle systems emitter should be disposed when the particle system is disposed
  58991. */
  58992. _this._disposeEmitterOnDispose = false;
  58993. // start of sub system methods
  58994. /**
  58995. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  58996. * Its lifetime will start back at 0.
  58997. */
  58998. _this.recycleParticle = function (particle) {
  58999. // move particle from activeParticle list to stock particles
  59000. var lastParticle = _this._particles.pop();
  59001. if (lastParticle !== particle) {
  59002. lastParticle.copyTo(particle);
  59003. }
  59004. _this._stockParticles.push(lastParticle);
  59005. };
  59006. _this._createParticle = function () {
  59007. var particle;
  59008. if (_this._stockParticles.length !== 0) {
  59009. particle = _this._stockParticles.pop();
  59010. particle._reset();
  59011. }
  59012. else {
  59013. particle = new BABYLON.Particle(_this);
  59014. }
  59015. // Attach emitters
  59016. if (_this._subEmitters && _this._subEmitters.length > 0) {
  59017. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  59018. particle._attachedSubEmitters = [];
  59019. subEmitters.forEach(function (subEmitter) {
  59020. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  59021. var newEmitter = subEmitter.clone();
  59022. particle._attachedSubEmitters.push(newEmitter);
  59023. newEmitter.particleSystem.start();
  59024. }
  59025. });
  59026. }
  59027. return particle;
  59028. };
  59029. _this._emitFromParticle = function (particle) {
  59030. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59031. return;
  59032. }
  59033. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59034. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59035. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59036. var subSystem = subEmitter.clone();
  59037. particle._inheritParticleInfoToSubEmitter(subSystem);
  59038. subSystem.particleSystem._rootParticleSystem = _this;
  59039. _this.activeSubSystems.push(subSystem.particleSystem);
  59040. subSystem.particleSystem.start();
  59041. }
  59042. });
  59043. };
  59044. _this._capacity = capacity;
  59045. _this._epsilon = epsilon;
  59046. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59047. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59048. // Setup the default processing configuration to the scene.
  59049. _this._attachImageProcessingConfiguration(null);
  59050. _this._customEffect = customEffect;
  59051. _this._scene.particleSystems.push(_this);
  59052. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59053. _this._createIndexBuffer();
  59054. _this._createVertexBuffers();
  59055. // Default emitter type
  59056. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59057. // Update
  59058. _this.updateFunction = function (particles) {
  59059. var noiseTextureSize = null;
  59060. var noiseTextureData = null;
  59061. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59062. noiseTextureSize = _this.noiseTexture.getSize();
  59063. noiseTextureData = (_this.noiseTexture.getContent());
  59064. }
  59065. var _loop_1 = function () {
  59066. particle = particles[index];
  59067. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59068. var previousAge = particle.age;
  59069. particle.age += scaledUpdateSpeed;
  59070. // Evaluate step to death
  59071. if (particle.age > particle.lifeTime) {
  59072. var diff = particle.age - previousAge;
  59073. var oldDiff = particle.lifeTime - previousAge;
  59074. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59075. particle.age = particle.lifeTime;
  59076. }
  59077. var ratio = particle.age / particle.lifeTime;
  59078. // Color
  59079. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59080. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59081. if (currentGradient !== particle._currentColorGradient) {
  59082. particle._currentColor1.copyFrom(particle._currentColor2);
  59083. nextGradient.getColorToRef(particle._currentColor2);
  59084. particle._currentColorGradient = currentGradient;
  59085. }
  59086. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59087. });
  59088. }
  59089. else {
  59090. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59091. particle.color.addInPlace(_this._scaledColorStep);
  59092. if (particle.color.a < 0) {
  59093. particle.color.a = 0;
  59094. }
  59095. }
  59096. // Angular speed
  59097. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59098. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59099. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59100. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59101. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59102. particle._currentAngularSpeedGradient = currentGradient;
  59103. }
  59104. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59105. });
  59106. }
  59107. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59108. // Direction
  59109. var directionScale = scaledUpdateSpeed;
  59110. /// Velocity
  59111. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59112. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59113. if (currentGradient !== particle._currentVelocityGradient) {
  59114. particle._currentVelocity1 = particle._currentVelocity2;
  59115. particle._currentVelocity2 = nextGradient.getFactor();
  59116. particle._currentVelocityGradient = currentGradient;
  59117. }
  59118. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59119. });
  59120. }
  59121. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59122. /// Limit velocity
  59123. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59124. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59125. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59126. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59127. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59128. particle._currentLimitVelocityGradient = currentGradient;
  59129. }
  59130. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59131. var currentVelocity = particle.direction.length();
  59132. if (currentVelocity > limitVelocity) {
  59133. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59134. }
  59135. });
  59136. }
  59137. /// Drag
  59138. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59139. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59140. if (currentGradient !== particle._currentDragGradient) {
  59141. particle._currentDrag1 = particle._currentDrag2;
  59142. particle._currentDrag2 = nextGradient.getFactor();
  59143. particle._currentDragGradient = currentGradient;
  59144. }
  59145. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59146. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59147. });
  59148. }
  59149. particle.position.addInPlace(_this._scaledDirection);
  59150. // Noise
  59151. if (noiseTextureData && noiseTextureSize) {
  59152. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59153. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59154. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59155. var force = BABYLON.Tmp.Vector3[0];
  59156. var scaledForce = BABYLON.Tmp.Vector3[1];
  59157. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59158. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59159. particle.direction.addInPlace(scaledForce);
  59160. }
  59161. // Gravity
  59162. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59163. particle.direction.addInPlace(_this._scaledGravity);
  59164. // Size
  59165. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59166. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59167. if (currentGradient !== particle._currentSizeGradient) {
  59168. particle._currentSize1 = particle._currentSize2;
  59169. particle._currentSize2 = nextGradient.getFactor();
  59170. particle._currentSizeGradient = currentGradient;
  59171. }
  59172. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59173. });
  59174. }
  59175. // Remap data
  59176. if (_this._useRampGradients) {
  59177. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59178. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59179. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59180. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59181. particle.remapData.x = min;
  59182. particle.remapData.y = max - min;
  59183. });
  59184. }
  59185. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59186. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59187. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59188. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59189. particle.remapData.z = min;
  59190. particle.remapData.w = max - min;
  59191. });
  59192. }
  59193. }
  59194. if (_this._isAnimationSheetEnabled) {
  59195. particle.updateCellIndex();
  59196. }
  59197. // Update the position of the attached sub-emitters to match their attached particle
  59198. particle._inheritParticleInfoToSubEmitters();
  59199. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59200. _this._emitFromParticle(particle);
  59201. if (particle._attachedSubEmitters) {
  59202. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59203. subEmitter.particleSystem.disposeOnStop = true;
  59204. subEmitter.particleSystem.stop();
  59205. });
  59206. particle._attachedSubEmitters = null;
  59207. }
  59208. _this.recycleParticle(particle);
  59209. index--;
  59210. return "continue";
  59211. }
  59212. };
  59213. var particle;
  59214. for (var index = 0; index < particles.length; index++) {
  59215. _loop_1();
  59216. }
  59217. };
  59218. return _this;
  59219. }
  59220. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59221. /**
  59222. * Sets a callback that will be triggered when the system is disposed
  59223. */
  59224. set: function (callback) {
  59225. if (this._onDisposeObserver) {
  59226. this.onDisposeObservable.remove(this._onDisposeObserver);
  59227. }
  59228. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59229. },
  59230. enumerable: true,
  59231. configurable: true
  59232. });
  59233. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59234. /** Gets or sets a boolean indicating that ramp gradients must be used
  59235. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59236. */
  59237. get: function () {
  59238. return this._useRampGradients;
  59239. },
  59240. set: function (value) {
  59241. if (this._useRampGradients === value) {
  59242. return;
  59243. }
  59244. this._useRampGradients = value;
  59245. this._resetEffect();
  59246. },
  59247. enumerable: true,
  59248. configurable: true
  59249. });
  59250. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59251. //end of Sub-emitter
  59252. /**
  59253. * Gets the current list of active particles
  59254. */
  59255. get: function () {
  59256. return this._particles;
  59257. },
  59258. enumerable: true,
  59259. configurable: true
  59260. });
  59261. /**
  59262. * Returns the string "ParticleSystem"
  59263. * @returns a string containing the class name
  59264. */
  59265. ParticleSystem.prototype.getClassName = function () {
  59266. return "ParticleSystem";
  59267. };
  59268. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59269. var newGradient = new BABYLON.FactorGradient();
  59270. newGradient.gradient = gradient;
  59271. newGradient.factor1 = factor;
  59272. newGradient.factor2 = factor2;
  59273. factorGradients.push(newGradient);
  59274. factorGradients.sort(function (a, b) {
  59275. if (a.gradient < b.gradient) {
  59276. return -1;
  59277. }
  59278. else if (a.gradient > b.gradient) {
  59279. return 1;
  59280. }
  59281. return 0;
  59282. });
  59283. };
  59284. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59285. if (!factorGradients) {
  59286. return;
  59287. }
  59288. var index = 0;
  59289. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59290. var factorGradient = factorGradients_1[_i];
  59291. if (factorGradient.gradient === gradient) {
  59292. factorGradients.splice(index, 1);
  59293. break;
  59294. }
  59295. index++;
  59296. }
  59297. };
  59298. /**
  59299. * Adds a new life time gradient
  59300. * @param gradient defines the gradient to use (between 0 and 1)
  59301. * @param factor defines the life time factor to affect to the specified gradient
  59302. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59303. * @returns the current particle system
  59304. */
  59305. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59306. if (!this._lifeTimeGradients) {
  59307. this._lifeTimeGradients = [];
  59308. }
  59309. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59310. return this;
  59311. };
  59312. /**
  59313. * Remove a specific life time gradient
  59314. * @param gradient defines the gradient to remove
  59315. * @returns the current particle system
  59316. */
  59317. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59318. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59319. return this;
  59320. };
  59321. /**
  59322. * Adds a new size gradient
  59323. * @param gradient defines the gradient to use (between 0 and 1)
  59324. * @param factor defines the size factor to affect to the specified gradient
  59325. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59326. * @returns the current particle system
  59327. */
  59328. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59329. if (!this._sizeGradients) {
  59330. this._sizeGradients = [];
  59331. }
  59332. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59333. return this;
  59334. };
  59335. /**
  59336. * Remove a specific size gradient
  59337. * @param gradient defines the gradient to remove
  59338. * @returns the current particle system
  59339. */
  59340. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59341. this._removeFactorGradient(this._sizeGradients, gradient);
  59342. return this;
  59343. };
  59344. /**
  59345. * Adds a new color remap gradient
  59346. * @param gradient defines the gradient to use (between 0 and 1)
  59347. * @param min defines the color remap minimal range
  59348. * @param max defines the color remap maximal range
  59349. * @returns the current particle system
  59350. */
  59351. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59352. if (!this._colorRemapGradients) {
  59353. this._colorRemapGradients = [];
  59354. }
  59355. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59356. return this;
  59357. };
  59358. /**
  59359. * Remove a specific color remap gradient
  59360. * @param gradient defines the gradient to remove
  59361. * @returns the current particle system
  59362. */
  59363. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59364. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59365. return this;
  59366. };
  59367. /**
  59368. * Adds a new alpha remap gradient
  59369. * @param gradient defines the gradient to use (between 0 and 1)
  59370. * @param min defines the alpha remap minimal range
  59371. * @param max defines the alpha remap maximal range
  59372. * @returns the current particle system
  59373. */
  59374. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59375. if (!this._alphaRemapGradients) {
  59376. this._alphaRemapGradients = [];
  59377. }
  59378. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59379. return this;
  59380. };
  59381. /**
  59382. * Remove a specific alpha remap gradient
  59383. * @param gradient defines the gradient to remove
  59384. * @returns the current particle system
  59385. */
  59386. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59387. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59388. return this;
  59389. };
  59390. /**
  59391. * Adds a new angular speed gradient
  59392. * @param gradient defines the gradient to use (between 0 and 1)
  59393. * @param factor defines the angular speed to affect to the specified gradient
  59394. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59395. * @returns the current particle system
  59396. */
  59397. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59398. if (!this._angularSpeedGradients) {
  59399. this._angularSpeedGradients = [];
  59400. }
  59401. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59402. return this;
  59403. };
  59404. /**
  59405. * Remove a specific angular speed gradient
  59406. * @param gradient defines the gradient to remove
  59407. * @returns the current particle system
  59408. */
  59409. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59410. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59411. return this;
  59412. };
  59413. /**
  59414. * Adds a new velocity gradient
  59415. * @param gradient defines the gradient to use (between 0 and 1)
  59416. * @param factor defines the velocity to affect to the specified gradient
  59417. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59418. * @returns the current particle system
  59419. */
  59420. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59421. if (!this._velocityGradients) {
  59422. this._velocityGradients = [];
  59423. }
  59424. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59425. return this;
  59426. };
  59427. /**
  59428. * Remove a specific velocity gradient
  59429. * @param gradient defines the gradient to remove
  59430. * @returns the current particle system
  59431. */
  59432. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59433. this._removeFactorGradient(this._velocityGradients, gradient);
  59434. return this;
  59435. };
  59436. /**
  59437. * Adds a new limit velocity gradient
  59438. * @param gradient defines the gradient to use (between 0 and 1)
  59439. * @param factor defines the limit velocity value to affect to the specified gradient
  59440. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59441. * @returns the current particle system
  59442. */
  59443. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59444. if (!this._limitVelocityGradients) {
  59445. this._limitVelocityGradients = [];
  59446. }
  59447. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59448. return this;
  59449. };
  59450. /**
  59451. * Remove a specific limit velocity gradient
  59452. * @param gradient defines the gradient to remove
  59453. * @returns the current particle system
  59454. */
  59455. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59456. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59457. return this;
  59458. };
  59459. /**
  59460. * Adds a new drag gradient
  59461. * @param gradient defines the gradient to use (between 0 and 1)
  59462. * @param factor defines the drag value to affect to the specified gradient
  59463. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59464. * @returns the current particle system
  59465. */
  59466. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59467. if (!this._dragGradients) {
  59468. this._dragGradients = [];
  59469. }
  59470. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59471. return this;
  59472. };
  59473. /**
  59474. * Remove a specific drag gradient
  59475. * @param gradient defines the gradient to remove
  59476. * @returns the current particle system
  59477. */
  59478. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59479. this._removeFactorGradient(this._dragGradients, gradient);
  59480. return this;
  59481. };
  59482. /**
  59483. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59484. * @param gradient defines the gradient to use (between 0 and 1)
  59485. * @param factor defines the emit rate value to affect to the specified gradient
  59486. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59487. * @returns the current particle system
  59488. */
  59489. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59490. if (!this._emitRateGradients) {
  59491. this._emitRateGradients = [];
  59492. }
  59493. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59494. return this;
  59495. };
  59496. /**
  59497. * Remove a specific emit rate gradient
  59498. * @param gradient defines the gradient to remove
  59499. * @returns the current particle system
  59500. */
  59501. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59502. this._removeFactorGradient(this._emitRateGradients, gradient);
  59503. return this;
  59504. };
  59505. /**
  59506. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59507. * @param gradient defines the gradient to use (between 0 and 1)
  59508. * @param factor defines the start size value to affect to the specified gradient
  59509. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59510. * @returns the current particle system
  59511. */
  59512. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59513. if (!this._startSizeGradients) {
  59514. this._startSizeGradients = [];
  59515. }
  59516. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59517. return this;
  59518. };
  59519. /**
  59520. * Remove a specific start size gradient
  59521. * @param gradient defines the gradient to remove
  59522. * @returns the current particle system
  59523. */
  59524. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59525. this._removeFactorGradient(this._emitRateGradients, gradient);
  59526. return this;
  59527. };
  59528. ParticleSystem.prototype._createRampGradientTexture = function () {
  59529. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59530. return;
  59531. }
  59532. var data = new Uint8Array(this._rawTextureWidth * 4);
  59533. var tmpColor = BABYLON.Tmp.Color3[0];
  59534. for (var x = 0; x < this._rawTextureWidth; x++) {
  59535. var ratio = x / this._rawTextureWidth;
  59536. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59537. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59538. data[x * 4] = tmpColor.r * 255;
  59539. data[x * 4 + 1] = tmpColor.g * 255;
  59540. data[x * 4 + 2] = tmpColor.b * 255;
  59541. data[x * 4 + 3] = 255;
  59542. });
  59543. }
  59544. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59545. };
  59546. /**
  59547. * Gets the current list of ramp gradients.
  59548. * You must use addRampGradient and removeRampGradient to udpate this list
  59549. * @returns the list of ramp gradients
  59550. */
  59551. ParticleSystem.prototype.getRampGradients = function () {
  59552. return this._rampGradients;
  59553. };
  59554. /**
  59555. * Adds a new ramp gradient used to remap particle colors
  59556. * @param gradient defines the gradient to use (between 0 and 1)
  59557. * @param color defines the color to affect to the specified gradient
  59558. * @returns the current particle system
  59559. */
  59560. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59561. if (!this._rampGradients) {
  59562. this._rampGradients = [];
  59563. }
  59564. var rampGradient = new BABYLON.Color3Gradient();
  59565. rampGradient.gradient = gradient;
  59566. rampGradient.color = color;
  59567. this._rampGradients.push(rampGradient);
  59568. this._rampGradients.sort(function (a, b) {
  59569. if (a.gradient < b.gradient) {
  59570. return -1;
  59571. }
  59572. else if (a.gradient > b.gradient) {
  59573. return 1;
  59574. }
  59575. return 0;
  59576. });
  59577. if (this._rampGradientsTexture) {
  59578. this._rampGradientsTexture.dispose();
  59579. this._rampGradientsTexture = null;
  59580. }
  59581. this._createRampGradientTexture();
  59582. return this;
  59583. };
  59584. /**
  59585. * Remove a specific ramp gradient
  59586. * @param gradient defines the gradient to remove
  59587. * @returns the current particle system
  59588. */
  59589. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59590. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59591. this._rampGradientsTexture = null;
  59592. if (this._rampGradients && this._rampGradients.length > 0) {
  59593. this._createRampGradientTexture();
  59594. }
  59595. return this;
  59596. };
  59597. /**
  59598. * Adds a new color gradient
  59599. * @param gradient defines the gradient to use (between 0 and 1)
  59600. * @param color1 defines the color to affect to the specified gradient
  59601. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59602. * @returns this particle system
  59603. */
  59604. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59605. if (!this._colorGradients) {
  59606. this._colorGradients = [];
  59607. }
  59608. var colorGradient = new BABYLON.ColorGradient();
  59609. colorGradient.gradient = gradient;
  59610. colorGradient.color1 = color1;
  59611. colorGradient.color2 = color2;
  59612. this._colorGradients.push(colorGradient);
  59613. this._colorGradients.sort(function (a, b) {
  59614. if (a.gradient < b.gradient) {
  59615. return -1;
  59616. }
  59617. else if (a.gradient > b.gradient) {
  59618. return 1;
  59619. }
  59620. return 0;
  59621. });
  59622. return this;
  59623. };
  59624. /**
  59625. * Remove a specific color gradient
  59626. * @param gradient defines the gradient to remove
  59627. * @returns this particle system
  59628. */
  59629. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59630. if (!this._colorGradients) {
  59631. return this;
  59632. }
  59633. var index = 0;
  59634. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59635. var colorGradient = _a[_i];
  59636. if (colorGradient.gradient === gradient) {
  59637. this._colorGradients.splice(index, 1);
  59638. break;
  59639. }
  59640. index++;
  59641. }
  59642. return this;
  59643. };
  59644. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59645. u = Math.abs(u) * 0.5 + 0.5;
  59646. v = Math.abs(v) * 0.5 + 0.5;
  59647. var wrappedU = ((u * width) % width) | 0;
  59648. var wrappedV = ((v * height) % height) | 0;
  59649. var position = (wrappedU + wrappedV * width) * 4;
  59650. return pixels[position] / 255;
  59651. };
  59652. ParticleSystem.prototype._reset = function () {
  59653. this._resetEffect();
  59654. };
  59655. ParticleSystem.prototype._resetEffect = function () {
  59656. if (this._vertexBuffer) {
  59657. this._vertexBuffer.dispose();
  59658. this._vertexBuffer = null;
  59659. }
  59660. if (this._spriteBuffer) {
  59661. this._spriteBuffer.dispose();
  59662. this._spriteBuffer = null;
  59663. }
  59664. this._createVertexBuffers();
  59665. };
  59666. ParticleSystem.prototype._createVertexBuffers = function () {
  59667. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59668. if (this._isAnimationSheetEnabled) {
  59669. this._vertexBufferSize += 1;
  59670. }
  59671. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59672. this._vertexBufferSize += 3;
  59673. }
  59674. if (this._useRampGradients) {
  59675. this._vertexBufferSize += 4;
  59676. }
  59677. var engine = this._scene.getEngine();
  59678. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59679. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59680. var dataOffset = 0;
  59681. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59682. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59683. dataOffset += 3;
  59684. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59685. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59686. dataOffset += 4;
  59687. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59688. this._vertexBuffers["angle"] = options;
  59689. dataOffset += 1;
  59690. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59691. this._vertexBuffers["size"] = size;
  59692. dataOffset += 2;
  59693. if (this._isAnimationSheetEnabled) {
  59694. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59695. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59696. dataOffset += 1;
  59697. }
  59698. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59699. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59700. this._vertexBuffers["direction"] = directionBuffer;
  59701. dataOffset += 3;
  59702. }
  59703. if (this._useRampGradients) {
  59704. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59705. this._vertexBuffers["remapData"] = rampDataBuffer;
  59706. dataOffset += 4;
  59707. }
  59708. var offsets;
  59709. if (this._useInstancing) {
  59710. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59711. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59712. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59713. }
  59714. else {
  59715. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59716. dataOffset += 2;
  59717. }
  59718. this._vertexBuffers["offset"] = offsets;
  59719. };
  59720. ParticleSystem.prototype._createIndexBuffer = function () {
  59721. if (this._useInstancing) {
  59722. return;
  59723. }
  59724. var indices = [];
  59725. var index = 0;
  59726. for (var count = 0; count < this._capacity; count++) {
  59727. indices.push(index);
  59728. indices.push(index + 1);
  59729. indices.push(index + 2);
  59730. indices.push(index);
  59731. indices.push(index + 2);
  59732. indices.push(index + 3);
  59733. index += 4;
  59734. }
  59735. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59736. };
  59737. /**
  59738. * Gets the maximum number of particles active at the same time.
  59739. * @returns The max number of active particles.
  59740. */
  59741. ParticleSystem.prototype.getCapacity = function () {
  59742. return this._capacity;
  59743. };
  59744. /**
  59745. * Gets whether there are still active particles in the system.
  59746. * @returns True if it is alive, otherwise false.
  59747. */
  59748. ParticleSystem.prototype.isAlive = function () {
  59749. return this._alive;
  59750. };
  59751. /**
  59752. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59753. * @returns True if it has been started, otherwise false.
  59754. */
  59755. ParticleSystem.prototype.isStarted = function () {
  59756. return this._started;
  59757. };
  59758. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59759. var _this = this;
  59760. this._subEmitters = new Array();
  59761. if (this.subEmitters) {
  59762. this.subEmitters.forEach(function (subEmitter) {
  59763. if (subEmitter instanceof ParticleSystem) {
  59764. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59765. }
  59766. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59767. _this._subEmitters.push([subEmitter]);
  59768. }
  59769. else if (subEmitter instanceof Array) {
  59770. _this._subEmitters.push(subEmitter);
  59771. }
  59772. });
  59773. }
  59774. };
  59775. /**
  59776. * Starts the particle system and begins to emit
  59777. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59778. */
  59779. ParticleSystem.prototype.start = function (delay) {
  59780. var _this = this;
  59781. if (delay === void 0) { delay = this.startDelay; }
  59782. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59783. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59784. }
  59785. if (delay) {
  59786. setTimeout(function () {
  59787. _this.start(0);
  59788. }, delay);
  59789. return;
  59790. }
  59791. // Convert the subEmitters field to the constant type field _subEmitters
  59792. this._prepareSubEmitterInternalArray();
  59793. this._started = true;
  59794. this._stopped = false;
  59795. this._actualFrame = 0;
  59796. if (this._subEmitters && this._subEmitters.length != 0) {
  59797. this.activeSubSystems = new Array();
  59798. }
  59799. // Reset emit gradient so it acts the same on every start
  59800. if (this._emitRateGradients) {
  59801. if (this._emitRateGradients.length > 0) {
  59802. this._currentEmitRateGradient = this._emitRateGradients[0];
  59803. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  59804. this._currentEmitRate2 = this._currentEmitRate1;
  59805. }
  59806. if (this._emitRateGradients.length > 1) {
  59807. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  59808. }
  59809. }
  59810. // Reset start size gradient so it acts the same on every start
  59811. if (this._startSizeGradients) {
  59812. if (this._startSizeGradients.length > 0) {
  59813. this._currentStartSizeGradient = this._startSizeGradients[0];
  59814. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  59815. this._currentStartSize2 = this._currentStartSize1;
  59816. }
  59817. if (this._startSizeGradients.length > 1) {
  59818. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  59819. }
  59820. }
  59821. if (this.preWarmCycles) {
  59822. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59823. this.emitter.computeWorldMatrix(true);
  59824. }
  59825. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59826. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59827. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59828. setTimeout(function () {
  59829. for (var index = 0; index < _this.preWarmCycles; index++) {
  59830. _this.animate(true);
  59831. noiseTextureAsProcedural_1.render();
  59832. }
  59833. });
  59834. });
  59835. }
  59836. else {
  59837. for (var index = 0; index < this.preWarmCycles; index++) {
  59838. this.animate(true);
  59839. }
  59840. }
  59841. }
  59842. // Animations
  59843. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59844. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59845. }
  59846. };
  59847. /**
  59848. * Stops the particle system.
  59849. * @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.
  59850. */
  59851. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59852. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59853. this._stopped = true;
  59854. if (stopSubEmitters) {
  59855. this._stopSubEmitters();
  59856. }
  59857. };
  59858. // animation sheet
  59859. /**
  59860. * Remove all active particles
  59861. */
  59862. ParticleSystem.prototype.reset = function () {
  59863. this._stockParticles = [];
  59864. this._particles = [];
  59865. };
  59866. /**
  59867. * @hidden (for internal use only)
  59868. */
  59869. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59870. var offset = index * this._vertexBufferSize;
  59871. this._vertexData[offset++] = particle.position.x;
  59872. this._vertexData[offset++] = particle.position.y;
  59873. this._vertexData[offset++] = particle.position.z;
  59874. this._vertexData[offset++] = particle.color.r;
  59875. this._vertexData[offset++] = particle.color.g;
  59876. this._vertexData[offset++] = particle.color.b;
  59877. this._vertexData[offset++] = particle.color.a;
  59878. this._vertexData[offset++] = particle.angle;
  59879. this._vertexData[offset++] = particle.scale.x * particle.size;
  59880. this._vertexData[offset++] = particle.scale.y * particle.size;
  59881. if (this._isAnimationSheetEnabled) {
  59882. this._vertexData[offset++] = particle.cellIndex;
  59883. }
  59884. if (!this._isBillboardBased) {
  59885. if (particle._initialDirection) {
  59886. this._vertexData[offset++] = particle._initialDirection.x;
  59887. this._vertexData[offset++] = particle._initialDirection.y;
  59888. this._vertexData[offset++] = particle._initialDirection.z;
  59889. }
  59890. else {
  59891. this._vertexData[offset++] = particle.direction.x;
  59892. this._vertexData[offset++] = particle.direction.y;
  59893. this._vertexData[offset++] = particle.direction.z;
  59894. }
  59895. }
  59896. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59897. this._vertexData[offset++] = particle.direction.x;
  59898. this._vertexData[offset++] = particle.direction.y;
  59899. this._vertexData[offset++] = particle.direction.z;
  59900. }
  59901. if (this._useRampGradients) {
  59902. this._vertexData[offset++] = particle.remapData.x;
  59903. this._vertexData[offset++] = particle.remapData.y;
  59904. this._vertexData[offset++] = particle.remapData.z;
  59905. this._vertexData[offset++] = particle.remapData.w;
  59906. }
  59907. if (!this._useInstancing) {
  59908. if (this._isAnimationSheetEnabled) {
  59909. if (offsetX === 0)
  59910. offsetX = this._epsilon;
  59911. else if (offsetX === 1)
  59912. offsetX = 1 - this._epsilon;
  59913. if (offsetY === 0)
  59914. offsetY = this._epsilon;
  59915. else if (offsetY === 1)
  59916. offsetY = 1 - this._epsilon;
  59917. }
  59918. this._vertexData[offset++] = offsetX;
  59919. this._vertexData[offset++] = offsetY;
  59920. }
  59921. };
  59922. ParticleSystem.prototype._stopSubEmitters = function () {
  59923. if (!this.activeSubSystems) {
  59924. return;
  59925. }
  59926. this.activeSubSystems.forEach(function (subSystem) {
  59927. subSystem.stop(true);
  59928. });
  59929. this.activeSubSystems = new Array();
  59930. };
  59931. ParticleSystem.prototype._removeFromRoot = function () {
  59932. if (!this._rootParticleSystem) {
  59933. return;
  59934. }
  59935. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59936. if (index !== -1) {
  59937. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59938. }
  59939. this._rootParticleSystem = null;
  59940. };
  59941. // End of sub system methods
  59942. ParticleSystem.prototype._update = function (newParticles) {
  59943. var _this = this;
  59944. // Update current
  59945. this._alive = this._particles.length > 0;
  59946. if (this.emitter.position) {
  59947. var emitterMesh = this.emitter;
  59948. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59949. }
  59950. else {
  59951. var emitterPosition = this.emitter;
  59952. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59953. }
  59954. this.updateFunction(this._particles);
  59955. // Add new ones
  59956. var particle;
  59957. var _loop_2 = function () {
  59958. if (this_1._particles.length === this_1._capacity) {
  59959. return "break";
  59960. }
  59961. particle = this_1._createParticle();
  59962. this_1._particles.push(particle);
  59963. // Emitter
  59964. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59965. if (this_1.startPositionFunction) {
  59966. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59967. }
  59968. else {
  59969. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59970. }
  59971. if (this_1.startDirectionFunction) {
  59972. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59973. }
  59974. else {
  59975. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  59976. }
  59977. if (emitPower === 0) {
  59978. if (!particle._initialDirection) {
  59979. particle._initialDirection = particle.direction.clone();
  59980. }
  59981. else {
  59982. particle._initialDirection.copyFrom(particle.direction);
  59983. }
  59984. }
  59985. else {
  59986. particle._initialDirection = null;
  59987. }
  59988. particle.direction.scaleInPlace(emitPower);
  59989. // Life time
  59990. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  59991. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  59992. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  59993. var factorGradient1 = currentGradient;
  59994. var factorGradient2 = nextGradient;
  59995. var lifeTime1 = factorGradient1.getFactor();
  59996. var lifeTime2 = factorGradient2.getFactor();
  59997. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  59998. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  59999. });
  60000. }
  60001. else {
  60002. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  60003. }
  60004. // Size
  60005. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  60006. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  60007. }
  60008. else {
  60009. particle._currentSizeGradient = this_1._sizeGradients[0];
  60010. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  60011. particle.size = particle._currentSize1;
  60012. if (this_1._sizeGradients.length > 1) {
  60013. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  60014. }
  60015. else {
  60016. particle._currentSize2 = particle._currentSize1;
  60017. }
  60018. }
  60019. // Size and scale
  60020. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  60021. // Adjust scale by start size
  60022. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60023. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60024. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60025. if (currentGradient !== _this._currentStartSizeGradient) {
  60026. _this._currentStartSize1 = _this._currentStartSize2;
  60027. _this._currentStartSize2 = nextGradient.getFactor();
  60028. _this._currentStartSizeGradient = currentGradient;
  60029. }
  60030. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60031. particle.scale.scaleInPlace(value);
  60032. });
  60033. }
  60034. // Angle
  60035. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60036. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60037. }
  60038. else {
  60039. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60040. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60041. particle._currentAngularSpeed1 = particle.angularSpeed;
  60042. if (this_1._angularSpeedGradients.length > 1) {
  60043. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60044. }
  60045. else {
  60046. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60047. }
  60048. }
  60049. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60050. // Velocity
  60051. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60052. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60053. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60054. if (this_1._velocityGradients.length > 1) {
  60055. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60056. }
  60057. else {
  60058. particle._currentVelocity2 = particle._currentVelocity1;
  60059. }
  60060. }
  60061. // Limit velocity
  60062. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60063. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60064. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60065. if (this_1._limitVelocityGradients.length > 1) {
  60066. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60067. }
  60068. else {
  60069. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60070. }
  60071. }
  60072. // Drag
  60073. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60074. particle._currentDragGradient = this_1._dragGradients[0];
  60075. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60076. if (this_1._dragGradients.length > 1) {
  60077. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60078. }
  60079. else {
  60080. particle._currentDrag2 = particle._currentDrag1;
  60081. }
  60082. }
  60083. // Color
  60084. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60085. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60086. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60087. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60088. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60089. }
  60090. else {
  60091. particle._currentColorGradient = this_1._colorGradients[0];
  60092. particle._currentColorGradient.getColorToRef(particle.color);
  60093. particle._currentColor1.copyFrom(particle.color);
  60094. if (this_1._colorGradients.length > 1) {
  60095. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60096. }
  60097. else {
  60098. particle._currentColor2.copyFrom(particle.color);
  60099. }
  60100. }
  60101. // Sheet
  60102. if (this_1._isAnimationSheetEnabled) {
  60103. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60104. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60105. }
  60106. // Inherited Velocity
  60107. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60108. // Ramp
  60109. if (this_1._useRampGradients) {
  60110. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60111. }
  60112. // Noise texture coordinates
  60113. if (this_1.noiseTexture) {
  60114. if (particle._randomNoiseCoordinates1) {
  60115. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60116. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60117. }
  60118. else {
  60119. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60120. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60121. }
  60122. }
  60123. // Update the position of the attached sub-emitters to match their attached particle
  60124. particle._inheritParticleInfoToSubEmitters();
  60125. };
  60126. var this_1 = this, step;
  60127. for (var index = 0; index < newParticles; index++) {
  60128. var state_1 = _loop_2();
  60129. if (state_1 === "break")
  60130. break;
  60131. }
  60132. };
  60133. /** @hidden */
  60134. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60135. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60136. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60137. if (useRampGradients === void 0) { useRampGradients = false; }
  60138. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60139. if (isAnimationSheetEnabled) {
  60140. attributeNamesOrOptions.push("cellIndex");
  60141. }
  60142. if (!isBillboardBased) {
  60143. attributeNamesOrOptions.push("direction");
  60144. }
  60145. if (useRampGradients) {
  60146. attributeNamesOrOptions.push("remapData");
  60147. }
  60148. return attributeNamesOrOptions;
  60149. };
  60150. /** @hidden */
  60151. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60152. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60153. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60154. if (isAnimationSheetEnabled) {
  60155. effectCreationOption.push("particlesInfos");
  60156. }
  60157. return effectCreationOption;
  60158. };
  60159. /** @hidden */
  60160. ParticleSystem.prototype._getEffect = function (blendMode) {
  60161. if (this._customEffect) {
  60162. return this._customEffect;
  60163. }
  60164. ;
  60165. var defines = [];
  60166. if (this._scene.clipPlane) {
  60167. defines.push("#define CLIPPLANE");
  60168. }
  60169. if (this._scene.clipPlane2) {
  60170. defines.push("#define CLIPPLANE2");
  60171. }
  60172. if (this._scene.clipPlane3) {
  60173. defines.push("#define CLIPPLANE3");
  60174. }
  60175. if (this._scene.clipPlane4) {
  60176. defines.push("#define CLIPPLANE4");
  60177. }
  60178. if (this._isAnimationSheetEnabled) {
  60179. defines.push("#define ANIMATESHEET");
  60180. }
  60181. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60182. defines.push("#define BLENDMULTIPLYMODE");
  60183. }
  60184. if (this._useRampGradients) {
  60185. defines.push("#define RAMPGRADIENT");
  60186. }
  60187. if (this._isBillboardBased) {
  60188. defines.push("#define BILLBOARD");
  60189. switch (this.billboardMode) {
  60190. case ParticleSystem.BILLBOARDMODE_Y:
  60191. defines.push("#define BILLBOARDY");
  60192. break;
  60193. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60194. defines.push("#define BILLBOARDSTRETCHED");
  60195. break;
  60196. case ParticleSystem.BILLBOARDMODE_ALL:
  60197. default:
  60198. break;
  60199. }
  60200. }
  60201. if (this._imageProcessingConfiguration) {
  60202. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60203. defines.push(this._imageProcessingConfigurationDefines.toString());
  60204. }
  60205. // Effect
  60206. var join = defines.join("\n");
  60207. if (this._cachedDefines !== join) {
  60208. this._cachedDefines = join;
  60209. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60210. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60211. var samplers = ["diffuseSampler", "rampSampler"];
  60212. if (BABYLON.ImageProcessingConfiguration) {
  60213. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60214. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60215. }
  60216. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60217. }
  60218. return this._effect;
  60219. };
  60220. /**
  60221. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60222. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60223. */
  60224. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60225. var _this = this;
  60226. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60227. if (!this._started)
  60228. return;
  60229. if (!preWarmOnly) {
  60230. // Check
  60231. if (!this.isReady())
  60232. return;
  60233. if (this._currentRenderId === this._scene.getRenderId()) {
  60234. return;
  60235. }
  60236. this._currentRenderId = this._scene.getRenderId();
  60237. }
  60238. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60239. // Determine the number of particles we need to create
  60240. var newParticles;
  60241. if (this.manualEmitCount > -1) {
  60242. newParticles = this.manualEmitCount;
  60243. this._newPartsExcess = 0;
  60244. this.manualEmitCount = 0;
  60245. }
  60246. else {
  60247. var rate_1 = this.emitRate;
  60248. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60249. var ratio = this._actualFrame / this.targetStopDuration;
  60250. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60251. if (currentGradient !== _this._currentEmitRateGradient) {
  60252. _this._currentEmitRate1 = _this._currentEmitRate2;
  60253. _this._currentEmitRate2 = nextGradient.getFactor();
  60254. _this._currentEmitRateGradient = currentGradient;
  60255. }
  60256. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60257. });
  60258. }
  60259. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60260. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60261. }
  60262. if (this._newPartsExcess > 1.0) {
  60263. newParticles += this._newPartsExcess >> 0;
  60264. this._newPartsExcess -= this._newPartsExcess >> 0;
  60265. }
  60266. this._alive = false;
  60267. if (!this._stopped) {
  60268. this._actualFrame += this._scaledUpdateSpeed;
  60269. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  60270. this.stop();
  60271. }
  60272. else {
  60273. newParticles = 0;
  60274. }
  60275. this._update(newParticles);
  60276. // Stopped?
  60277. if (this._stopped) {
  60278. if (!this._alive) {
  60279. this._started = false;
  60280. if (this.onAnimationEnd) {
  60281. this.onAnimationEnd();
  60282. }
  60283. if (this.disposeOnStop) {
  60284. this._scene._toBeDisposed.push(this);
  60285. }
  60286. }
  60287. }
  60288. if (!preWarmOnly) {
  60289. // Update VBO
  60290. var offset = 0;
  60291. for (var index = 0; index < this._particles.length; index++) {
  60292. var particle = this._particles[index];
  60293. this._appendParticleVertices(offset, particle);
  60294. offset += this._useInstancing ? 1 : 4;
  60295. }
  60296. if (this._vertexBuffer) {
  60297. this._vertexBuffer.update(this._vertexData);
  60298. }
  60299. }
  60300. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60301. this.stop();
  60302. }
  60303. };
  60304. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60305. this._appendParticleVertex(offset++, particle, 0, 0);
  60306. if (!this._useInstancing) {
  60307. this._appendParticleVertex(offset++, particle, 1, 0);
  60308. this._appendParticleVertex(offset++, particle, 1, 1);
  60309. this._appendParticleVertex(offset++, particle, 0, 1);
  60310. }
  60311. };
  60312. /**
  60313. * Rebuilds the particle system.
  60314. */
  60315. ParticleSystem.prototype.rebuild = function () {
  60316. this._createIndexBuffer();
  60317. if (this._vertexBuffer) {
  60318. this._vertexBuffer._rebuild();
  60319. }
  60320. };
  60321. /**
  60322. * Is this system ready to be used/rendered
  60323. * @return true if the system is ready
  60324. */
  60325. ParticleSystem.prototype.isReady = function () {
  60326. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60327. return false;
  60328. }
  60329. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60330. if (!this._getEffect(this.blendMode).isReady()) {
  60331. return false;
  60332. }
  60333. }
  60334. else {
  60335. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60336. return false;
  60337. }
  60338. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60339. return false;
  60340. }
  60341. }
  60342. return true;
  60343. };
  60344. ParticleSystem.prototype._render = function (blendMode) {
  60345. var effect = this._getEffect(blendMode);
  60346. var engine = this._scene.getEngine();
  60347. // Render
  60348. engine.enableEffect(effect);
  60349. var viewMatrix = this._scene.getViewMatrix();
  60350. effect.setTexture("diffuseSampler", this.particleTexture);
  60351. effect.setMatrix("view", viewMatrix);
  60352. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60353. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60354. var baseSize = this.particleTexture.getBaseSize();
  60355. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60356. }
  60357. effect.setVector2("translationPivot", this.translationPivot);
  60358. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60359. if (this._isBillboardBased) {
  60360. var camera = this._scene.activeCamera;
  60361. effect.setVector3("eyePosition", camera.globalPosition);
  60362. }
  60363. if (this._rampGradientsTexture) {
  60364. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60365. }
  60366. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60367. var invView = viewMatrix.clone();
  60368. invView.invert();
  60369. effect.setMatrix("invView", invView);
  60370. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60371. }
  60372. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60373. // image processing
  60374. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60375. this._imageProcessingConfiguration.bind(effect);
  60376. }
  60377. // Draw order
  60378. switch (blendMode) {
  60379. case ParticleSystem.BLENDMODE_ADD:
  60380. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60381. break;
  60382. case ParticleSystem.BLENDMODE_ONEONE:
  60383. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60384. break;
  60385. case ParticleSystem.BLENDMODE_STANDARD:
  60386. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60387. break;
  60388. case ParticleSystem.BLENDMODE_MULTIPLY:
  60389. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60390. break;
  60391. }
  60392. if (this._useInstancing) {
  60393. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60394. }
  60395. else {
  60396. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60397. }
  60398. return this._particles.length;
  60399. };
  60400. /**
  60401. * Renders the particle system in its current state.
  60402. * @returns the current number of particles
  60403. */
  60404. ParticleSystem.prototype.render = function () {
  60405. // Check
  60406. if (!this.isReady() || !this._particles.length) {
  60407. return 0;
  60408. }
  60409. var engine = this._scene.getEngine();
  60410. engine.setState(false);
  60411. if (this.forceDepthWrite) {
  60412. engine.setDepthWrite(true);
  60413. }
  60414. var outparticles = 0;
  60415. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60416. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60417. }
  60418. outparticles = this._render(this.blendMode);
  60419. engine.unbindInstanceAttributes();
  60420. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60421. return outparticles;
  60422. };
  60423. /**
  60424. * Disposes the particle system and free the associated resources
  60425. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60426. */
  60427. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60428. if (disposeTexture === void 0) { disposeTexture = true; }
  60429. if (this._vertexBuffer) {
  60430. this._vertexBuffer.dispose();
  60431. this._vertexBuffer = null;
  60432. }
  60433. if (this._spriteBuffer) {
  60434. this._spriteBuffer.dispose();
  60435. this._spriteBuffer = null;
  60436. }
  60437. if (this._indexBuffer) {
  60438. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60439. this._indexBuffer = null;
  60440. }
  60441. if (disposeTexture && this.particleTexture) {
  60442. this.particleTexture.dispose();
  60443. this.particleTexture = null;
  60444. }
  60445. if (disposeTexture && this.noiseTexture) {
  60446. this.noiseTexture.dispose();
  60447. this.noiseTexture = null;
  60448. }
  60449. if (this._rampGradientsTexture) {
  60450. this._rampGradientsTexture.dispose();
  60451. this._rampGradientsTexture = null;
  60452. }
  60453. this._removeFromRoot();
  60454. if (this._subEmitters && this._subEmitters.length) {
  60455. for (var index = 0; index < this._subEmitters.length; index++) {
  60456. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60457. var subEmitter = _a[_i];
  60458. subEmitter.dispose();
  60459. }
  60460. }
  60461. this._subEmitters = [];
  60462. this.subEmitters = [];
  60463. }
  60464. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60465. this.emitter.dispose(true);
  60466. }
  60467. // Remove from scene
  60468. var index = this._scene.particleSystems.indexOf(this);
  60469. if (index > -1) {
  60470. this._scene.particleSystems.splice(index, 1);
  60471. }
  60472. this._scene._activeParticleSystems.dispose();
  60473. // Callback
  60474. this.onDisposeObservable.notifyObservers(this);
  60475. this.onDisposeObservable.clear();
  60476. this.reset();
  60477. };
  60478. // Clone
  60479. /**
  60480. * Clones the particle system.
  60481. * @param name The name of the cloned object
  60482. * @param newEmitter The new emitter to use
  60483. * @returns the cloned particle system
  60484. */
  60485. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60486. var custom = null;
  60487. var program = null;
  60488. if (this.customShader != null) {
  60489. program = this.customShader;
  60490. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60491. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60492. }
  60493. else if (this._customEffect) {
  60494. custom = this._customEffect;
  60495. }
  60496. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60497. result.customShader = program;
  60498. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60499. if (newEmitter === undefined) {
  60500. newEmitter = this.emitter;
  60501. }
  60502. result.noiseTexture = this.noiseTexture;
  60503. result.emitter = newEmitter;
  60504. if (this.particleTexture) {
  60505. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60506. }
  60507. // Clone gradients
  60508. if (this._colorGradients) {
  60509. this._colorGradients.forEach(function (v) {
  60510. result.addColorGradient(v.gradient, v.color1, v.color2);
  60511. });
  60512. }
  60513. if (this._dragGradients) {
  60514. this._dragGradients.forEach(function (v) {
  60515. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60516. });
  60517. }
  60518. if (this._angularSpeedGradients) {
  60519. this._angularSpeedGradients.forEach(function (v) {
  60520. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60521. });
  60522. }
  60523. if (this._emitRateGradients) {
  60524. this._emitRateGradients.forEach(function (v) {
  60525. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60526. });
  60527. }
  60528. if (this._lifeTimeGradients) {
  60529. this._lifeTimeGradients.forEach(function (v) {
  60530. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60531. });
  60532. }
  60533. if (this._limitVelocityGradients) {
  60534. this._limitVelocityGradients.forEach(function (v) {
  60535. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60536. });
  60537. }
  60538. if (this._sizeGradients) {
  60539. this._sizeGradients.forEach(function (v) {
  60540. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60541. });
  60542. }
  60543. if (this._startSizeGradients) {
  60544. this._startSizeGradients.forEach(function (v) {
  60545. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60546. });
  60547. }
  60548. if (this._velocityGradients) {
  60549. this._velocityGradients.forEach(function (v) {
  60550. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60551. });
  60552. }
  60553. if (this._rampGradients) {
  60554. this._rampGradients.forEach(function (v) {
  60555. result.addRampGradient(v.gradient, v.color);
  60556. });
  60557. }
  60558. if (this._colorRemapGradients) {
  60559. this._colorRemapGradients.forEach(function (v) {
  60560. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60561. });
  60562. }
  60563. if (this._alphaRemapGradients) {
  60564. this._alphaRemapGradients.forEach(function (v) {
  60565. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60566. });
  60567. }
  60568. if (!this.preventAutoStart) {
  60569. result.start();
  60570. }
  60571. return result;
  60572. };
  60573. /**
  60574. * Serializes the particle system to a JSON object.
  60575. * @returns the JSON object
  60576. */
  60577. ParticleSystem.prototype.serialize = function () {
  60578. var serializationObject = {};
  60579. ParticleSystem._Serialize(serializationObject, this);
  60580. serializationObject.textureMask = this.textureMask.asArray();
  60581. serializationObject.customShader = this.customShader;
  60582. serializationObject.preventAutoStart = this.preventAutoStart;
  60583. // SubEmitters
  60584. if (this.subEmitters) {
  60585. serializationObject.subEmitters = [];
  60586. if (!this._subEmitters) {
  60587. this._prepareSubEmitterInternalArray();
  60588. }
  60589. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60590. var subs = _a[_i];
  60591. var cell = [];
  60592. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60593. var sub = subs_1[_b];
  60594. cell.push(sub.serialize());
  60595. }
  60596. serializationObject.subEmitters.push(cell);
  60597. }
  60598. }
  60599. return serializationObject;
  60600. };
  60601. /** @hidden */
  60602. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60603. serializationObject.name = particleSystem.name;
  60604. serializationObject.id = particleSystem.id;
  60605. serializationObject.capacity = particleSystem.getCapacity();
  60606. // Emitter
  60607. if (particleSystem.emitter.position) {
  60608. var emitterMesh = particleSystem.emitter;
  60609. serializationObject.emitterId = emitterMesh.id;
  60610. }
  60611. else {
  60612. var emitterPosition = particleSystem.emitter;
  60613. serializationObject.emitter = emitterPosition.asArray();
  60614. }
  60615. // Emitter
  60616. if (particleSystem.particleEmitterType) {
  60617. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60618. }
  60619. if (particleSystem.particleTexture) {
  60620. serializationObject.textureName = particleSystem.particleTexture.name;
  60621. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60622. }
  60623. // Animations
  60624. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60625. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60626. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60627. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60628. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60629. // Particle system
  60630. serializationObject.startDelay = particleSystem.startDelay;
  60631. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60632. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60633. serializationObject.billboardMode = particleSystem.billboardMode;
  60634. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60635. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60636. serializationObject.minSize = particleSystem.minSize;
  60637. serializationObject.maxSize = particleSystem.maxSize;
  60638. serializationObject.minScaleX = particleSystem.minScaleX;
  60639. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60640. serializationObject.minScaleY = particleSystem.minScaleY;
  60641. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60642. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60643. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60644. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60645. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60646. serializationObject.emitRate = particleSystem.emitRate;
  60647. serializationObject.gravity = particleSystem.gravity.asArray();
  60648. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60649. serializationObject.color1 = particleSystem.color1.asArray();
  60650. serializationObject.color2 = particleSystem.color2.asArray();
  60651. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60652. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60653. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60654. serializationObject.blendMode = particleSystem.blendMode;
  60655. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60656. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60657. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60658. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60659. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60660. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60661. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60662. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60663. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60664. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60665. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60666. var colorGradients = particleSystem.getColorGradients();
  60667. if (colorGradients) {
  60668. serializationObject.colorGradients = [];
  60669. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60670. var colorGradient = colorGradients_1[_i];
  60671. var serializedGradient = {
  60672. gradient: colorGradient.gradient,
  60673. color1: colorGradient.color1.asArray()
  60674. };
  60675. if (colorGradient.color2) {
  60676. serializedGradient.color2 = colorGradient.color2.asArray();
  60677. }
  60678. serializationObject.colorGradients.push(serializedGradient);
  60679. }
  60680. }
  60681. var rampGradients = particleSystem.getRampGradients();
  60682. if (rampGradients) {
  60683. serializationObject.rampGradients = [];
  60684. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60685. var rampGradient = rampGradients_1[_a];
  60686. var serializedGradient = {
  60687. gradient: rampGradient.gradient,
  60688. color: rampGradient.color.asArray()
  60689. };
  60690. serializationObject.rampGradients.push(serializedGradient);
  60691. }
  60692. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60693. }
  60694. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60695. if (colorRemapGradients) {
  60696. serializationObject.colorRemapGradients = [];
  60697. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60698. var colorRemapGradient = colorRemapGradients_1[_b];
  60699. var serializedGradient = {
  60700. gradient: colorRemapGradient.gradient,
  60701. factor1: colorRemapGradient.factor1
  60702. };
  60703. if (colorRemapGradient.factor2 !== undefined) {
  60704. serializedGradient.factor2 = colorRemapGradient.factor2;
  60705. }
  60706. serializationObject.colorRemapGradients.push(serializedGradient);
  60707. }
  60708. }
  60709. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60710. if (alphaRemapGradients) {
  60711. serializationObject.alphaRemapGradients = [];
  60712. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60713. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60714. var serializedGradient = {
  60715. gradient: alphaRemapGradient.gradient,
  60716. factor1: alphaRemapGradient.factor1
  60717. };
  60718. if (alphaRemapGradient.factor2 !== undefined) {
  60719. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60720. }
  60721. serializationObject.alphaRemapGradients.push(serializedGradient);
  60722. }
  60723. }
  60724. var sizeGradients = particleSystem.getSizeGradients();
  60725. if (sizeGradients) {
  60726. serializationObject.sizeGradients = [];
  60727. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60728. var sizeGradient = sizeGradients_1[_d];
  60729. var serializedGradient = {
  60730. gradient: sizeGradient.gradient,
  60731. factor1: sizeGradient.factor1
  60732. };
  60733. if (sizeGradient.factor2 !== undefined) {
  60734. serializedGradient.factor2 = sizeGradient.factor2;
  60735. }
  60736. serializationObject.sizeGradients.push(serializedGradient);
  60737. }
  60738. }
  60739. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60740. if (angularSpeedGradients) {
  60741. serializationObject.angularSpeedGradients = [];
  60742. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60743. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60744. var serializedGradient = {
  60745. gradient: angularSpeedGradient.gradient,
  60746. factor1: angularSpeedGradient.factor1
  60747. };
  60748. if (angularSpeedGradient.factor2 !== undefined) {
  60749. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60750. }
  60751. serializationObject.angularSpeedGradients.push(serializedGradient);
  60752. }
  60753. }
  60754. var velocityGradients = particleSystem.getVelocityGradients();
  60755. if (velocityGradients) {
  60756. serializationObject.velocityGradients = [];
  60757. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60758. var velocityGradient = velocityGradients_1[_f];
  60759. var serializedGradient = {
  60760. gradient: velocityGradient.gradient,
  60761. factor1: velocityGradient.factor1
  60762. };
  60763. if (velocityGradient.factor2 !== undefined) {
  60764. serializedGradient.factor2 = velocityGradient.factor2;
  60765. }
  60766. serializationObject.velocityGradients.push(serializedGradient);
  60767. }
  60768. }
  60769. var dragGradients = particleSystem.getDragGradients();
  60770. if (dragGradients) {
  60771. serializationObject.dragyGradients = [];
  60772. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60773. var dragGradient = dragGradients_1[_g];
  60774. var serializedGradient = {
  60775. gradient: dragGradient.gradient,
  60776. factor1: dragGradient.factor1
  60777. };
  60778. if (dragGradient.factor2 !== undefined) {
  60779. serializedGradient.factor2 = dragGradient.factor2;
  60780. }
  60781. serializationObject.dragGradients.push(serializedGradient);
  60782. }
  60783. }
  60784. var emitRateGradients = particleSystem.getEmitRateGradients();
  60785. if (emitRateGradients) {
  60786. serializationObject.emitRateGradients = [];
  60787. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60788. var emitRateGradient = emitRateGradients_1[_h];
  60789. var serializedGradient = {
  60790. gradient: emitRateGradient.gradient,
  60791. factor1: emitRateGradient.factor1
  60792. };
  60793. if (emitRateGradient.factor2 !== undefined) {
  60794. serializedGradient.factor2 = emitRateGradient.factor2;
  60795. }
  60796. serializationObject.emitRateGradients.push(serializedGradient);
  60797. }
  60798. }
  60799. var startSizeGradients = particleSystem.getStartSizeGradients();
  60800. if (startSizeGradients) {
  60801. serializationObject.startSizeGradients = [];
  60802. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60803. var startSizeGradient = startSizeGradients_1[_j];
  60804. var serializedGradient = {
  60805. gradient: startSizeGradient.gradient,
  60806. factor1: startSizeGradient.factor1
  60807. };
  60808. if (startSizeGradient.factor2 !== undefined) {
  60809. serializedGradient.factor2 = startSizeGradient.factor2;
  60810. }
  60811. serializationObject.startSizeGradients.push(serializedGradient);
  60812. }
  60813. }
  60814. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60815. if (lifeTimeGradients) {
  60816. serializationObject.lifeTimeGradients = [];
  60817. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60818. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60819. var serializedGradient = {
  60820. gradient: lifeTimeGradient.gradient,
  60821. factor1: lifeTimeGradient.factor1
  60822. };
  60823. if (lifeTimeGradient.factor2 !== undefined) {
  60824. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60825. }
  60826. serializationObject.lifeTimeGradients.push(serializedGradient);
  60827. }
  60828. }
  60829. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60830. if (limitVelocityGradients) {
  60831. serializationObject.limitVelocityGradients = [];
  60832. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60833. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60834. var serializedGradient = {
  60835. gradient: limitVelocityGradient.gradient,
  60836. factor1: limitVelocityGradient.factor1
  60837. };
  60838. if (limitVelocityGradient.factor2 !== undefined) {
  60839. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60840. }
  60841. serializationObject.limitVelocityGradients.push(serializedGradient);
  60842. }
  60843. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60844. }
  60845. if (particleSystem.noiseTexture) {
  60846. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60847. }
  60848. };
  60849. /** @hidden */
  60850. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60851. // Texture
  60852. if (parsedParticleSystem.textureName) {
  60853. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60854. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60855. }
  60856. // Emitter
  60857. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60858. particleSystem.emitter = BABYLON.Vector3.Zero();
  60859. }
  60860. else if (parsedParticleSystem.emitterId) {
  60861. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60862. }
  60863. else {
  60864. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60865. }
  60866. // Misc.
  60867. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60868. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60869. }
  60870. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60871. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60872. }
  60873. if (parsedParticleSystem.billboardMode !== undefined) {
  60874. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60875. }
  60876. // Animations
  60877. if (parsedParticleSystem.animations) {
  60878. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60879. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60880. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60881. }
  60882. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60883. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60884. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60885. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60886. }
  60887. if (parsedParticleSystem.autoAnimate) {
  60888. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60889. }
  60890. // Particle system
  60891. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60892. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60893. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60894. particleSystem.minSize = parsedParticleSystem.minSize;
  60895. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60896. if (parsedParticleSystem.minScaleX) {
  60897. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60898. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60899. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60900. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60901. }
  60902. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60903. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60904. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60905. }
  60906. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60907. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60908. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60909. }
  60910. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60911. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60912. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60913. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60914. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60915. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60916. if (parsedParticleSystem.noiseStrength) {
  60917. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60918. }
  60919. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60920. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60921. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60922. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60923. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60924. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60925. if (parsedParticleSystem.colorGradients) {
  60926. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60927. var colorGradient = _a[_i];
  60928. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60929. }
  60930. }
  60931. if (parsedParticleSystem.rampGradients) {
  60932. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60933. var rampGradient = _c[_b];
  60934. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60935. }
  60936. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60937. }
  60938. if (parsedParticleSystem.colorRemapGradients) {
  60939. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60940. var colorRemapGradient = _e[_d];
  60941. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60942. }
  60943. }
  60944. if (parsedParticleSystem.alphaRemapGradients) {
  60945. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60946. var alphaRemapGradient = _g[_f];
  60947. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60948. }
  60949. }
  60950. if (parsedParticleSystem.sizeGradients) {
  60951. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60952. var sizeGradient = _j[_h];
  60953. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60954. }
  60955. }
  60956. if (parsedParticleSystem.sizeGradients) {
  60957. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60958. var sizeGradient = _l[_k];
  60959. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60960. }
  60961. }
  60962. if (parsedParticleSystem.angularSpeedGradients) {
  60963. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60964. var angularSpeedGradient = _o[_m];
  60965. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60966. }
  60967. }
  60968. if (parsedParticleSystem.velocityGradients) {
  60969. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60970. var velocityGradient = _q[_p];
  60971. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60972. }
  60973. }
  60974. if (parsedParticleSystem.dragGradients) {
  60975. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  60976. var dragGradient = _s[_r];
  60977. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  60978. }
  60979. }
  60980. if (parsedParticleSystem.emitRateGradients) {
  60981. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  60982. var emitRateGradient = _u[_t];
  60983. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  60984. }
  60985. }
  60986. if (parsedParticleSystem.startSizeGradients) {
  60987. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  60988. var startSizeGradient = _w[_v];
  60989. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  60990. }
  60991. }
  60992. if (parsedParticleSystem.lifeTimeGradients) {
  60993. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  60994. var lifeTimeGradient = _y[_x];
  60995. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  60996. }
  60997. }
  60998. if (parsedParticleSystem.limitVelocityGradients) {
  60999. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  61000. var limitVelocityGradient = _0[_z];
  61001. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  61002. }
  61003. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  61004. }
  61005. if (parsedParticleSystem.noiseTexture) {
  61006. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  61007. }
  61008. // Emitter
  61009. var emitterType;
  61010. if (parsedParticleSystem.particleEmitterType) {
  61011. switch (parsedParticleSystem.particleEmitterType.type) {
  61012. case "SphereParticleEmitter":
  61013. emitterType = new BABYLON.SphereParticleEmitter();
  61014. break;
  61015. case "SphereDirectedParticleEmitter":
  61016. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  61017. break;
  61018. case "ConeEmitter":
  61019. case "ConeParticleEmitter":
  61020. emitterType = new BABYLON.ConeParticleEmitter();
  61021. break;
  61022. case "CylinderParticleEmitter":
  61023. emitterType = new BABYLON.CylinderParticleEmitter();
  61024. break;
  61025. case "HemisphericParticleEmitter":
  61026. emitterType = new BABYLON.HemisphericParticleEmitter();
  61027. break;
  61028. case "BoxEmitter":
  61029. case "BoxParticleEmitter":
  61030. default:
  61031. emitterType = new BABYLON.BoxParticleEmitter();
  61032. break;
  61033. }
  61034. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61035. }
  61036. else {
  61037. emitterType = new BABYLON.BoxParticleEmitter();
  61038. emitterType.parse(parsedParticleSystem);
  61039. }
  61040. particleSystem.particleEmitterType = emitterType;
  61041. // Animation sheet
  61042. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61043. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61044. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61045. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61046. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61047. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61048. };
  61049. /**
  61050. * Parses a JSON object to create a particle system.
  61051. * @param parsedParticleSystem The JSON object to parse
  61052. * @param scene The scene to create the particle system in
  61053. * @param rootUrl The root url to use to load external dependencies like texture
  61054. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61055. * @returns the Parsed particle system
  61056. */
  61057. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61058. if (doNotStart === void 0) { doNotStart = false; }
  61059. var name = parsedParticleSystem.name;
  61060. var custom = null;
  61061. var program = null;
  61062. if (parsedParticleSystem.customShader) {
  61063. program = parsedParticleSystem.customShader;
  61064. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61065. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61066. }
  61067. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61068. particleSystem.customShader = program;
  61069. if (parsedParticleSystem.id) {
  61070. particleSystem.id = parsedParticleSystem.id;
  61071. }
  61072. // SubEmitters
  61073. if (parsedParticleSystem.subEmitters) {
  61074. particleSystem.subEmitters = [];
  61075. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61076. var cell = _a[_i];
  61077. var cellArray = [];
  61078. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61079. var sub = cell_1[_b];
  61080. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61081. }
  61082. particleSystem.subEmitters.push(cellArray);
  61083. }
  61084. }
  61085. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61086. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61087. // Auto start
  61088. if (parsedParticleSystem.preventAutoStart) {
  61089. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61090. }
  61091. if (!doNotStart && !particleSystem.preventAutoStart) {
  61092. particleSystem.start();
  61093. }
  61094. return particleSystem;
  61095. };
  61096. /**
  61097. * Billboard mode will only apply to Y axis
  61098. */
  61099. ParticleSystem.BILLBOARDMODE_Y = 2;
  61100. /**
  61101. * Billboard mode will apply to all axes
  61102. */
  61103. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61104. /**
  61105. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61106. */
  61107. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61108. return ParticleSystem;
  61109. }(BABYLON.BaseParticleSystem));
  61110. BABYLON.ParticleSystem = ParticleSystem;
  61111. })(BABYLON || (BABYLON = {}));
  61112. //# sourceMappingURL=babylon.particleSystem.js.map
  61113. var BABYLON;
  61114. (function (BABYLON) {
  61115. /**
  61116. * Particle emitter emitting particles from the inside of a box.
  61117. * It emits the particles randomly between 2 given directions.
  61118. */
  61119. var BoxParticleEmitter = /** @class */ (function () {
  61120. /**
  61121. * Creates a new instance BoxParticleEmitter
  61122. */
  61123. function BoxParticleEmitter() {
  61124. /**
  61125. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61126. */
  61127. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61128. /**
  61129. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61130. */
  61131. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61132. /**
  61133. * 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.
  61134. */
  61135. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61136. /**
  61137. * 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.
  61138. */
  61139. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61140. }
  61141. /**
  61142. * Called by the particle System when the direction is computed for the created particle.
  61143. * @param worldMatrix is the world matrix of the particle system
  61144. * @param directionToUpdate is the direction vector to update with the result
  61145. * @param particle is the particle we are computed the direction for
  61146. */
  61147. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61148. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61149. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61150. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61151. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61152. };
  61153. /**
  61154. * Called by the particle System when the position is computed for the created particle.
  61155. * @param worldMatrix is the world matrix of the particle system
  61156. * @param positionToUpdate is the position vector to update with the result
  61157. * @param particle is the particle we are computed the position for
  61158. */
  61159. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61160. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61161. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61162. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61163. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61164. };
  61165. /**
  61166. * Clones the current emitter and returns a copy of it
  61167. * @returns the new emitter
  61168. */
  61169. BoxParticleEmitter.prototype.clone = function () {
  61170. var newOne = new BoxParticleEmitter();
  61171. BABYLON.Tools.DeepCopy(this, newOne);
  61172. return newOne;
  61173. };
  61174. /**
  61175. * Called by the GPUParticleSystem to setup the update shader
  61176. * @param effect defines the update shader
  61177. */
  61178. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61179. effect.setVector3("direction1", this.direction1);
  61180. effect.setVector3("direction2", this.direction2);
  61181. effect.setVector3("minEmitBox", this.minEmitBox);
  61182. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61183. };
  61184. /**
  61185. * Returns a string to use to update the GPU particles update shader
  61186. * @returns a string containng the defines string
  61187. */
  61188. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61189. return "#define BOXEMITTER";
  61190. };
  61191. /**
  61192. * Returns the string "BoxParticleEmitter"
  61193. * @returns a string containing the class name
  61194. */
  61195. BoxParticleEmitter.prototype.getClassName = function () {
  61196. return "BoxParticleEmitter";
  61197. };
  61198. /**
  61199. * Serializes the particle system to a JSON object.
  61200. * @returns the JSON object
  61201. */
  61202. BoxParticleEmitter.prototype.serialize = function () {
  61203. var serializationObject = {};
  61204. serializationObject.type = this.getClassName();
  61205. serializationObject.direction1 = this.direction1.asArray();
  61206. serializationObject.direction2 = this.direction2.asArray();
  61207. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61208. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61209. return serializationObject;
  61210. };
  61211. /**
  61212. * Parse properties from a JSON object
  61213. * @param serializationObject defines the JSON object
  61214. */
  61215. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61216. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61217. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61218. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61219. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61220. };
  61221. return BoxParticleEmitter;
  61222. }());
  61223. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61224. })(BABYLON || (BABYLON = {}));
  61225. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61226. var BABYLON;
  61227. (function (BABYLON) {
  61228. /**
  61229. * Particle emitter emitting particles from the inside of a cylinder.
  61230. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61231. */
  61232. var CylinderParticleEmitter = /** @class */ (function () {
  61233. /**
  61234. * Creates a new instance CylinderParticleEmitter
  61235. * @param radius the radius of the emission cylinder (1 by default)
  61236. * @param height the height of the emission cylinder (1 by default)
  61237. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61238. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61239. */
  61240. function CylinderParticleEmitter(
  61241. /**
  61242. * The radius of the emission cylinder.
  61243. */
  61244. radius,
  61245. /**
  61246. * The height of the emission cylinder.
  61247. */
  61248. height,
  61249. /**
  61250. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61251. */
  61252. radiusRange,
  61253. /**
  61254. * How much to randomize the particle direction [0-1].
  61255. */
  61256. directionRandomizer) {
  61257. if (radius === void 0) { radius = 1; }
  61258. if (height === void 0) { height = 1; }
  61259. if (radiusRange === void 0) { radiusRange = 1; }
  61260. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61261. this.radius = radius;
  61262. this.height = height;
  61263. this.radiusRange = radiusRange;
  61264. this.directionRandomizer = directionRandomizer;
  61265. }
  61266. /**
  61267. * Called by the particle System when the direction is computed for the created particle.
  61268. * @param worldMatrix is the world matrix of the particle system
  61269. * @param directionToUpdate is the direction vector to update with the result
  61270. * @param particle is the particle we are computed the direction for
  61271. */
  61272. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61273. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61274. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61275. var angle = Math.atan2(direction.x, direction.z);
  61276. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61277. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61278. direction.x = Math.sin(angle);
  61279. direction.z = Math.cos(angle);
  61280. direction.normalize();
  61281. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61282. };
  61283. /**
  61284. * Called by the particle System when the position is computed for the created particle.
  61285. * @param worldMatrix is the world matrix of the particle system
  61286. * @param positionToUpdate is the position vector to update with the result
  61287. * @param particle is the particle we are computed the position for
  61288. */
  61289. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61290. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61291. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61292. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61293. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61294. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61295. var xPos = positionRadius * Math.cos(angle);
  61296. var zPos = positionRadius * Math.sin(angle);
  61297. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61298. };
  61299. /**
  61300. * Clones the current emitter and returns a copy of it
  61301. * @returns the new emitter
  61302. */
  61303. CylinderParticleEmitter.prototype.clone = function () {
  61304. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61305. BABYLON.Tools.DeepCopy(this, newOne);
  61306. return newOne;
  61307. };
  61308. /**
  61309. * Called by the GPUParticleSystem to setup the update shader
  61310. * @param effect defines the update shader
  61311. */
  61312. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61313. effect.setFloat("radius", this.radius);
  61314. effect.setFloat("height", this.height);
  61315. effect.setFloat("radiusRange", this.radiusRange);
  61316. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61317. };
  61318. /**
  61319. * Returns a string to use to update the GPU particles update shader
  61320. * @returns a string containng the defines string
  61321. */
  61322. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61323. return "#define CYLINDEREMITTER";
  61324. };
  61325. /**
  61326. * Returns the string "CylinderParticleEmitter"
  61327. * @returns a string containing the class name
  61328. */
  61329. CylinderParticleEmitter.prototype.getClassName = function () {
  61330. return "CylinderParticleEmitter";
  61331. };
  61332. /**
  61333. * Serializes the particle system to a JSON object.
  61334. * @returns the JSON object
  61335. */
  61336. CylinderParticleEmitter.prototype.serialize = function () {
  61337. var serializationObject = {};
  61338. serializationObject.type = this.getClassName();
  61339. serializationObject.radius = this.radius;
  61340. serializationObject.height = this.height;
  61341. serializationObject.radiusRange = this.radiusRange;
  61342. serializationObject.directionRandomizer = this.directionRandomizer;
  61343. return serializationObject;
  61344. };
  61345. /**
  61346. * Parse properties from a JSON object
  61347. * @param serializationObject defines the JSON object
  61348. */
  61349. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61350. this.radius = serializationObject.radius;
  61351. this.height = serializationObject.height;
  61352. this.radiusRange = serializationObject.radiusRange;
  61353. this.directionRandomizer = serializationObject.directionRandomizer;
  61354. };
  61355. return CylinderParticleEmitter;
  61356. }());
  61357. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61358. /**
  61359. * Particle emitter emitting particles from the inside of a cylinder.
  61360. * It emits the particles randomly between two vectors.
  61361. */
  61362. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61363. __extends(CylinderDirectedParticleEmitter, _super);
  61364. /**
  61365. * Creates a new instance CylinderDirectedParticleEmitter
  61366. * @param radius the radius of the emission cylinder (1 by default)
  61367. * @param height the height of the emission cylinder (1 by default)
  61368. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61369. * @param direction1 the min limit of the emission direction (up vector by default)
  61370. * @param direction2 the max limit of the emission direction (up vector by default)
  61371. */
  61372. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61373. /**
  61374. * The min limit of the emission direction.
  61375. */
  61376. direction1,
  61377. /**
  61378. * The max limit of the emission direction.
  61379. */
  61380. direction2) {
  61381. if (radius === void 0) { radius = 1; }
  61382. if (height === void 0) { height = 1; }
  61383. if (radiusRange === void 0) { radiusRange = 1; }
  61384. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61385. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61386. var _this = _super.call(this, radius, height, radiusRange) || this;
  61387. _this.direction1 = direction1;
  61388. _this.direction2 = direction2;
  61389. return _this;
  61390. }
  61391. /**
  61392. * Called by the particle System when the direction is computed for the created particle.
  61393. * @param worldMatrix is the world matrix of the particle system
  61394. * @param directionToUpdate is the direction vector to update with the result
  61395. * @param particle is the particle we are computed the direction for
  61396. */
  61397. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61398. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61399. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61400. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61401. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61402. };
  61403. /**
  61404. * Clones the current emitter and returns a copy of it
  61405. * @returns the new emitter
  61406. */
  61407. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61408. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61409. BABYLON.Tools.DeepCopy(this, newOne);
  61410. return newOne;
  61411. };
  61412. /**
  61413. * Called by the GPUParticleSystem to setup the update shader
  61414. * @param effect defines the update shader
  61415. */
  61416. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61417. effect.setFloat("radius", this.radius);
  61418. effect.setFloat("height", this.height);
  61419. effect.setFloat("radiusRange", this.radiusRange);
  61420. effect.setVector3("direction1", this.direction1);
  61421. effect.setVector3("direction2", this.direction2);
  61422. };
  61423. /**
  61424. * Returns a string to use to update the GPU particles update shader
  61425. * @returns a string containng the defines string
  61426. */
  61427. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61428. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61429. };
  61430. /**
  61431. * Returns the string "CylinderDirectedParticleEmitter"
  61432. * @returns a string containing the class name
  61433. */
  61434. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61435. return "CylinderDirectedParticleEmitter";
  61436. };
  61437. /**
  61438. * Serializes the particle system to a JSON object.
  61439. * @returns the JSON object
  61440. */
  61441. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61442. var serializationObject = _super.prototype.serialize.call(this);
  61443. serializationObject.direction1 = this.direction1.asArray();
  61444. serializationObject.direction2 = this.direction2.asArray();
  61445. return serializationObject;
  61446. };
  61447. /**
  61448. * Parse properties from a JSON object
  61449. * @param serializationObject defines the JSON object
  61450. */
  61451. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61452. _super.prototype.parse.call(this, serializationObject);
  61453. this.direction1.copyFrom(serializationObject.direction1);
  61454. this.direction2.copyFrom(serializationObject.direction2);
  61455. };
  61456. return CylinderDirectedParticleEmitter;
  61457. }(CylinderParticleEmitter));
  61458. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61459. })(BABYLON || (BABYLON = {}));
  61460. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61461. var BABYLON;
  61462. (function (BABYLON) {
  61463. /**
  61464. * Particle emitter emitting particles from the inside of a cone.
  61465. * It emits the particles alongside the cone volume from the base to the particle.
  61466. * The emission direction might be randomized.
  61467. */
  61468. var ConeParticleEmitter = /** @class */ (function () {
  61469. /**
  61470. * Creates a new instance ConeParticleEmitter
  61471. * @param radius the radius of the emission cone (1 by default)
  61472. * @param angles the cone base angle (PI by default)
  61473. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61474. */
  61475. function ConeParticleEmitter(radius, angle,
  61476. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61477. directionRandomizer) {
  61478. if (radius === void 0) { radius = 1; }
  61479. if (angle === void 0) { angle = Math.PI; }
  61480. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61481. this.directionRandomizer = directionRandomizer;
  61482. /**
  61483. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61484. */
  61485. this.radiusRange = 1;
  61486. /**
  61487. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61488. */
  61489. this.heightRange = 1;
  61490. /**
  61491. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61492. */
  61493. this.emitFromSpawnPointOnly = false;
  61494. this.angle = angle;
  61495. this.radius = radius;
  61496. }
  61497. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61498. /**
  61499. * Gets or sets the radius of the emission cone
  61500. */
  61501. get: function () {
  61502. return this._radius;
  61503. },
  61504. set: function (value) {
  61505. this._radius = value;
  61506. this._buildHeight();
  61507. },
  61508. enumerable: true,
  61509. configurable: true
  61510. });
  61511. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61512. /**
  61513. * Gets or sets the angle of the emission cone
  61514. */
  61515. get: function () {
  61516. return this._angle;
  61517. },
  61518. set: function (value) {
  61519. this._angle = value;
  61520. this._buildHeight();
  61521. },
  61522. enumerable: true,
  61523. configurable: true
  61524. });
  61525. ConeParticleEmitter.prototype._buildHeight = function () {
  61526. if (this._angle !== 0) {
  61527. this._height = this._radius / Math.tan(this._angle / 2);
  61528. }
  61529. else {
  61530. this._height = 1;
  61531. }
  61532. };
  61533. /**
  61534. * Called by the particle System when the direction is computed for the created particle.
  61535. * @param worldMatrix is the world matrix of the particle system
  61536. * @param directionToUpdate is the direction vector to update with the result
  61537. * @param particle is the particle we are computed the direction for
  61538. */
  61539. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61540. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61541. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61542. }
  61543. else {
  61544. // measure the direction Vector from the emitter to the particle.
  61545. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61546. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61547. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61548. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61549. direction.x += randX;
  61550. direction.y += randY;
  61551. direction.z += randZ;
  61552. direction.normalize();
  61553. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61554. }
  61555. };
  61556. /**
  61557. * Called by the particle System when the position is computed for the created particle.
  61558. * @param worldMatrix is the world matrix of the particle system
  61559. * @param positionToUpdate is the position vector to update with the result
  61560. * @param particle is the particle we are computed the position for
  61561. */
  61562. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61563. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61564. var h;
  61565. if (!this.emitFromSpawnPointOnly) {
  61566. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61567. // Better distribution in a cone at normal angles.
  61568. h = 1 - h * h;
  61569. }
  61570. else {
  61571. h = 0.0001;
  61572. }
  61573. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61574. radius = radius * h;
  61575. var randX = radius * Math.sin(s);
  61576. var randZ = radius * Math.cos(s);
  61577. var randY = h * this._height;
  61578. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61579. };
  61580. /**
  61581. * Clones the current emitter and returns a copy of it
  61582. * @returns the new emitter
  61583. */
  61584. ConeParticleEmitter.prototype.clone = function () {
  61585. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61586. BABYLON.Tools.DeepCopy(this, newOne);
  61587. return newOne;
  61588. };
  61589. /**
  61590. * Called by the GPUParticleSystem to setup the update shader
  61591. * @param effect defines the update shader
  61592. */
  61593. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61594. effect.setFloat2("radius", this._radius, this.radiusRange);
  61595. effect.setFloat("coneAngle", this._angle);
  61596. effect.setFloat2("height", this._height, this.heightRange);
  61597. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61598. };
  61599. /**
  61600. * Returns a string to use to update the GPU particles update shader
  61601. * @returns a string containng the defines string
  61602. */
  61603. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61604. var defines = "#define CONEEMITTER";
  61605. if (this.emitFromSpawnPointOnly) {
  61606. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61607. }
  61608. return defines;
  61609. };
  61610. /**
  61611. * Returns the string "ConeParticleEmitter"
  61612. * @returns a string containing the class name
  61613. */
  61614. ConeParticleEmitter.prototype.getClassName = function () {
  61615. return "ConeParticleEmitter";
  61616. };
  61617. /**
  61618. * Serializes the particle system to a JSON object.
  61619. * @returns the JSON object
  61620. */
  61621. ConeParticleEmitter.prototype.serialize = function () {
  61622. var serializationObject = {};
  61623. serializationObject.type = this.getClassName();
  61624. serializationObject.radius = this._radius;
  61625. serializationObject.angle = this._angle;
  61626. serializationObject.directionRandomizer = this.directionRandomizer;
  61627. return serializationObject;
  61628. };
  61629. /**
  61630. * Parse properties from a JSON object
  61631. * @param serializationObject defines the JSON object
  61632. */
  61633. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61634. this.radius = serializationObject.radius;
  61635. this.angle = serializationObject.angle;
  61636. this.directionRandomizer = serializationObject.directionRandomizer;
  61637. };
  61638. return ConeParticleEmitter;
  61639. }());
  61640. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61641. })(BABYLON || (BABYLON = {}));
  61642. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61643. var BABYLON;
  61644. (function (BABYLON) {
  61645. /**
  61646. * Particle emitter emitting particles from the inside of a sphere.
  61647. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61648. */
  61649. var SphereParticleEmitter = /** @class */ (function () {
  61650. /**
  61651. * Creates a new instance SphereParticleEmitter
  61652. * @param radius the radius of the emission sphere (1 by default)
  61653. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61654. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61655. */
  61656. function SphereParticleEmitter(
  61657. /**
  61658. * The radius of the emission sphere.
  61659. */
  61660. radius,
  61661. /**
  61662. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61663. */
  61664. radiusRange,
  61665. /**
  61666. * How much to randomize the particle direction [0-1].
  61667. */
  61668. directionRandomizer) {
  61669. if (radius === void 0) { radius = 1; }
  61670. if (radiusRange === void 0) { radiusRange = 1; }
  61671. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61672. this.radius = radius;
  61673. this.radiusRange = radiusRange;
  61674. this.directionRandomizer = directionRandomizer;
  61675. }
  61676. /**
  61677. * Called by the particle System when the direction is computed for the created particle.
  61678. * @param worldMatrix is the world matrix of the particle system
  61679. * @param directionToUpdate is the direction vector to update with the result
  61680. * @param particle is the particle we are computed the direction for
  61681. */
  61682. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61683. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61684. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61685. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61686. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61687. direction.x += randX;
  61688. direction.y += randY;
  61689. direction.z += randZ;
  61690. direction.normalize();
  61691. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61692. };
  61693. /**
  61694. * Called by the particle System when the position is computed for the created particle.
  61695. * @param worldMatrix is the world matrix of the particle system
  61696. * @param positionToUpdate is the position vector to update with the result
  61697. * @param particle is the particle we are computed the position for
  61698. */
  61699. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61700. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61701. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61702. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61703. var theta = Math.acos(2 * v - 1);
  61704. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61705. var randY = randRadius * Math.cos(theta);
  61706. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61707. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61708. };
  61709. /**
  61710. * Clones the current emitter and returns a copy of it
  61711. * @returns the new emitter
  61712. */
  61713. SphereParticleEmitter.prototype.clone = function () {
  61714. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61715. BABYLON.Tools.DeepCopy(this, newOne);
  61716. return newOne;
  61717. };
  61718. /**
  61719. * Called by the GPUParticleSystem to setup the update shader
  61720. * @param effect defines the update shader
  61721. */
  61722. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61723. effect.setFloat("radius", this.radius);
  61724. effect.setFloat("radiusRange", this.radiusRange);
  61725. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61726. };
  61727. /**
  61728. * Returns a string to use to update the GPU particles update shader
  61729. * @returns a string containng the defines string
  61730. */
  61731. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61732. return "#define SPHEREEMITTER";
  61733. };
  61734. /**
  61735. * Returns the string "SphereParticleEmitter"
  61736. * @returns a string containing the class name
  61737. */
  61738. SphereParticleEmitter.prototype.getClassName = function () {
  61739. return "SphereParticleEmitter";
  61740. };
  61741. /**
  61742. * Serializes the particle system to a JSON object.
  61743. * @returns the JSON object
  61744. */
  61745. SphereParticleEmitter.prototype.serialize = function () {
  61746. var serializationObject = {};
  61747. serializationObject.type = this.getClassName();
  61748. serializationObject.radius = this.radius;
  61749. serializationObject.radiusRange = this.radiusRange;
  61750. serializationObject.directionRandomizer = this.directionRandomizer;
  61751. return serializationObject;
  61752. };
  61753. /**
  61754. * Parse properties from a JSON object
  61755. * @param serializationObject defines the JSON object
  61756. */
  61757. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61758. this.radius = serializationObject.radius;
  61759. this.radiusRange = serializationObject.radiusRange;
  61760. this.directionRandomizer = serializationObject.directionRandomizer;
  61761. };
  61762. return SphereParticleEmitter;
  61763. }());
  61764. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61765. /**
  61766. * Particle emitter emitting particles from the inside of a sphere.
  61767. * It emits the particles randomly between two vectors.
  61768. */
  61769. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61770. __extends(SphereDirectedParticleEmitter, _super);
  61771. /**
  61772. * Creates a new instance SphereDirectedParticleEmitter
  61773. * @param radius the radius of the emission sphere (1 by default)
  61774. * @param direction1 the min limit of the emission direction (up vector by default)
  61775. * @param direction2 the max limit of the emission direction (up vector by default)
  61776. */
  61777. function SphereDirectedParticleEmitter(radius,
  61778. /**
  61779. * The min limit of the emission direction.
  61780. */
  61781. direction1,
  61782. /**
  61783. * The max limit of the emission direction.
  61784. */
  61785. direction2) {
  61786. if (radius === void 0) { radius = 1; }
  61787. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61788. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61789. var _this = _super.call(this, radius) || this;
  61790. _this.direction1 = direction1;
  61791. _this.direction2 = direction2;
  61792. return _this;
  61793. }
  61794. /**
  61795. * Called by the particle System when the direction is computed for the created particle.
  61796. * @param worldMatrix is the world matrix of the particle system
  61797. * @param directionToUpdate is the direction vector to update with the result
  61798. * @param particle is the particle we are computed the direction for
  61799. */
  61800. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61801. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61802. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61803. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61804. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61805. };
  61806. /**
  61807. * Clones the current emitter and returns a copy of it
  61808. * @returns the new emitter
  61809. */
  61810. SphereDirectedParticleEmitter.prototype.clone = function () {
  61811. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61812. BABYLON.Tools.DeepCopy(this, newOne);
  61813. return newOne;
  61814. };
  61815. /**
  61816. * Called by the GPUParticleSystem to setup the update shader
  61817. * @param effect defines the update shader
  61818. */
  61819. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61820. effect.setFloat("radius", this.radius);
  61821. effect.setFloat("radiusRange", this.radiusRange);
  61822. effect.setVector3("direction1", this.direction1);
  61823. effect.setVector3("direction2", this.direction2);
  61824. };
  61825. /**
  61826. * Returns a string to use to update the GPU particles update shader
  61827. * @returns a string containng the defines string
  61828. */
  61829. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61830. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61831. };
  61832. /**
  61833. * Returns the string "SphereDirectedParticleEmitter"
  61834. * @returns a string containing the class name
  61835. */
  61836. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61837. return "SphereDirectedParticleEmitter";
  61838. };
  61839. /**
  61840. * Serializes the particle system to a JSON object.
  61841. * @returns the JSON object
  61842. */
  61843. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61844. var serializationObject = _super.prototype.serialize.call(this);
  61845. serializationObject.direction1 = this.direction1.asArray();
  61846. serializationObject.direction2 = this.direction2.asArray();
  61847. return serializationObject;
  61848. };
  61849. /**
  61850. * Parse properties from a JSON object
  61851. * @param serializationObject defines the JSON object
  61852. */
  61853. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61854. _super.prototype.parse.call(this, serializationObject);
  61855. this.direction1.copyFrom(serializationObject.direction1);
  61856. this.direction2.copyFrom(serializationObject.direction2);
  61857. };
  61858. return SphereDirectedParticleEmitter;
  61859. }(SphereParticleEmitter));
  61860. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61861. })(BABYLON || (BABYLON = {}));
  61862. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61863. var BABYLON;
  61864. (function (BABYLON) {
  61865. /**
  61866. * Particle emitter emitting particles from the inside of a hemisphere.
  61867. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61868. */
  61869. var HemisphericParticleEmitter = /** @class */ (function () {
  61870. /**
  61871. * Creates a new instance HemisphericParticleEmitter
  61872. * @param radius the radius of the emission hemisphere (1 by default)
  61873. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61874. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61875. */
  61876. function HemisphericParticleEmitter(
  61877. /**
  61878. * The radius of the emission hemisphere.
  61879. */
  61880. radius,
  61881. /**
  61882. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61883. */
  61884. radiusRange,
  61885. /**
  61886. * How much to randomize the particle direction [0-1].
  61887. */
  61888. directionRandomizer) {
  61889. if (radius === void 0) { radius = 1; }
  61890. if (radiusRange === void 0) { radiusRange = 1; }
  61891. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61892. this.radius = radius;
  61893. this.radiusRange = radiusRange;
  61894. this.directionRandomizer = directionRandomizer;
  61895. }
  61896. /**
  61897. * Called by the particle System when the direction is computed for the created particle.
  61898. * @param worldMatrix is the world matrix of the particle system
  61899. * @param directionToUpdate is the direction vector to update with the result
  61900. * @param particle is the particle we are computed the direction for
  61901. */
  61902. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61903. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61904. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61905. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61906. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61907. direction.x += randX;
  61908. direction.y += randY;
  61909. direction.z += randZ;
  61910. direction.normalize();
  61911. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61912. };
  61913. /**
  61914. * Called by the particle System when the position is computed for the created particle.
  61915. * @param worldMatrix is the world matrix of the particle system
  61916. * @param positionToUpdate is the position vector to update with the result
  61917. * @param particle is the particle we are computed the position for
  61918. */
  61919. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61920. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61921. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61922. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61923. var theta = Math.acos(2 * v - 1);
  61924. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61925. var randY = randRadius * Math.cos(theta);
  61926. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61927. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61928. };
  61929. /**
  61930. * Clones the current emitter and returns a copy of it
  61931. * @returns the new emitter
  61932. */
  61933. HemisphericParticleEmitter.prototype.clone = function () {
  61934. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61935. BABYLON.Tools.DeepCopy(this, newOne);
  61936. return newOne;
  61937. };
  61938. /**
  61939. * Called by the GPUParticleSystem to setup the update shader
  61940. * @param effect defines the update shader
  61941. */
  61942. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61943. effect.setFloat("radius", this.radius);
  61944. effect.setFloat("radiusRange", this.radiusRange);
  61945. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61946. };
  61947. /**
  61948. * Returns a string to use to update the GPU particles update shader
  61949. * @returns a string containng the defines string
  61950. */
  61951. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61952. return "#define HEMISPHERICEMITTER";
  61953. };
  61954. /**
  61955. * Returns the string "HemisphericParticleEmitter"
  61956. * @returns a string containing the class name
  61957. */
  61958. HemisphericParticleEmitter.prototype.getClassName = function () {
  61959. return "HemisphericParticleEmitter";
  61960. };
  61961. /**
  61962. * Serializes the particle system to a JSON object.
  61963. * @returns the JSON object
  61964. */
  61965. HemisphericParticleEmitter.prototype.serialize = function () {
  61966. var serializationObject = {};
  61967. serializationObject.type = this.getClassName();
  61968. serializationObject.radius = this.radius;
  61969. serializationObject.radiusRange = this.radiusRange;
  61970. serializationObject.directionRandomizer = this.directionRandomizer;
  61971. return serializationObject;
  61972. };
  61973. /**
  61974. * Parse properties from a JSON object
  61975. * @param serializationObject defines the JSON object
  61976. */
  61977. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  61978. this.radius = serializationObject.radius;
  61979. this.radiusRange = serializationObject.radiusRange;
  61980. this.directionRandomizer = serializationObject.directionRandomizer;
  61981. };
  61982. return HemisphericParticleEmitter;
  61983. }());
  61984. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  61985. })(BABYLON || (BABYLON = {}));
  61986. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  61987. var BABYLON;
  61988. (function (BABYLON) {
  61989. /**
  61990. * Particle emitter emitting particles from a point.
  61991. * It emits the particles randomly between 2 given directions.
  61992. */
  61993. var PointParticleEmitter = /** @class */ (function () {
  61994. /**
  61995. * Creates a new instance PointParticleEmitter
  61996. */
  61997. function PointParticleEmitter() {
  61998. /**
  61999. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62000. */
  62001. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62002. /**
  62003. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62004. */
  62005. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62006. }
  62007. /**
  62008. * Called by the particle System when the direction is computed for the created particle.
  62009. * @param worldMatrix is the world matrix of the particle system
  62010. * @param directionToUpdate is the direction vector to update with the result
  62011. * @param particle is the particle we are computed the direction for
  62012. */
  62013. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62014. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62015. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62016. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62017. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62018. };
  62019. /**
  62020. * Called by the particle System when the position is computed for the created particle.
  62021. * @param worldMatrix is the world matrix of the particle system
  62022. * @param positionToUpdate is the position vector to update with the result
  62023. * @param particle is the particle we are computed the position for
  62024. */
  62025. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62027. };
  62028. /**
  62029. * Clones the current emitter and returns a copy of it
  62030. * @returns the new emitter
  62031. */
  62032. PointParticleEmitter.prototype.clone = function () {
  62033. var newOne = new PointParticleEmitter();
  62034. BABYLON.Tools.DeepCopy(this, newOne);
  62035. return newOne;
  62036. };
  62037. /**
  62038. * Called by the GPUParticleSystem to setup the update shader
  62039. * @param effect defines the update shader
  62040. */
  62041. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62042. effect.setVector3("direction1", this.direction1);
  62043. effect.setVector3("direction2", this.direction2);
  62044. };
  62045. /**
  62046. * Returns a string to use to update the GPU particles update shader
  62047. * @returns a string containng the defines string
  62048. */
  62049. PointParticleEmitter.prototype.getEffectDefines = function () {
  62050. return "#define POINTEMITTER";
  62051. };
  62052. /**
  62053. * Returns the string "PointParticleEmitter"
  62054. * @returns a string containing the class name
  62055. */
  62056. PointParticleEmitter.prototype.getClassName = function () {
  62057. return "PointParticleEmitter";
  62058. };
  62059. /**
  62060. * Serializes the particle system to a JSON object.
  62061. * @returns the JSON object
  62062. */
  62063. PointParticleEmitter.prototype.serialize = function () {
  62064. var serializationObject = {};
  62065. serializationObject.type = this.getClassName();
  62066. serializationObject.direction1 = this.direction1.asArray();
  62067. serializationObject.direction2 = this.direction2.asArray();
  62068. return serializationObject;
  62069. };
  62070. /**
  62071. * Parse properties from a JSON object
  62072. * @param serializationObject defines the JSON object
  62073. */
  62074. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62075. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62076. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62077. };
  62078. return PointParticleEmitter;
  62079. }());
  62080. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62081. })(BABYLON || (BABYLON = {}));
  62082. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62083. var BABYLON;
  62084. (function (BABYLON) {
  62085. // Adds the parsers to the scene parsers.
  62086. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62087. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62088. if (!individualParser) {
  62089. return;
  62090. }
  62091. // Particles Systems
  62092. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62093. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62094. var parsedParticleSystem = parsedData.particleSystems[index];
  62095. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62096. }
  62097. }
  62098. });
  62099. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62100. if (parsedParticleSystem.activeParticleCount) {
  62101. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62102. return ps;
  62103. }
  62104. else {
  62105. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62106. return ps;
  62107. }
  62108. });
  62109. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62110. if (uniformsNames === void 0) { uniformsNames = []; }
  62111. if (samplers === void 0) { samplers = []; }
  62112. if (defines === void 0) { defines = ""; }
  62113. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62114. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62115. if (defines.indexOf(" BILLBOARD") === -1) {
  62116. defines += "\n#define BILLBOARD\n";
  62117. }
  62118. if (samplers.indexOf("diffuseSampler") === -1) {
  62119. samplers.push("diffuseSampler");
  62120. }
  62121. return this.createEffect({
  62122. vertex: "particles",
  62123. fragmentElement: fragmentName
  62124. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62125. };
  62126. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62127. var results = new Array();
  62128. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62129. var particleSystem = this.getScene().particleSystems[index];
  62130. if (particleSystem.emitter === this) {
  62131. results.push(particleSystem);
  62132. }
  62133. }
  62134. return results;
  62135. };
  62136. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62137. var results = new Array();
  62138. var descendants = this.getDescendants();
  62139. descendants.push(this);
  62140. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62141. var particleSystem = this.getScene().particleSystems[index];
  62142. var emitter = particleSystem.emitter;
  62143. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62144. results.push(particleSystem);
  62145. }
  62146. }
  62147. return results;
  62148. };
  62149. })(BABYLON || (BABYLON = {}));
  62150. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62151. var BABYLON;
  62152. (function (BABYLON) {
  62153. /**
  62154. * Type of sub emitter
  62155. */
  62156. var SubEmitterType;
  62157. (function (SubEmitterType) {
  62158. /**
  62159. * Attached to the particle over it's lifetime
  62160. */
  62161. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62162. /**
  62163. * Created when the particle dies
  62164. */
  62165. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62166. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62167. /**
  62168. * Sub emitter class used to emit particles from an existing particle
  62169. */
  62170. var SubEmitter = /** @class */ (function () {
  62171. /**
  62172. * Creates a sub emitter
  62173. * @param particleSystem the particle system to be used by the sub emitter
  62174. */
  62175. function SubEmitter(
  62176. /**
  62177. * the particle system to be used by the sub emitter
  62178. */
  62179. particleSystem) {
  62180. this.particleSystem = particleSystem;
  62181. /**
  62182. * Type of the submitter (Default: END)
  62183. */
  62184. this.type = SubEmitterType.END;
  62185. /**
  62186. * 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)
  62187. * Note: This only is supported when using an emitter of type Mesh
  62188. */
  62189. this.inheritDirection = false;
  62190. /**
  62191. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62192. */
  62193. this.inheritedVelocityAmount = 0;
  62194. // Create mesh as emitter to support rotation
  62195. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  62196. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  62197. }
  62198. // Automatically dispose of subemitter when system is disposed
  62199. particleSystem.onDisposeObservable.add(function () {
  62200. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  62201. particleSystem.emitter.dispose();
  62202. }
  62203. });
  62204. }
  62205. /**
  62206. * Clones the sub emitter
  62207. * @returns the cloned sub emitter
  62208. */
  62209. SubEmitter.prototype.clone = function () {
  62210. // Clone particle system
  62211. var emitter = this.particleSystem.emitter;
  62212. if (!emitter) {
  62213. emitter = new BABYLON.Vector3();
  62214. }
  62215. else if (emitter instanceof BABYLON.Vector3) {
  62216. emitter = emitter.clone();
  62217. }
  62218. else if (emitter instanceof BABYLON.AbstractMesh) {
  62219. emitter = new BABYLON.Mesh("", emitter.getScene());
  62220. emitter.isVisible = false;
  62221. }
  62222. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62223. // Clone properties
  62224. clone.type = this.type;
  62225. clone.inheritDirection = this.inheritDirection;
  62226. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62227. clone.particleSystem._disposeEmitterOnDispose = true;
  62228. clone.particleSystem.disposeOnStop = true;
  62229. return clone;
  62230. };
  62231. /**
  62232. * Serialize current object to a JSON object
  62233. * @returns the serialized object
  62234. */
  62235. SubEmitter.prototype.serialize = function () {
  62236. var serializationObject = {};
  62237. serializationObject.type = this.type;
  62238. serializationObject.inheritDirection = this.inheritDirection;
  62239. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62240. serializationObject.particleSystem = this.particleSystem.serialize();
  62241. return serializationObject;
  62242. };
  62243. /**
  62244. * Creates a new SubEmitter from a serialized JSON version
  62245. * @param serializationObject defines the JSON object to read from
  62246. * @param scene defines the hosting scene
  62247. * @param rootUrl defines the rootUrl for data loading
  62248. * @returns a new SubEmitter
  62249. */
  62250. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62251. var system = serializationObject.particleSystem;
  62252. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62253. subEmitter.type = serializationObject.type;
  62254. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62255. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62256. subEmitter.particleSystem._isSubEmitter = true;
  62257. return subEmitter;
  62258. };
  62259. /** Release associated resources */
  62260. SubEmitter.prototype.dispose = function () {
  62261. this.particleSystem.dispose();
  62262. };
  62263. return SubEmitter;
  62264. }());
  62265. BABYLON.SubEmitter = SubEmitter;
  62266. })(BABYLON || (BABYLON = {}));
  62267. //# sourceMappingURL=babylon.subEmitter.js.map
  62268. var BABYLON;
  62269. (function (BABYLON) {
  62270. /**
  62271. * 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.
  62272. *
  62273. * This returned material effects how the mesh will look based on the code in the shaders.
  62274. *
  62275. * @see http://doc.babylonjs.com/how_to/shader_material
  62276. */
  62277. var ShaderMaterial = /** @class */ (function (_super) {
  62278. __extends(ShaderMaterial, _super);
  62279. /**
  62280. * Instantiate a new shader material.
  62281. * 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.
  62282. * This returned material effects how the mesh will look based on the code in the shaders.
  62283. * @see http://doc.babylonjs.com/how_to/shader_material
  62284. * @param name Define the name of the material in the scene
  62285. * @param scene Define the scene the material belongs to
  62286. * @param shaderPath Defines the route to the shader code in one of three ways:
  62287. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62288. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62289. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62290. * @param options Define the options used to create the shader
  62291. */
  62292. function ShaderMaterial(name, scene, shaderPath, options) {
  62293. if (options === void 0) { options = {}; }
  62294. var _this = _super.call(this, name, scene) || this;
  62295. _this._textures = {};
  62296. _this._textureArrays = {};
  62297. _this._floats = {};
  62298. _this._ints = {};
  62299. _this._floatsArrays = {};
  62300. _this._colors3 = {};
  62301. _this._colors3Arrays = {};
  62302. _this._colors4 = {};
  62303. _this._vectors2 = {};
  62304. _this._vectors3 = {};
  62305. _this._vectors4 = {};
  62306. _this._matrices = {};
  62307. _this._matrices3x3 = {};
  62308. _this._matrices2x2 = {};
  62309. _this._vectors2Arrays = {};
  62310. _this._vectors3Arrays = {};
  62311. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62312. _this._shaderPath = shaderPath;
  62313. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62314. return _this;
  62315. }
  62316. /**
  62317. * Gets the current class name of the material e.g. "ShaderMaterial"
  62318. * Mainly use in serialization.
  62319. * @returns the class name
  62320. */
  62321. ShaderMaterial.prototype.getClassName = function () {
  62322. return "ShaderMaterial";
  62323. };
  62324. /**
  62325. * Specifies if the material will require alpha blending
  62326. * @returns a boolean specifying if alpha blending is needed
  62327. */
  62328. ShaderMaterial.prototype.needAlphaBlending = function () {
  62329. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62330. };
  62331. /**
  62332. * Specifies if this material should be rendered in alpha test mode
  62333. * @returns a boolean specifying if an alpha test is needed.
  62334. */
  62335. ShaderMaterial.prototype.needAlphaTesting = function () {
  62336. return this._options.needAlphaTesting;
  62337. };
  62338. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62339. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62340. this._options.uniforms.push(uniformName);
  62341. }
  62342. };
  62343. /**
  62344. * Set a texture in the shader.
  62345. * @param name Define the name of the uniform samplers as defined in the shader
  62346. * @param texture Define the texture to bind to this sampler
  62347. * @return the material itself allowing "fluent" like uniform updates
  62348. */
  62349. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62350. if (this._options.samplers.indexOf(name) === -1) {
  62351. this._options.samplers.push(name);
  62352. }
  62353. this._textures[name] = texture;
  62354. return this;
  62355. };
  62356. /**
  62357. * Set a texture array in the shader.
  62358. * @param name Define the name of the uniform sampler array as defined in the shader
  62359. * @param textures Define the list of textures to bind to this sampler
  62360. * @return the material itself allowing "fluent" like uniform updates
  62361. */
  62362. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62363. if (this._options.samplers.indexOf(name) === -1) {
  62364. this._options.samplers.push(name);
  62365. }
  62366. this._checkUniform(name);
  62367. this._textureArrays[name] = textures;
  62368. return this;
  62369. };
  62370. /**
  62371. * Set a float in the shader.
  62372. * @param name Define the name of the uniform as defined in the shader
  62373. * @param value Define the value to give to the uniform
  62374. * @return the material itself allowing "fluent" like uniform updates
  62375. */
  62376. ShaderMaterial.prototype.setFloat = function (name, value) {
  62377. this._checkUniform(name);
  62378. this._floats[name] = value;
  62379. return this;
  62380. };
  62381. /**
  62382. * Set a int in the shader.
  62383. * @param name Define the name of the uniform as defined in the shader
  62384. * @param value Define the value to give to the uniform
  62385. * @return the material itself allowing "fluent" like uniform updates
  62386. */
  62387. ShaderMaterial.prototype.setInt = function (name, value) {
  62388. this._checkUniform(name);
  62389. this._ints[name] = value;
  62390. return this;
  62391. };
  62392. /**
  62393. * Set an array of floats in the shader.
  62394. * @param name Define the name of the uniform as defined in the shader
  62395. * @param value Define the value to give to the uniform
  62396. * @return the material itself allowing "fluent" like uniform updates
  62397. */
  62398. ShaderMaterial.prototype.setFloats = function (name, value) {
  62399. this._checkUniform(name);
  62400. this._floatsArrays[name] = value;
  62401. return this;
  62402. };
  62403. /**
  62404. * Set a vec3 in the shader from a Color3.
  62405. * @param name Define the name of the uniform as defined in the shader
  62406. * @param value Define the value to give to the uniform
  62407. * @return the material itself allowing "fluent" like uniform updates
  62408. */
  62409. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62410. this._checkUniform(name);
  62411. this._colors3[name] = value;
  62412. return this;
  62413. };
  62414. /**
  62415. * Set a vec3 array in the shader from a Color3 array.
  62416. * @param name Define the name of the uniform as defined in the shader
  62417. * @param value Define the value to give to the uniform
  62418. * @return the material itself allowing "fluent" like uniform updates
  62419. */
  62420. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62421. this._checkUniform(name);
  62422. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62423. color.toArray(arr, arr.length);
  62424. return arr;
  62425. }, []);
  62426. return this;
  62427. };
  62428. /**
  62429. * Set a vec4 in the shader from a Color4.
  62430. * @param name Define the name of the uniform as defined in the shader
  62431. * @param value Define the value to give to the uniform
  62432. * @return the material itself allowing "fluent" like uniform updates
  62433. */
  62434. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62435. this._checkUniform(name);
  62436. this._colors4[name] = value;
  62437. return this;
  62438. };
  62439. /**
  62440. * Set a vec2 in the shader from a Vector2.
  62441. * @param name Define the name of the uniform as defined in the shader
  62442. * @param value Define the value to give to the uniform
  62443. * @return the material itself allowing "fluent" like uniform updates
  62444. */
  62445. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62446. this._checkUniform(name);
  62447. this._vectors2[name] = value;
  62448. return this;
  62449. };
  62450. /**
  62451. * Set a vec3 in the shader from a Vector3.
  62452. * @param name Define the name of the uniform as defined in the shader
  62453. * @param value Define the value to give to the uniform
  62454. * @return the material itself allowing "fluent" like uniform updates
  62455. */
  62456. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62457. this._checkUniform(name);
  62458. this._vectors3[name] = value;
  62459. return this;
  62460. };
  62461. /**
  62462. * Set a vec4 in the shader from a Vector4.
  62463. * @param name Define the name of the uniform as defined in the shader
  62464. * @param value Define the value to give to the uniform
  62465. * @return the material itself allowing "fluent" like uniform updates
  62466. */
  62467. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62468. this._checkUniform(name);
  62469. this._vectors4[name] = value;
  62470. return this;
  62471. };
  62472. /**
  62473. * Set a mat4 in the shader from a Matrix.
  62474. * @param name Define the name of the uniform as defined in the shader
  62475. * @param value Define the value to give to the uniform
  62476. * @return the material itself allowing "fluent" like uniform updates
  62477. */
  62478. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62479. this._checkUniform(name);
  62480. this._matrices[name] = value;
  62481. return this;
  62482. };
  62483. /**
  62484. * Set a mat3 in the shader from a Float32Array.
  62485. * @param name Define the name of the uniform as defined in the shader
  62486. * @param value Define the value to give to the uniform
  62487. * @return the material itself allowing "fluent" like uniform updates
  62488. */
  62489. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62490. this._checkUniform(name);
  62491. this._matrices3x3[name] = value;
  62492. return this;
  62493. };
  62494. /**
  62495. * Set a mat2 in the shader from a Float32Array.
  62496. * @param name Define the name of the uniform as defined in the shader
  62497. * @param value Define the value to give to the uniform
  62498. * @return the material itself allowing "fluent" like uniform updates
  62499. */
  62500. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62501. this._checkUniform(name);
  62502. this._matrices2x2[name] = value;
  62503. return this;
  62504. };
  62505. /**
  62506. * Set a vec2 array in the shader from a number array.
  62507. * @param name Define the name of the uniform as defined in the shader
  62508. * @param value Define the value to give to the uniform
  62509. * @return the material itself allowing "fluent" like uniform updates
  62510. */
  62511. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62512. this._checkUniform(name);
  62513. this._vectors2Arrays[name] = value;
  62514. return this;
  62515. };
  62516. /**
  62517. * Set a vec3 array in the shader from a number array.
  62518. * @param name Define the name of the uniform as defined in the shader
  62519. * @param value Define the value to give to the uniform
  62520. * @return the material itself allowing "fluent" like uniform updates
  62521. */
  62522. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62523. this._checkUniform(name);
  62524. this._vectors3Arrays[name] = value;
  62525. return this;
  62526. };
  62527. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62528. if (!mesh) {
  62529. return true;
  62530. }
  62531. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62532. return false;
  62533. }
  62534. return false;
  62535. };
  62536. /**
  62537. * Checks if the material is ready to render the requested mesh
  62538. * @param mesh Define the mesh to render
  62539. * @param useInstances Define whether or not the material is used with instances
  62540. * @returns true if ready, otherwise false
  62541. */
  62542. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62543. var scene = this.getScene();
  62544. var engine = scene.getEngine();
  62545. if (!this.checkReadyOnEveryCall) {
  62546. if (this._renderId === scene.getRenderId()) {
  62547. if (this._checkCache(scene, mesh, useInstances)) {
  62548. return true;
  62549. }
  62550. }
  62551. }
  62552. // Instances
  62553. var defines = [];
  62554. var attribs = [];
  62555. var fallbacks = new BABYLON.EffectFallbacks();
  62556. for (var index = 0; index < this._options.defines.length; index++) {
  62557. defines.push(this._options.defines[index]);
  62558. }
  62559. for (var index = 0; index < this._options.attributes.length; index++) {
  62560. attribs.push(this._options.attributes[index]);
  62561. }
  62562. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62563. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62564. defines.push("#define VERTEXCOLOR");
  62565. }
  62566. if (useInstances) {
  62567. defines.push("#define INSTANCES");
  62568. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62569. }
  62570. // Bones
  62571. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62572. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62573. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62574. if (mesh.numBoneInfluencers > 4) {
  62575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62577. }
  62578. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62579. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62580. fallbacks.addCPUSkinningFallback(0, mesh);
  62581. if (this._options.uniforms.indexOf("mBones") === -1) {
  62582. this._options.uniforms.push("mBones");
  62583. }
  62584. }
  62585. else {
  62586. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62587. }
  62588. // Textures
  62589. for (var name in this._textures) {
  62590. if (!this._textures[name].isReady()) {
  62591. return false;
  62592. }
  62593. }
  62594. // Alpha test
  62595. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62596. defines.push("#define ALPHATEST");
  62597. }
  62598. var previousEffect = this._effect;
  62599. var join = defines.join("\n");
  62600. this._effect = engine.createEffect(this._shaderPath, {
  62601. attributes: attribs,
  62602. uniformsNames: this._options.uniforms,
  62603. uniformBuffersNames: this._options.uniformBuffers,
  62604. samplers: this._options.samplers,
  62605. defines: join,
  62606. fallbacks: fallbacks,
  62607. onCompiled: this.onCompiled,
  62608. onError: this.onError
  62609. }, engine);
  62610. if (!this._effect.isReady()) {
  62611. return false;
  62612. }
  62613. if (previousEffect !== this._effect) {
  62614. scene.resetCachedMaterial();
  62615. }
  62616. this._renderId = scene.getRenderId();
  62617. return true;
  62618. };
  62619. /**
  62620. * Binds the world matrix to the material
  62621. * @param world defines the world transformation matrix
  62622. */
  62623. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62624. var scene = this.getScene();
  62625. if (!this._effect) {
  62626. return;
  62627. }
  62628. if (this._options.uniforms.indexOf("world") !== -1) {
  62629. this._effect.setMatrix("world", world);
  62630. }
  62631. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62632. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62633. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62634. }
  62635. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62636. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62637. }
  62638. };
  62639. /**
  62640. * Binds the material to the mesh
  62641. * @param world defines the world transformation matrix
  62642. * @param mesh defines the mesh to bind the material to
  62643. */
  62644. ShaderMaterial.prototype.bind = function (world, mesh) {
  62645. // Std values
  62646. this.bindOnlyWorldMatrix(world);
  62647. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62648. if (this._options.uniforms.indexOf("view") !== -1) {
  62649. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62650. }
  62651. if (this._options.uniforms.indexOf("projection") !== -1) {
  62652. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62653. }
  62654. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62655. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62656. }
  62657. // Bones
  62658. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62659. var name;
  62660. // Texture
  62661. for (name in this._textures) {
  62662. this._effect.setTexture(name, this._textures[name]);
  62663. }
  62664. // Texture arrays
  62665. for (name in this._textureArrays) {
  62666. this._effect.setTextureArray(name, this._textureArrays[name]);
  62667. }
  62668. // Int
  62669. for (name in this._ints) {
  62670. this._effect.setInt(name, this._ints[name]);
  62671. }
  62672. // Float
  62673. for (name in this._floats) {
  62674. this._effect.setFloat(name, this._floats[name]);
  62675. }
  62676. // Floats
  62677. for (name in this._floatsArrays) {
  62678. this._effect.setArray(name, this._floatsArrays[name]);
  62679. }
  62680. // Color3
  62681. for (name in this._colors3) {
  62682. this._effect.setColor3(name, this._colors3[name]);
  62683. }
  62684. for (name in this._colors3Arrays) {
  62685. this._effect.setArray3(name, this._colors3Arrays[name]);
  62686. }
  62687. // Color4
  62688. for (name in this._colors4) {
  62689. var color = this._colors4[name];
  62690. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62691. }
  62692. // Vector2
  62693. for (name in this._vectors2) {
  62694. this._effect.setVector2(name, this._vectors2[name]);
  62695. }
  62696. // Vector3
  62697. for (name in this._vectors3) {
  62698. this._effect.setVector3(name, this._vectors3[name]);
  62699. }
  62700. // Vector4
  62701. for (name in this._vectors4) {
  62702. this._effect.setVector4(name, this._vectors4[name]);
  62703. }
  62704. // Matrix
  62705. for (name in this._matrices) {
  62706. this._effect.setMatrix(name, this._matrices[name]);
  62707. }
  62708. // Matrix 3x3
  62709. for (name in this._matrices3x3) {
  62710. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62711. }
  62712. // Matrix 2x2
  62713. for (name in this._matrices2x2) {
  62714. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62715. }
  62716. // Vector2Array
  62717. for (name in this._vectors2Arrays) {
  62718. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62719. }
  62720. // Vector3Array
  62721. for (name in this._vectors3Arrays) {
  62722. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62723. }
  62724. }
  62725. this._afterBind(mesh);
  62726. };
  62727. /**
  62728. * Gets the active textures from the material
  62729. * @returns an array of textures
  62730. */
  62731. ShaderMaterial.prototype.getActiveTextures = function () {
  62732. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62733. for (var name in this._textures) {
  62734. activeTextures.push(this._textures[name]);
  62735. }
  62736. for (var name in this._textureArrays) {
  62737. var array = this._textureArrays[name];
  62738. for (var index = 0; index < array.length; index++) {
  62739. activeTextures.push(array[index]);
  62740. }
  62741. }
  62742. return activeTextures;
  62743. };
  62744. /**
  62745. * Specifies if the material uses a texture
  62746. * @param texture defines the texture to check against the material
  62747. * @returns a boolean specifying if the material uses the texture
  62748. */
  62749. ShaderMaterial.prototype.hasTexture = function (texture) {
  62750. if (_super.prototype.hasTexture.call(this, texture)) {
  62751. return true;
  62752. }
  62753. for (var name in this._textures) {
  62754. if (this._textures[name] === texture) {
  62755. return true;
  62756. }
  62757. }
  62758. for (var name in this._textureArrays) {
  62759. var array = this._textureArrays[name];
  62760. for (var index = 0; index < array.length; index++) {
  62761. if (array[index] === texture) {
  62762. return true;
  62763. }
  62764. }
  62765. }
  62766. return false;
  62767. };
  62768. /**
  62769. * Makes a duplicate of the material, and gives it a new name
  62770. * @param name defines the new name for the duplicated material
  62771. * @returns the cloned material
  62772. */
  62773. ShaderMaterial.prototype.clone = function (name) {
  62774. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62775. return newShaderMaterial;
  62776. };
  62777. /**
  62778. * Disposes the material
  62779. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62780. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62781. */
  62782. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62783. if (forceDisposeTextures) {
  62784. var name;
  62785. for (name in this._textures) {
  62786. this._textures[name].dispose();
  62787. }
  62788. for (name in this._textureArrays) {
  62789. var array = this._textureArrays[name];
  62790. for (var index = 0; index < array.length; index++) {
  62791. array[index].dispose();
  62792. }
  62793. }
  62794. }
  62795. this._textures = {};
  62796. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62797. };
  62798. /**
  62799. * Serializes this material in a JSON representation
  62800. * @returns the serialized material object
  62801. */
  62802. ShaderMaterial.prototype.serialize = function () {
  62803. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62804. serializationObject.customType = "BABYLON.ShaderMaterial";
  62805. serializationObject.options = this._options;
  62806. serializationObject.shaderPath = this._shaderPath;
  62807. var name;
  62808. // Texture
  62809. serializationObject.textures = {};
  62810. for (name in this._textures) {
  62811. serializationObject.textures[name] = this._textures[name].serialize();
  62812. }
  62813. // Texture arrays
  62814. serializationObject.textureArrays = {};
  62815. for (name in this._textureArrays) {
  62816. serializationObject.textureArrays[name] = [];
  62817. var array = this._textureArrays[name];
  62818. for (var index = 0; index < array.length; index++) {
  62819. serializationObject.textureArrays[name].push(array[index].serialize());
  62820. }
  62821. }
  62822. // Float
  62823. serializationObject.floats = {};
  62824. for (name in this._floats) {
  62825. serializationObject.floats[name] = this._floats[name];
  62826. }
  62827. // Float s
  62828. serializationObject.FloatArrays = {};
  62829. for (name in this._floatsArrays) {
  62830. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62831. }
  62832. // Color3
  62833. serializationObject.colors3 = {};
  62834. for (name in this._colors3) {
  62835. serializationObject.colors3[name] = this._colors3[name].asArray();
  62836. }
  62837. // Color3 array
  62838. serializationObject.colors3Arrays = {};
  62839. for (name in this._colors3Arrays) {
  62840. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62841. }
  62842. // Color4
  62843. serializationObject.colors4 = {};
  62844. for (name in this._colors4) {
  62845. serializationObject.colors4[name] = this._colors4[name].asArray();
  62846. }
  62847. // Vector2
  62848. serializationObject.vectors2 = {};
  62849. for (name in this._vectors2) {
  62850. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62851. }
  62852. // Vector3
  62853. serializationObject.vectors3 = {};
  62854. for (name in this._vectors3) {
  62855. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62856. }
  62857. // Vector4
  62858. serializationObject.vectors4 = {};
  62859. for (name in this._vectors4) {
  62860. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62861. }
  62862. // Matrix
  62863. serializationObject.matrices = {};
  62864. for (name in this._matrices) {
  62865. serializationObject.matrices[name] = this._matrices[name].asArray();
  62866. }
  62867. // Matrix 3x3
  62868. serializationObject.matrices3x3 = {};
  62869. for (name in this._matrices3x3) {
  62870. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62871. }
  62872. // Matrix 2x2
  62873. serializationObject.matrices2x2 = {};
  62874. for (name in this._matrices2x2) {
  62875. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62876. }
  62877. // Vector2Array
  62878. serializationObject.vectors2Arrays = {};
  62879. for (name in this._vectors2Arrays) {
  62880. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62881. }
  62882. // Vector3Array
  62883. serializationObject.vectors3Arrays = {};
  62884. for (name in this._vectors3Arrays) {
  62885. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62886. }
  62887. return serializationObject;
  62888. };
  62889. /**
  62890. * Creates a shader material from parsed shader material data
  62891. * @param source defines the JSON represnetation of the material
  62892. * @param scene defines the hosting scene
  62893. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62894. * @returns a new material
  62895. */
  62896. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62897. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62898. var name;
  62899. // Texture
  62900. for (name in source.textures) {
  62901. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62902. }
  62903. // Texture arrays
  62904. for (name in source.textureArrays) {
  62905. var array = source.textureArrays[name];
  62906. var textureArray = new Array();
  62907. for (var index = 0; index < array.length; index++) {
  62908. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62909. }
  62910. material.setTextureArray(name, textureArray);
  62911. }
  62912. // Float
  62913. for (name in source.floats) {
  62914. material.setFloat(name, source.floats[name]);
  62915. }
  62916. // Float s
  62917. for (name in source.floatsArrays) {
  62918. material.setFloats(name, source.floatsArrays[name]);
  62919. }
  62920. // Color3
  62921. for (name in source.colors3) {
  62922. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62923. }
  62924. // Color3 arrays
  62925. for (name in source.colors3Arrays) {
  62926. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62927. if (i % 3 === 0) {
  62928. arr.push([num]);
  62929. }
  62930. else {
  62931. arr[arr.length - 1].push(num);
  62932. }
  62933. return arr;
  62934. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62935. material.setColor3Array(name, colors);
  62936. }
  62937. // Color4
  62938. for (name in source.colors4) {
  62939. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62940. }
  62941. // Vector2
  62942. for (name in source.vectors2) {
  62943. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62944. }
  62945. // Vector3
  62946. for (name in source.vectors3) {
  62947. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62948. }
  62949. // Vector4
  62950. for (name in source.vectors4) {
  62951. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62952. }
  62953. // Matrix
  62954. for (name in source.matrices) {
  62955. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62956. }
  62957. // Matrix 3x3
  62958. for (name in source.matrices3x3) {
  62959. material.setMatrix3x3(name, source.matrices3x3[name]);
  62960. }
  62961. // Matrix 2x2
  62962. for (name in source.matrices2x2) {
  62963. material.setMatrix2x2(name, source.matrices2x2[name]);
  62964. }
  62965. // Vector2Array
  62966. for (name in source.vectors2Arrays) {
  62967. material.setArray2(name, source.vectors2Arrays[name]);
  62968. }
  62969. // Vector3Array
  62970. for (name in source.vectors3Arrays) {
  62971. material.setArray3(name, source.vectors3Arrays[name]);
  62972. }
  62973. return material;
  62974. };
  62975. return ShaderMaterial;
  62976. }(BABYLON.Material));
  62977. BABYLON.ShaderMaterial = ShaderMaterial;
  62978. })(BABYLON || (BABYLON = {}));
  62979. //# sourceMappingURL=babylon.shaderMaterial.js.map
  62980. var BABYLON;
  62981. (function (BABYLON) {
  62982. /**
  62983. * Mesh representing the gorund
  62984. */
  62985. var GroundMesh = /** @class */ (function (_super) {
  62986. __extends(GroundMesh, _super);
  62987. function GroundMesh(name, scene) {
  62988. var _this = _super.call(this, name, scene) || this;
  62989. /** If octree should be generated */
  62990. _this.generateOctree = false;
  62991. return _this;
  62992. }
  62993. /**
  62994. * "GroundMesh"
  62995. * @returns "GroundMesh"
  62996. */
  62997. GroundMesh.prototype.getClassName = function () {
  62998. return "GroundMesh";
  62999. };
  63000. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  63001. /**
  63002. * The minimum of x and y subdivisions
  63003. */
  63004. get: function () {
  63005. return Math.min(this._subdivisionsX, this._subdivisionsY);
  63006. },
  63007. enumerable: true,
  63008. configurable: true
  63009. });
  63010. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  63011. /**
  63012. * X subdivisions
  63013. */
  63014. get: function () {
  63015. return this._subdivisionsX;
  63016. },
  63017. enumerable: true,
  63018. configurable: true
  63019. });
  63020. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  63021. /**
  63022. * Y subdivisions
  63023. */
  63024. get: function () {
  63025. return this._subdivisionsY;
  63026. },
  63027. enumerable: true,
  63028. configurable: true
  63029. });
  63030. /**
  63031. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63032. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63033. * @param chunksCount the number of subdivisions for x and y
  63034. * @param octreeBlocksSize (Default: 32)
  63035. */
  63036. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63037. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63038. this._subdivisionsX = chunksCount;
  63039. this._subdivisionsY = chunksCount;
  63040. this.subdivide(chunksCount);
  63041. // Call the octree system optimization if it is defined.
  63042. var thisAsAny = this;
  63043. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63044. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63045. }
  63046. };
  63047. /**
  63048. * Returns a height (y) value in the Worl system :
  63049. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63050. * @param x x coordinate
  63051. * @param z z coordinate
  63052. * @returns the ground y position if (x, z) are outside the ground surface.
  63053. */
  63054. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63055. var world = this.getWorldMatrix();
  63056. var invMat = BABYLON.Tmp.Matrix[5];
  63057. world.invertToRef(invMat);
  63058. var tmpVect = BABYLON.Tmp.Vector3[8];
  63059. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63060. x = tmpVect.x;
  63061. z = tmpVect.z;
  63062. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63063. return this.position.y;
  63064. }
  63065. if (!this._heightQuads || this._heightQuads.length == 0) {
  63066. this._initHeightQuads();
  63067. this._computeHeightQuads();
  63068. }
  63069. var facet = this._getFacetAt(x, z);
  63070. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63071. // return y in the World system
  63072. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63073. return tmpVect.y;
  63074. };
  63075. /**
  63076. * Returns a normalized vector (Vector3) orthogonal to the ground
  63077. * at the ground coordinates (x, z) expressed in the World system.
  63078. * @param x x coordinate
  63079. * @param z z coordinate
  63080. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63081. */
  63082. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63083. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63084. this.getNormalAtCoordinatesToRef(x, z, normal);
  63085. return normal;
  63086. };
  63087. /**
  63088. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63089. * at the ground coordinates (x, z) expressed in the World system.
  63090. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63091. * @param x x coordinate
  63092. * @param z z coordinate
  63093. * @param ref vector to store the result
  63094. * @returns the GroundMesh.
  63095. */
  63096. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63097. var world = this.getWorldMatrix();
  63098. var tmpMat = BABYLON.Tmp.Matrix[5];
  63099. world.invertToRef(tmpMat);
  63100. var tmpVect = BABYLON.Tmp.Vector3[8];
  63101. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63102. x = tmpVect.x;
  63103. z = tmpVect.z;
  63104. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63105. return this;
  63106. }
  63107. if (!this._heightQuads || this._heightQuads.length == 0) {
  63108. this._initHeightQuads();
  63109. this._computeHeightQuads();
  63110. }
  63111. var facet = this._getFacetAt(x, z);
  63112. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63113. return this;
  63114. };
  63115. /**
  63116. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63117. * if the ground has been updated.
  63118. * This can be used in the render loop.
  63119. * @returns the GroundMesh.
  63120. */
  63121. GroundMesh.prototype.updateCoordinateHeights = function () {
  63122. if (!this._heightQuads || this._heightQuads.length == 0) {
  63123. this._initHeightQuads();
  63124. }
  63125. this._computeHeightQuads();
  63126. return this;
  63127. };
  63128. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63129. GroundMesh.prototype._getFacetAt = function (x, z) {
  63130. // retrieve col and row from x, z coordinates in the ground local system
  63131. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63132. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63133. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63134. var facet;
  63135. if (z < quad.slope.x * x + quad.slope.y) {
  63136. facet = quad.facet1;
  63137. }
  63138. else {
  63139. facet = quad.facet2;
  63140. }
  63141. return facet;
  63142. };
  63143. // Creates and populates the heightMap array with "facet" elements :
  63144. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63145. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63146. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63147. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63148. // Returns the GroundMesh.
  63149. GroundMesh.prototype._initHeightQuads = function () {
  63150. var subdivisionsX = this._subdivisionsX;
  63151. var subdivisionsY = this._subdivisionsY;
  63152. this._heightQuads = new Array();
  63153. for (var row = 0; row < subdivisionsY; row++) {
  63154. for (var col = 0; col < subdivisionsX; col++) {
  63155. 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) };
  63156. this._heightQuads[row * subdivisionsX + col] = quad;
  63157. }
  63158. }
  63159. return this;
  63160. };
  63161. // Compute each quad element values and update the the heightMap array :
  63162. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63163. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63164. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63165. // Returns the GroundMesh.
  63166. GroundMesh.prototype._computeHeightQuads = function () {
  63167. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63168. if (!positions) {
  63169. return this;
  63170. }
  63171. var v1 = BABYLON.Tmp.Vector3[3];
  63172. var v2 = BABYLON.Tmp.Vector3[2];
  63173. var v3 = BABYLON.Tmp.Vector3[1];
  63174. var v4 = BABYLON.Tmp.Vector3[0];
  63175. var v1v2 = BABYLON.Tmp.Vector3[4];
  63176. var v1v3 = BABYLON.Tmp.Vector3[5];
  63177. var v1v4 = BABYLON.Tmp.Vector3[6];
  63178. var norm1 = BABYLON.Tmp.Vector3[7];
  63179. var norm2 = BABYLON.Tmp.Vector3[8];
  63180. var i = 0;
  63181. var j = 0;
  63182. var k = 0;
  63183. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63184. var h = 0;
  63185. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63186. var d2 = 0;
  63187. var subdivisionsX = this._subdivisionsX;
  63188. var subdivisionsY = this._subdivisionsY;
  63189. for (var row = 0; row < subdivisionsY; row++) {
  63190. for (var col = 0; col < subdivisionsX; col++) {
  63191. i = col * 3;
  63192. j = row * (subdivisionsX + 1) * 3;
  63193. k = (row + 1) * (subdivisionsX + 1) * 3;
  63194. v1.x = positions[j + i];
  63195. v1.y = positions[j + i + 1];
  63196. v1.z = positions[j + i + 2];
  63197. v2.x = positions[j + i + 3];
  63198. v2.y = positions[j + i + 4];
  63199. v2.z = positions[j + i + 5];
  63200. v3.x = positions[k + i];
  63201. v3.y = positions[k + i + 1];
  63202. v3.z = positions[k + i + 2];
  63203. v4.x = positions[k + i + 3];
  63204. v4.y = positions[k + i + 4];
  63205. v4.z = positions[k + i + 5];
  63206. // 2D slope V1V4
  63207. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63208. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63209. // facet equations :
  63210. // we compute each facet normal vector
  63211. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63212. // we compute the value d by applying the equation to v1 which belongs to the plane
  63213. // then we store the facet equation in a Vector4
  63214. v2.subtractToRef(v1, v1v2);
  63215. v3.subtractToRef(v1, v1v3);
  63216. v4.subtractToRef(v1, v1v4);
  63217. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63218. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63219. norm1.normalize();
  63220. norm2.normalize();
  63221. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63222. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63223. var quad = this._heightQuads[row * subdivisionsX + col];
  63224. quad.slope.copyFromFloats(cd, h);
  63225. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63226. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63227. }
  63228. }
  63229. return this;
  63230. };
  63231. /**
  63232. * Serializes this ground mesh
  63233. * @param serializationObject object to write serialization to
  63234. */
  63235. GroundMesh.prototype.serialize = function (serializationObject) {
  63236. _super.prototype.serialize.call(this, serializationObject);
  63237. serializationObject.subdivisionsX = this._subdivisionsX;
  63238. serializationObject.subdivisionsY = this._subdivisionsY;
  63239. serializationObject.minX = this._minX;
  63240. serializationObject.maxX = this._maxX;
  63241. serializationObject.minZ = this._minZ;
  63242. serializationObject.maxZ = this._maxZ;
  63243. serializationObject.width = this._width;
  63244. serializationObject.height = this._height;
  63245. };
  63246. /**
  63247. * Parses a serialized ground mesh
  63248. * @param parsedMesh the serialized mesh
  63249. * @param scene the scene to create the ground mesh in
  63250. * @returns the created ground mesh
  63251. */
  63252. GroundMesh.Parse = function (parsedMesh, scene) {
  63253. var result = new GroundMesh(parsedMesh.name, scene);
  63254. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63255. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63256. result._minX = parsedMesh.minX;
  63257. result._maxX = parsedMesh.maxX;
  63258. result._minZ = parsedMesh.minZ;
  63259. result._maxZ = parsedMesh.maxZ;
  63260. result._width = parsedMesh.width;
  63261. result._height = parsedMesh.height;
  63262. return result;
  63263. };
  63264. return GroundMesh;
  63265. }(BABYLON.Mesh));
  63266. BABYLON.GroundMesh = GroundMesh;
  63267. })(BABYLON || (BABYLON = {}));
  63268. //# sourceMappingURL=babylon.groundMesh.js.map
  63269. var BABYLON;
  63270. (function (BABYLON) {
  63271. /**
  63272. * Creates an instance based on a source mesh.
  63273. */
  63274. var InstancedMesh = /** @class */ (function (_super) {
  63275. __extends(InstancedMesh, _super);
  63276. function InstancedMesh(name, source) {
  63277. var _this = _super.call(this, name, source.getScene()) || this;
  63278. source.instances.push(_this);
  63279. _this._sourceMesh = source;
  63280. _this.position.copyFrom(source.position);
  63281. _this.rotation.copyFrom(source.rotation);
  63282. _this.scaling.copyFrom(source.scaling);
  63283. if (source.rotationQuaternion) {
  63284. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63285. }
  63286. _this.infiniteDistance = source.infiniteDistance;
  63287. _this.setPivotMatrix(source.getPivotMatrix());
  63288. _this.refreshBoundingInfo();
  63289. _this._syncSubMeshes();
  63290. return _this;
  63291. }
  63292. /**
  63293. * Returns the string "InstancedMesh".
  63294. */
  63295. InstancedMesh.prototype.getClassName = function () {
  63296. return "InstancedMesh";
  63297. };
  63298. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63299. // Methods
  63300. /**
  63301. * If the source mesh receives shadows
  63302. */
  63303. get: function () {
  63304. return this._sourceMesh.receiveShadows;
  63305. },
  63306. enumerable: true,
  63307. configurable: true
  63308. });
  63309. Object.defineProperty(InstancedMesh.prototype, "material", {
  63310. /**
  63311. * The material of the source mesh
  63312. */
  63313. get: function () {
  63314. return this._sourceMesh.material;
  63315. },
  63316. enumerable: true,
  63317. configurable: true
  63318. });
  63319. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63320. /**
  63321. * Visibility of the source mesh
  63322. */
  63323. get: function () {
  63324. return this._sourceMesh.visibility;
  63325. },
  63326. enumerable: true,
  63327. configurable: true
  63328. });
  63329. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63330. /**
  63331. * Skeleton of the source mesh
  63332. */
  63333. get: function () {
  63334. return this._sourceMesh.skeleton;
  63335. },
  63336. enumerable: true,
  63337. configurable: true
  63338. });
  63339. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63340. /**
  63341. * Rendering ground id of the source mesh
  63342. */
  63343. get: function () {
  63344. return this._sourceMesh.renderingGroupId;
  63345. },
  63346. set: function (value) {
  63347. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63348. return;
  63349. }
  63350. //no-op with warning
  63351. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63352. },
  63353. enumerable: true,
  63354. configurable: true
  63355. });
  63356. /**
  63357. * Returns the total number of vertices (integer).
  63358. */
  63359. InstancedMesh.prototype.getTotalVertices = function () {
  63360. return this._sourceMesh.getTotalVertices();
  63361. };
  63362. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63363. /**
  63364. * The source mesh of the instance
  63365. */
  63366. get: function () {
  63367. return this._sourceMesh;
  63368. },
  63369. enumerable: true,
  63370. configurable: true
  63371. });
  63372. /**
  63373. * Is this node ready to be used/rendered
  63374. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63375. * @return {boolean} is it ready
  63376. */
  63377. InstancedMesh.prototype.isReady = function (completeCheck) {
  63378. if (completeCheck === void 0) { completeCheck = false; }
  63379. return this._sourceMesh.isReady(completeCheck, true);
  63380. };
  63381. /**
  63382. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63383. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63384. * @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.
  63385. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63386. */
  63387. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63388. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63389. };
  63390. /**
  63391. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63392. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63393. * The `data` are either a numeric array either a Float32Array.
  63394. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63395. * 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).
  63396. * Note that a new underlying VertexBuffer object is created each call.
  63397. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63398. *
  63399. * Possible `kind` values :
  63400. * - BABYLON.VertexBuffer.PositionKind
  63401. * - BABYLON.VertexBuffer.UVKind
  63402. * - BABYLON.VertexBuffer.UV2Kind
  63403. * - BABYLON.VertexBuffer.UV3Kind
  63404. * - BABYLON.VertexBuffer.UV4Kind
  63405. * - BABYLON.VertexBuffer.UV5Kind
  63406. * - BABYLON.VertexBuffer.UV6Kind
  63407. * - BABYLON.VertexBuffer.ColorKind
  63408. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63409. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63410. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63411. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63412. *
  63413. * Returns the Mesh.
  63414. */
  63415. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63416. if (this.sourceMesh) {
  63417. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63418. }
  63419. return this.sourceMesh;
  63420. };
  63421. /**
  63422. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63423. * If the mesh has no geometry, it is simply returned as it is.
  63424. * The `data` are either a numeric array either a Float32Array.
  63425. * No new underlying VertexBuffer object is created.
  63426. * 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.
  63427. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63428. *
  63429. * Possible `kind` values :
  63430. * - BABYLON.VertexBuffer.PositionKind
  63431. * - BABYLON.VertexBuffer.UVKind
  63432. * - BABYLON.VertexBuffer.UV2Kind
  63433. * - BABYLON.VertexBuffer.UV3Kind
  63434. * - BABYLON.VertexBuffer.UV4Kind
  63435. * - BABYLON.VertexBuffer.UV5Kind
  63436. * - BABYLON.VertexBuffer.UV6Kind
  63437. * - BABYLON.VertexBuffer.ColorKind
  63438. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63439. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63440. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63441. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63442. *
  63443. * Returns the Mesh.
  63444. */
  63445. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63446. if (this.sourceMesh) {
  63447. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63448. }
  63449. return this.sourceMesh;
  63450. };
  63451. /**
  63452. * Sets the mesh indices.
  63453. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63454. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63455. * This method creates a new index buffer each call.
  63456. * Returns the Mesh.
  63457. */
  63458. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63459. if (totalVertices === void 0) { totalVertices = null; }
  63460. if (this.sourceMesh) {
  63461. this.sourceMesh.setIndices(indices, totalVertices);
  63462. }
  63463. return this.sourceMesh;
  63464. };
  63465. /**
  63466. * Boolean : True if the mesh owns the requested kind of data.
  63467. */
  63468. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63469. return this._sourceMesh.isVerticesDataPresent(kind);
  63470. };
  63471. /**
  63472. * Returns an array of indices (IndicesArray).
  63473. */
  63474. InstancedMesh.prototype.getIndices = function () {
  63475. return this._sourceMesh.getIndices();
  63476. };
  63477. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63478. get: function () {
  63479. return this._sourceMesh._positions;
  63480. },
  63481. enumerable: true,
  63482. configurable: true
  63483. });
  63484. /**
  63485. * Sets a new updated BoundingInfo to the mesh.
  63486. * @returns the mesh.
  63487. */
  63488. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63489. var meshBB = this._sourceMesh.getBoundingInfo();
  63490. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63491. this._updateBoundingInfo();
  63492. return this;
  63493. };
  63494. /** @hidden */
  63495. InstancedMesh.prototype._preActivate = function () {
  63496. if (this._currentLOD) {
  63497. this._currentLOD._preActivate();
  63498. }
  63499. return this;
  63500. };
  63501. /** @hidden */
  63502. InstancedMesh.prototype._activate = function (renderId) {
  63503. if (this._currentLOD) {
  63504. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63505. }
  63506. return this;
  63507. };
  63508. /**
  63509. * Returns the current associated LOD AbstractMesh.
  63510. */
  63511. InstancedMesh.prototype.getLOD = function (camera) {
  63512. if (!camera) {
  63513. return this;
  63514. }
  63515. var boundingInfo = this.getBoundingInfo();
  63516. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63517. if (this._currentLOD === this.sourceMesh) {
  63518. return this;
  63519. }
  63520. return this._currentLOD;
  63521. };
  63522. /** @hidden */
  63523. InstancedMesh.prototype._syncSubMeshes = function () {
  63524. this.releaseSubMeshes();
  63525. if (this._sourceMesh.subMeshes) {
  63526. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63527. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63528. }
  63529. }
  63530. return this;
  63531. };
  63532. /** @hidden */
  63533. InstancedMesh.prototype._generatePointsArray = function () {
  63534. return this._sourceMesh._generatePointsArray();
  63535. };
  63536. /**
  63537. * Creates a new InstancedMesh from the current mesh.
  63538. * - name (string) : the cloned mesh name
  63539. * - newParent (optional Node) : the optional Node to parent the clone to.
  63540. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63541. *
  63542. * Returns the clone.
  63543. */
  63544. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63545. var result = this._sourceMesh.createInstance(name);
  63546. // Deep copy
  63547. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63548. // Bounding info
  63549. this.refreshBoundingInfo();
  63550. // Parent
  63551. if (newParent) {
  63552. result.parent = newParent;
  63553. }
  63554. if (!doNotCloneChildren) {
  63555. // Children
  63556. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63557. var mesh = this.getScene().meshes[index];
  63558. if (mesh.parent === this) {
  63559. mesh.clone(mesh.name, result);
  63560. }
  63561. }
  63562. }
  63563. result.computeWorldMatrix(true);
  63564. return result;
  63565. };
  63566. /**
  63567. * Disposes the InstancedMesh.
  63568. * Returns nothing.
  63569. */
  63570. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63571. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63572. // Remove from mesh
  63573. var index = this._sourceMesh.instances.indexOf(this);
  63574. this._sourceMesh.instances.splice(index, 1);
  63575. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63576. };
  63577. return InstancedMesh;
  63578. }(BABYLON.AbstractMesh));
  63579. BABYLON.InstancedMesh = InstancedMesh;
  63580. })(BABYLON || (BABYLON = {}));
  63581. //# sourceMappingURL=babylon.instancedMesh.js.map
  63582. var BABYLON;
  63583. (function (BABYLON) {
  63584. /**
  63585. * Line mesh
  63586. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63587. */
  63588. var LinesMesh = /** @class */ (function (_super) {
  63589. __extends(LinesMesh, _super);
  63590. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63591. /**
  63592. * If vertex color should be applied to the mesh
  63593. */
  63594. useVertexColor,
  63595. /**
  63596. * If vertex alpha should be applied to the mesh
  63597. */
  63598. useVertexAlpha) {
  63599. if (scene === void 0) { scene = null; }
  63600. if (parent === void 0) { parent = null; }
  63601. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63602. _this.useVertexColor = useVertexColor;
  63603. _this.useVertexAlpha = useVertexAlpha;
  63604. /**
  63605. * Color of the line (Default: White)
  63606. */
  63607. _this.color = new BABYLON.Color3(1, 1, 1);
  63608. /**
  63609. * Alpha of the line (Default: 1)
  63610. */
  63611. _this.alpha = 1;
  63612. if (source) {
  63613. _this.color = source.color.clone();
  63614. _this.alpha = source.alpha;
  63615. _this.useVertexColor = source.useVertexColor;
  63616. _this.useVertexAlpha = source.useVertexAlpha;
  63617. }
  63618. _this._intersectionThreshold = 0.1;
  63619. var defines = [];
  63620. var options = {
  63621. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63622. uniforms: ["world", "viewProjection"],
  63623. needAlphaBlending: true,
  63624. defines: defines
  63625. };
  63626. if (useVertexAlpha === false) {
  63627. options.needAlphaBlending = false;
  63628. }
  63629. if (!useVertexColor) {
  63630. options.uniforms.push("color");
  63631. }
  63632. else {
  63633. options.defines.push("#define VERTEXCOLOR");
  63634. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63635. }
  63636. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63637. return _this;
  63638. }
  63639. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63640. /**
  63641. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63642. * This margin is expressed in world space coordinates, so its value may vary.
  63643. * Default value is 0.1
  63644. * @returns the intersection Threshold value.
  63645. */
  63646. get: function () {
  63647. return this._intersectionThreshold;
  63648. },
  63649. /**
  63650. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63651. * This margin is expressed in world space coordinates, so its value may vary.
  63652. */
  63653. set: function (value) {
  63654. if (this._intersectionThreshold === value) {
  63655. return;
  63656. }
  63657. this._intersectionThreshold = value;
  63658. if (this.geometry) {
  63659. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63660. }
  63661. },
  63662. enumerable: true,
  63663. configurable: true
  63664. });
  63665. /**
  63666. * Returns the string "LineMesh"
  63667. */
  63668. LinesMesh.prototype.getClassName = function () {
  63669. return "LinesMesh";
  63670. };
  63671. Object.defineProperty(LinesMesh.prototype, "material", {
  63672. /**
  63673. * @hidden
  63674. */
  63675. get: function () {
  63676. return this._colorShader;
  63677. },
  63678. /**
  63679. * @hidden
  63680. */
  63681. set: function (value) {
  63682. // Do nothing
  63683. },
  63684. enumerable: true,
  63685. configurable: true
  63686. });
  63687. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63688. /**
  63689. * @hidden
  63690. */
  63691. get: function () {
  63692. return false;
  63693. },
  63694. enumerable: true,
  63695. configurable: true
  63696. });
  63697. /** @hidden */
  63698. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63699. if (!this._geometry) {
  63700. return this;
  63701. }
  63702. // VBOs
  63703. this._geometry._bind(this._colorShader.getEffect());
  63704. // Color
  63705. if (!this.useVertexColor) {
  63706. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63707. }
  63708. return this;
  63709. };
  63710. /** @hidden */
  63711. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63712. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63713. return this;
  63714. }
  63715. var engine = this.getScene().getEngine();
  63716. // Draw order
  63717. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63718. return this;
  63719. };
  63720. /**
  63721. * Disposes of the line mesh
  63722. * @param doNotRecurse If children should be disposed
  63723. */
  63724. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63725. this._colorShader.dispose();
  63726. _super.prototype.dispose.call(this, doNotRecurse);
  63727. };
  63728. /**
  63729. * Returns a new LineMesh object cloned from the current one.
  63730. */
  63731. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63732. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63733. };
  63734. return LinesMesh;
  63735. }(BABYLON.Mesh));
  63736. BABYLON.LinesMesh = LinesMesh;
  63737. })(BABYLON || (BABYLON = {}));
  63738. //# sourceMappingURL=babylon.linesMesh.js.map
  63739. var BABYLON;
  63740. (function (BABYLON) {
  63741. /**
  63742. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63743. * The underlying implementation relies on an associative array to ensure the best performances.
  63744. * The value can be anything including 'null' but except 'undefined'
  63745. */
  63746. var StringDictionary = /** @class */ (function () {
  63747. function StringDictionary() {
  63748. this._count = 0;
  63749. this._data = {};
  63750. }
  63751. /**
  63752. * This will clear this dictionary and copy the content from the 'source' one.
  63753. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63754. * @param source the dictionary to take the content from and copy to this dictionary
  63755. */
  63756. StringDictionary.prototype.copyFrom = function (source) {
  63757. var _this = this;
  63758. this.clear();
  63759. source.forEach(function (t, v) { return _this.add(t, v); });
  63760. };
  63761. /**
  63762. * Get a value based from its key
  63763. * @param key the given key to get the matching value from
  63764. * @return the value if found, otherwise undefined is returned
  63765. */
  63766. StringDictionary.prototype.get = function (key) {
  63767. var val = this._data[key];
  63768. if (val !== undefined) {
  63769. return val;
  63770. }
  63771. return undefined;
  63772. };
  63773. /**
  63774. * Get a value from its key or add it if it doesn't exist.
  63775. * This method will ensure you that a given key/data will be present in the dictionary.
  63776. * @param key the given key to get the matching value from
  63777. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63778. * The factory will only be invoked if there's no data for the given key.
  63779. * @return the value corresponding to the key.
  63780. */
  63781. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63782. var val = this.get(key);
  63783. if (val !== undefined) {
  63784. return val;
  63785. }
  63786. val = factory(key);
  63787. if (val) {
  63788. this.add(key, val);
  63789. }
  63790. return val;
  63791. };
  63792. /**
  63793. * Get a value from its key if present in the dictionary otherwise add it
  63794. * @param key the key to get the value from
  63795. * @param val if there's no such key/value pair in the dictionary add it with this value
  63796. * @return the value corresponding to the key
  63797. */
  63798. StringDictionary.prototype.getOrAdd = function (key, val) {
  63799. var curVal = this.get(key);
  63800. if (curVal !== undefined) {
  63801. return curVal;
  63802. }
  63803. this.add(key, val);
  63804. return val;
  63805. };
  63806. /**
  63807. * Check if there's a given key in the dictionary
  63808. * @param key the key to check for
  63809. * @return true if the key is present, false otherwise
  63810. */
  63811. StringDictionary.prototype.contains = function (key) {
  63812. return this._data[key] !== undefined;
  63813. };
  63814. /**
  63815. * Add a new key and its corresponding value
  63816. * @param key the key to add
  63817. * @param value the value corresponding to the key
  63818. * @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
  63819. */
  63820. StringDictionary.prototype.add = function (key, value) {
  63821. if (this._data[key] !== undefined) {
  63822. return false;
  63823. }
  63824. this._data[key] = value;
  63825. ++this._count;
  63826. return true;
  63827. };
  63828. /**
  63829. * Update a specific value associated to a key
  63830. * @param key defines the key to use
  63831. * @param value defines the value to store
  63832. * @returns true if the value was updated (or false if the key was not found)
  63833. */
  63834. StringDictionary.prototype.set = function (key, value) {
  63835. if (this._data[key] === undefined) {
  63836. return false;
  63837. }
  63838. this._data[key] = value;
  63839. return true;
  63840. };
  63841. /**
  63842. * Get the element of the given key and remove it from the dictionary
  63843. * @param key defines the key to search
  63844. * @returns the value associated with the key or null if not found
  63845. */
  63846. StringDictionary.prototype.getAndRemove = function (key) {
  63847. var val = this.get(key);
  63848. if (val !== undefined) {
  63849. delete this._data[key];
  63850. --this._count;
  63851. return val;
  63852. }
  63853. return null;
  63854. };
  63855. /**
  63856. * Remove a key/value from the dictionary.
  63857. * @param key the key to remove
  63858. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63859. */
  63860. StringDictionary.prototype.remove = function (key) {
  63861. if (this.contains(key)) {
  63862. delete this._data[key];
  63863. --this._count;
  63864. return true;
  63865. }
  63866. return false;
  63867. };
  63868. /**
  63869. * Clear the whole content of the dictionary
  63870. */
  63871. StringDictionary.prototype.clear = function () {
  63872. this._data = {};
  63873. this._count = 0;
  63874. };
  63875. Object.defineProperty(StringDictionary.prototype, "count", {
  63876. /**
  63877. * Gets the current count
  63878. */
  63879. get: function () {
  63880. return this._count;
  63881. },
  63882. enumerable: true,
  63883. configurable: true
  63884. });
  63885. /**
  63886. * Execute a callback on each key/val of the dictionary.
  63887. * Note that you can remove any element in this dictionary in the callback implementation
  63888. * @param callback the callback to execute on a given key/value pair
  63889. */
  63890. StringDictionary.prototype.forEach = function (callback) {
  63891. for (var cur in this._data) {
  63892. var val = this._data[cur];
  63893. callback(cur, val);
  63894. }
  63895. };
  63896. /**
  63897. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63898. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63899. * Note that you can remove any element in this dictionary in the callback implementation
  63900. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63901. * @returns the first item
  63902. */
  63903. StringDictionary.prototype.first = function (callback) {
  63904. for (var cur in this._data) {
  63905. var val = this._data[cur];
  63906. var res = callback(cur, val);
  63907. if (res) {
  63908. return res;
  63909. }
  63910. }
  63911. return null;
  63912. };
  63913. return StringDictionary;
  63914. }());
  63915. BABYLON.StringDictionary = StringDictionary;
  63916. })(BABYLON || (BABYLON = {}));
  63917. //# sourceMappingURL=babylon.stringDictionary.js.map
  63918. var BABYLON;
  63919. (function (BABYLON) {
  63920. var Debug;
  63921. (function (Debug) {
  63922. /**
  63923. * Class used to render a debug view of a given skeleton
  63924. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63925. */
  63926. var SkeletonViewer = /** @class */ (function () {
  63927. /**
  63928. * Creates a new SkeletonViewer
  63929. * @param skeleton defines the skeleton to render
  63930. * @param mesh defines the mesh attached to the skeleton
  63931. * @param scene defines the hosting scene
  63932. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63933. * @param renderingGroupId defines the rendering group id to use with the viewer
  63934. */
  63935. function SkeletonViewer(
  63936. /** defines the skeleton to render */
  63937. skeleton,
  63938. /** defines the mesh attached to the skeleton */
  63939. mesh, scene,
  63940. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63941. autoUpdateBonesMatrices,
  63942. /** defines the rendering group id to use with the viewer */
  63943. renderingGroupId) {
  63944. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63945. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63946. this.skeleton = skeleton;
  63947. this.mesh = mesh;
  63948. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63949. this.renderingGroupId = renderingGroupId;
  63950. /** Gets or sets the color used to render the skeleton */
  63951. this.color = BABYLON.Color3.White();
  63952. this._debugLines = new Array();
  63953. this._isEnabled = false;
  63954. this._scene = scene;
  63955. this.update();
  63956. this._renderFunction = this.update.bind(this);
  63957. }
  63958. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63959. get: function () {
  63960. return this._isEnabled;
  63961. },
  63962. /** Gets or sets a boolean indicating if the viewer is enabled */
  63963. set: function (value) {
  63964. if (this._isEnabled === value) {
  63965. return;
  63966. }
  63967. this._isEnabled = value;
  63968. if (value) {
  63969. this._scene.registerBeforeRender(this._renderFunction);
  63970. }
  63971. else {
  63972. this._scene.unregisterBeforeRender(this._renderFunction);
  63973. }
  63974. },
  63975. enumerable: true,
  63976. configurable: true
  63977. });
  63978. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  63979. if (x === void 0) { x = 0; }
  63980. if (y === void 0) { y = 0; }
  63981. if (z === void 0) { z = 0; }
  63982. var tmat = BABYLON.Tmp.Matrix[0];
  63983. var parentBone = bone.getParent();
  63984. tmat.copyFrom(bone.getLocalMatrix());
  63985. if (x !== 0 || y !== 0 || z !== 0) {
  63986. var tmat2 = BABYLON.Tmp.Matrix[1];
  63987. BABYLON.Matrix.IdentityToRef(tmat2);
  63988. tmat2.m[12] = x;
  63989. tmat2.m[13] = y;
  63990. tmat2.m[14] = z;
  63991. tmat2.multiplyToRef(tmat, tmat);
  63992. }
  63993. if (parentBone) {
  63994. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  63995. }
  63996. tmat.multiplyToRef(meshMat, tmat);
  63997. position.x = tmat.m[12];
  63998. position.y = tmat.m[13];
  63999. position.z = tmat.m[14];
  64000. };
  64001. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64002. var len = bones.length;
  64003. var meshPos = this.mesh.position;
  64004. for (var i = 0; i < len; i++) {
  64005. var bone = bones[i];
  64006. var points = this._debugLines[i];
  64007. if (!points) {
  64008. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64009. this._debugLines[i] = points;
  64010. }
  64011. this._getBonePosition(points[0], bone, meshMat);
  64012. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64013. points[0].subtractInPlace(meshPos);
  64014. points[1].subtractInPlace(meshPos);
  64015. }
  64016. };
  64017. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64018. var len = bones.length;
  64019. var boneNum = 0;
  64020. var meshPos = this.mesh.position;
  64021. for (var i = len - 1; i >= 0; i--) {
  64022. var childBone = bones[i];
  64023. var parentBone = childBone.getParent();
  64024. if (!parentBone) {
  64025. continue;
  64026. }
  64027. var points = this._debugLines[boneNum];
  64028. if (!points) {
  64029. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64030. this._debugLines[boneNum] = points;
  64031. }
  64032. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64033. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64034. points[0].subtractInPlace(meshPos);
  64035. points[1].subtractInPlace(meshPos);
  64036. boneNum++;
  64037. }
  64038. };
  64039. /** Update the viewer to sync with current skeleton state */
  64040. SkeletonViewer.prototype.update = function () {
  64041. if (this.autoUpdateBonesMatrices) {
  64042. this.skeleton.computeAbsoluteTransforms();
  64043. }
  64044. if (this.skeleton.bones[0].length === undefined) {
  64045. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64046. }
  64047. else {
  64048. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64049. }
  64050. if (!this._debugMesh) {
  64051. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64052. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64053. }
  64054. else {
  64055. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64056. }
  64057. this._debugMesh.position.copyFrom(this.mesh.position);
  64058. this._debugMesh.color = this.color;
  64059. };
  64060. /** Release associated resources */
  64061. SkeletonViewer.prototype.dispose = function () {
  64062. if (this._debugMesh) {
  64063. this.isEnabled = false;
  64064. this._debugMesh.dispose();
  64065. this._debugMesh = null;
  64066. }
  64067. };
  64068. return SkeletonViewer;
  64069. }());
  64070. Debug.SkeletonViewer = SkeletonViewer;
  64071. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64072. })(BABYLON || (BABYLON = {}));
  64073. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64074. /**
  64075. * Module Debug contains the (visual) components to debug a scene correctly
  64076. */
  64077. var BABYLON;
  64078. (function (BABYLON) {
  64079. var Debug;
  64080. (function (Debug) {
  64081. /**
  64082. * The Axes viewer will show 3 axes in a specific point in space
  64083. */
  64084. var AxesViewer = /** @class */ (function () {
  64085. /**
  64086. * Creates a new AxesViewer
  64087. * @param scene defines the hosting scene
  64088. * @param scaleLines defines a number used to scale line length (1 by default)
  64089. */
  64090. function AxesViewer(scene, scaleLines) {
  64091. if (scaleLines === void 0) { scaleLines = 1; }
  64092. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64093. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64094. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64095. /**
  64096. * Gets or sets a number used to scale line length
  64097. */
  64098. this.scaleLines = 1;
  64099. this.scaleLines = scaleLines;
  64100. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64101. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64102. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64103. this._xmesh.renderingGroupId = 2;
  64104. this._ymesh.renderingGroupId = 2;
  64105. this._zmesh.renderingGroupId = 2;
  64106. this._xmesh.material.checkReadyOnlyOnce = true;
  64107. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64108. this._ymesh.material.checkReadyOnlyOnce = true;
  64109. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64110. this._zmesh.material.checkReadyOnlyOnce = true;
  64111. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64112. this.scene = scene;
  64113. }
  64114. /**
  64115. * Force the viewer to update
  64116. * @param position defines the position of the viewer
  64117. * @param xaxis defines the x axis of the viewer
  64118. * @param yaxis defines the y axis of the viewer
  64119. * @param zaxis defines the z axis of the viewer
  64120. */
  64121. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64122. var scaleLines = this.scaleLines;
  64123. if (this._xmesh) {
  64124. this._xmesh.position.copyFrom(position);
  64125. }
  64126. if (this._ymesh) {
  64127. this._ymesh.position.copyFrom(position);
  64128. }
  64129. if (this._zmesh) {
  64130. this._zmesh.position.copyFrom(position);
  64131. }
  64132. var point2 = this._xline[1];
  64133. point2.x = xaxis.x * scaleLines;
  64134. point2.y = xaxis.y * scaleLines;
  64135. point2.z = xaxis.z * scaleLines;
  64136. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64137. point2 = this._yline[1];
  64138. point2.x = yaxis.x * scaleLines;
  64139. point2.y = yaxis.y * scaleLines;
  64140. point2.z = yaxis.z * scaleLines;
  64141. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64142. point2 = this._zline[1];
  64143. point2.x = zaxis.x * scaleLines;
  64144. point2.y = zaxis.y * scaleLines;
  64145. point2.z = zaxis.z * scaleLines;
  64146. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64147. };
  64148. /** Releases resources */
  64149. AxesViewer.prototype.dispose = function () {
  64150. if (this._xmesh) {
  64151. this._xmesh.dispose();
  64152. }
  64153. if (this._ymesh) {
  64154. this._ymesh.dispose();
  64155. }
  64156. if (this._zmesh) {
  64157. this._zmesh.dispose();
  64158. }
  64159. this._xmesh = null;
  64160. this._ymesh = null;
  64161. this._zmesh = null;
  64162. this.scene = null;
  64163. };
  64164. return AxesViewer;
  64165. }());
  64166. Debug.AxesViewer = AxesViewer;
  64167. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64168. })(BABYLON || (BABYLON = {}));
  64169. //# sourceMappingURL=babylon.axesViewer.js.map
  64170. var BABYLON;
  64171. (function (BABYLON) {
  64172. var Debug;
  64173. (function (Debug) {
  64174. /**
  64175. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64176. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64177. */
  64178. var BoneAxesViewer = /** @class */ (function (_super) {
  64179. __extends(BoneAxesViewer, _super);
  64180. /**
  64181. * Creates a new BoneAxesViewer
  64182. * @param scene defines the hosting scene
  64183. * @param bone defines the target bone
  64184. * @param mesh defines the target mesh
  64185. * @param scaleLines defines a scaling factor for line length (1 by default)
  64186. */
  64187. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64188. if (scaleLines === void 0) { scaleLines = 1; }
  64189. var _this = _super.call(this, scene, scaleLines) || this;
  64190. /** Gets current position */
  64191. _this.pos = BABYLON.Vector3.Zero();
  64192. /** Gets direction of X axis */
  64193. _this.xaxis = BABYLON.Vector3.Zero();
  64194. /** Gets direction of Y axis */
  64195. _this.yaxis = BABYLON.Vector3.Zero();
  64196. /** Gets direction of Z axis */
  64197. _this.zaxis = BABYLON.Vector3.Zero();
  64198. _this.mesh = mesh;
  64199. _this.bone = bone;
  64200. return _this;
  64201. }
  64202. /**
  64203. * Force the viewer to update
  64204. */
  64205. BoneAxesViewer.prototype.update = function () {
  64206. if (!this.mesh || !this.bone) {
  64207. return;
  64208. }
  64209. var bone = this.bone;
  64210. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64211. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64212. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64213. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64214. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64215. };
  64216. /** Releases resources */
  64217. BoneAxesViewer.prototype.dispose = function () {
  64218. if (this.mesh) {
  64219. this.mesh = null;
  64220. this.bone = null;
  64221. _super.prototype.dispose.call(this);
  64222. }
  64223. };
  64224. return BoneAxesViewer;
  64225. }(Debug.AxesViewer));
  64226. Debug.BoneAxesViewer = BoneAxesViewer;
  64227. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64228. })(BABYLON || (BABYLON = {}));
  64229. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64230. var BABYLON;
  64231. (function (BABYLON) {
  64232. /**
  64233. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64234. * in order to better appreciate the issue one might have.
  64235. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64236. */
  64237. var RayHelper = /** @class */ (function () {
  64238. /**
  64239. * Instantiate a new ray helper.
  64240. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64241. * in order to better appreciate the issue one might have.
  64242. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64243. * @param ray Defines the ray we are currently tryin to visualize
  64244. */
  64245. function RayHelper(ray) {
  64246. this.ray = ray;
  64247. }
  64248. /**
  64249. * Helper function to create a colored helper in a scene in one line.
  64250. * @param ray Defines the ray we are currently tryin to visualize
  64251. * @param scene Defines the scene the ray is used in
  64252. * @param color Defines the color we want to see the ray in
  64253. * @returns The newly created ray helper.
  64254. */
  64255. RayHelper.CreateAndShow = function (ray, scene, color) {
  64256. var helper = new RayHelper(ray);
  64257. helper.show(scene, color);
  64258. return helper;
  64259. };
  64260. /**
  64261. * Shows the ray we are willing to debug.
  64262. * @param scene Defines the scene the ray needs to be rendered in
  64263. * @param color Defines the color the ray needs to be rendered in
  64264. */
  64265. RayHelper.prototype.show = function (scene, color) {
  64266. if (!this._renderFunction && this.ray) {
  64267. var ray = this.ray;
  64268. this._renderFunction = this._render.bind(this);
  64269. this._scene = scene;
  64270. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64271. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64272. if (this._renderFunction) {
  64273. this._scene.registerBeforeRender(this._renderFunction);
  64274. }
  64275. }
  64276. if (color && this._renderLine) {
  64277. this._renderLine.color.copyFrom(color);
  64278. }
  64279. };
  64280. /**
  64281. * Hides the ray we are debugging.
  64282. */
  64283. RayHelper.prototype.hide = function () {
  64284. if (this._renderFunction && this._scene) {
  64285. this._scene.unregisterBeforeRender(this._renderFunction);
  64286. this._scene = null;
  64287. this._renderFunction = null;
  64288. if (this._renderLine) {
  64289. this._renderLine.dispose();
  64290. this._renderLine = null;
  64291. }
  64292. this._renderPoints = [];
  64293. }
  64294. };
  64295. RayHelper.prototype._render = function () {
  64296. var ray = this.ray;
  64297. if (!ray) {
  64298. return;
  64299. }
  64300. var point = this._renderPoints[1];
  64301. var len = Math.min(ray.length, 1000000);
  64302. point.copyFrom(ray.direction);
  64303. point.scaleInPlace(len);
  64304. point.addInPlace(ray.origin);
  64305. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64306. };
  64307. /**
  64308. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64309. * @param mesh Defines the mesh we want the helper attached to
  64310. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64311. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64312. * @param length Defines the length of the ray
  64313. */
  64314. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64315. this._attachedToMesh = mesh;
  64316. var ray = this.ray;
  64317. if (!ray) {
  64318. return;
  64319. }
  64320. if (!ray.direction) {
  64321. ray.direction = BABYLON.Vector3.Zero();
  64322. }
  64323. if (!ray.origin) {
  64324. ray.origin = BABYLON.Vector3.Zero();
  64325. }
  64326. if (length) {
  64327. ray.length = length;
  64328. }
  64329. if (!meshSpaceOrigin) {
  64330. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64331. }
  64332. if (!meshSpaceDirection) {
  64333. // -1 so that this will work with Mesh.lookAt
  64334. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64335. }
  64336. if (!this._meshSpaceDirection) {
  64337. this._meshSpaceDirection = meshSpaceDirection.clone();
  64338. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64339. }
  64340. else {
  64341. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64342. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64343. }
  64344. if (!this._updateToMeshFunction) {
  64345. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64346. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64347. }
  64348. this._updateToMesh();
  64349. };
  64350. /**
  64351. * Detach the ray helper from the mesh it has previously been attached to.
  64352. */
  64353. RayHelper.prototype.detachFromMesh = function () {
  64354. if (this._attachedToMesh) {
  64355. if (this._updateToMeshFunction) {
  64356. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64357. }
  64358. this._attachedToMesh = null;
  64359. this._updateToMeshFunction = null;
  64360. }
  64361. };
  64362. RayHelper.prototype._updateToMesh = function () {
  64363. var ray = this.ray;
  64364. if (!this._attachedToMesh || !ray) {
  64365. return;
  64366. }
  64367. if (this._attachedToMesh._isDisposed) {
  64368. this.detachFromMesh();
  64369. return;
  64370. }
  64371. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64372. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64373. };
  64374. /**
  64375. * Dispose the helper and release its associated resources.
  64376. */
  64377. RayHelper.prototype.dispose = function () {
  64378. this.hide();
  64379. this.detachFromMesh();
  64380. this.ray = null;
  64381. };
  64382. return RayHelper;
  64383. }());
  64384. BABYLON.RayHelper = RayHelper;
  64385. })(BABYLON || (BABYLON = {}));
  64386. //# sourceMappingURL=babylon.rayHelper.js.map
  64387. var BABYLON;
  64388. (function (BABYLON) {
  64389. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64390. get: function () {
  64391. if (!this._debugLayer) {
  64392. this._debugLayer = new DebugLayer(this);
  64393. }
  64394. return this._debugLayer;
  64395. },
  64396. enumerable: true,
  64397. configurable: true
  64398. });
  64399. /**
  64400. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64401. * what is happening in your scene
  64402. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64403. */
  64404. var DebugLayer = /** @class */ (function () {
  64405. /**
  64406. * Instantiates a new debug layer.
  64407. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64408. * what is happening in your scene
  64409. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64410. * @param scene Defines the scene to inspect
  64411. */
  64412. function DebugLayer(scene) {
  64413. var _this = this;
  64414. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64415. /**
  64416. * Observable triggered when a property is changed through the inspector.
  64417. */
  64418. this.onPropertyChangedObservable = new BABYLON.Observable();
  64419. this._scene = scene;
  64420. this._scene.onDisposeObservable.add(function () {
  64421. // Debug layer
  64422. if (_this._scene._debugLayer) {
  64423. _this._scene._debugLayer.hide();
  64424. }
  64425. });
  64426. }
  64427. /** Creates the inspector window. */
  64428. DebugLayer.prototype._createInspector = function (config) {
  64429. if (config === void 0) { config = {}; }
  64430. var popup = config.popup || false;
  64431. var initialTab = config.initialTab || 0;
  64432. var parentElement = config.parentElement || null;
  64433. if (!this._inspector) {
  64434. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64435. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64436. } // else nothing to do as instance is already created
  64437. };
  64438. /**
  64439. * Get if the inspector is visible or not.
  64440. * @returns true if visible otherwise, false
  64441. */
  64442. DebugLayer.prototype.isVisible = function () {
  64443. if (!this._inspector) {
  64444. return false;
  64445. }
  64446. return true;
  64447. };
  64448. /**
  64449. * Hide the inspector and close its window.
  64450. */
  64451. DebugLayer.prototype.hide = function () {
  64452. if (this._inspector) {
  64453. try {
  64454. this._inspector.dispose();
  64455. }
  64456. catch (e) {
  64457. // If the inspector has been removed directly from the inspector tool
  64458. }
  64459. this.onPropertyChangedObservable.clear();
  64460. this._inspector = null;
  64461. }
  64462. };
  64463. /**
  64464. *
  64465. * Launch the debugLayer.
  64466. *
  64467. * initialTab:
  64468. * | Value | Tab Name |
  64469. * | --- | --- |
  64470. * | 0 | Scene |
  64471. * | 1 | Console |
  64472. * | 2 | Stats |
  64473. * | 3 | Textures |
  64474. * | 4 | Mesh |
  64475. * | 5 | Light |
  64476. * | 6 | Material |
  64477. * | 7 | GLTF |
  64478. * | 8 | GUI |
  64479. * | 9 | Physics |
  64480. * | 10 | Camera |
  64481. * | 11 | Audio |
  64482. *
  64483. * @param config Define the configuration of the inspector
  64484. */
  64485. DebugLayer.prototype.show = function (config) {
  64486. if (config === void 0) { config = {}; }
  64487. if (typeof this.BJSINSPECTOR == 'undefined') {
  64488. // Load inspector and add it to the DOM
  64489. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64490. }
  64491. else {
  64492. // Otherwise creates the inspector
  64493. this._createInspector(config);
  64494. }
  64495. };
  64496. /**
  64497. * Gets the active tab
  64498. * @return the index of the active tab or -1 if the inspector is hidden
  64499. */
  64500. DebugLayer.prototype.getActiveTab = function () {
  64501. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64502. };
  64503. /**
  64504. * Define the url to get the inspector script from.
  64505. * By default it uses the babylonjs CDN.
  64506. * @ignoreNaming
  64507. */
  64508. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64509. return DebugLayer;
  64510. }());
  64511. BABYLON.DebugLayer = DebugLayer;
  64512. })(BABYLON || (BABYLON = {}));
  64513. //# sourceMappingURL=babylon.debugLayer.js.map
  64514. var BABYLON;
  64515. (function (BABYLON) {
  64516. var Debug;
  64517. (function (Debug) {
  64518. /**
  64519. * Used to show the physics impostor around the specific mesh
  64520. */
  64521. var PhysicsViewer = /** @class */ (function () {
  64522. /**
  64523. * Creates a new PhysicsViewer
  64524. * @param scene defines the hosting scene
  64525. */
  64526. function PhysicsViewer(scene) {
  64527. /** @hidden */
  64528. this._impostors = [];
  64529. /** @hidden */
  64530. this._meshes = [];
  64531. /** @hidden */
  64532. this._numMeshes = 0;
  64533. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64534. var physicEngine = this._scene.getPhysicsEngine();
  64535. if (physicEngine) {
  64536. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64537. }
  64538. }
  64539. /** @hidden */
  64540. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64541. var plugin = this._physicsEnginePlugin;
  64542. for (var i = 0; i < this._numMeshes; i++) {
  64543. var impostor = this._impostors[i];
  64544. if (!impostor) {
  64545. continue;
  64546. }
  64547. if (impostor.isDisposed) {
  64548. this.hideImpostor(this._impostors[i--]);
  64549. }
  64550. else {
  64551. var mesh = this._meshes[i];
  64552. if (mesh && plugin) {
  64553. plugin.syncMeshWithImpostor(mesh, impostor);
  64554. }
  64555. }
  64556. }
  64557. };
  64558. /**
  64559. * Renders a specified physic impostor
  64560. * @param impostor defines the impostor to render
  64561. */
  64562. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64563. if (!this._scene) {
  64564. return;
  64565. }
  64566. for (var i = 0; i < this._numMeshes; i++) {
  64567. if (this._impostors[i] == impostor) {
  64568. return;
  64569. }
  64570. }
  64571. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64572. if (debugMesh) {
  64573. this._impostors[this._numMeshes] = impostor;
  64574. this._meshes[this._numMeshes] = debugMesh;
  64575. if (this._numMeshes === 0) {
  64576. this._renderFunction = this._updateDebugMeshes.bind(this);
  64577. this._scene.registerBeforeRender(this._renderFunction);
  64578. }
  64579. this._numMeshes++;
  64580. }
  64581. };
  64582. /**
  64583. * Hides a specified physic impostor
  64584. * @param impostor defines the impostor to hide
  64585. */
  64586. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64587. if (!impostor || !this._scene) {
  64588. return;
  64589. }
  64590. var removed = false;
  64591. for (var i = 0; i < this._numMeshes; i++) {
  64592. if (this._impostors[i] == impostor) {
  64593. var mesh = this._meshes[i];
  64594. if (!mesh) {
  64595. continue;
  64596. }
  64597. this._scene.removeMesh(mesh);
  64598. mesh.dispose();
  64599. this._numMeshes--;
  64600. if (this._numMeshes > 0) {
  64601. this._meshes[i] = this._meshes[this._numMeshes];
  64602. this._impostors[i] = this._impostors[this._numMeshes];
  64603. this._meshes[this._numMeshes] = null;
  64604. this._impostors[this._numMeshes] = null;
  64605. }
  64606. else {
  64607. this._meshes[0] = null;
  64608. this._impostors[0] = null;
  64609. }
  64610. removed = true;
  64611. break;
  64612. }
  64613. }
  64614. if (removed && this._numMeshes === 0) {
  64615. this._scene.unregisterBeforeRender(this._renderFunction);
  64616. }
  64617. };
  64618. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64619. if (!this._debugMaterial) {
  64620. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64621. this._debugMaterial.wireframe = true;
  64622. }
  64623. return this._debugMaterial;
  64624. };
  64625. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64626. if (!this._debugBoxMesh) {
  64627. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64628. this._debugBoxMesh.renderingGroupId = 1;
  64629. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64630. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64631. scene.removeMesh(this._debugBoxMesh);
  64632. }
  64633. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64634. };
  64635. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64636. if (!this._debugSphereMesh) {
  64637. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64638. this._debugSphereMesh.renderingGroupId = 1;
  64639. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64640. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64641. scene.removeMesh(this._debugSphereMesh);
  64642. }
  64643. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64644. };
  64645. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64646. var mesh = null;
  64647. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64648. mesh = this._getDebugBoxMesh(scene);
  64649. impostor.getBoxSizeToRef(mesh.scaling);
  64650. }
  64651. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64652. mesh = this._getDebugSphereMesh(scene);
  64653. var radius = impostor.getRadius();
  64654. mesh.scaling.x = radius * 2;
  64655. mesh.scaling.y = radius * 2;
  64656. mesh.scaling.z = radius * 2;
  64657. }
  64658. return mesh;
  64659. };
  64660. /** Releases all resources */
  64661. PhysicsViewer.prototype.dispose = function () {
  64662. for (var i = 0; i < this._numMeshes; i++) {
  64663. this.hideImpostor(this._impostors[i]);
  64664. }
  64665. if (this._debugBoxMesh) {
  64666. this._debugBoxMesh.dispose();
  64667. }
  64668. if (this._debugSphereMesh) {
  64669. this._debugSphereMesh.dispose();
  64670. }
  64671. if (this._debugMaterial) {
  64672. this._debugMaterial.dispose();
  64673. }
  64674. this._impostors.length = 0;
  64675. this._scene = null;
  64676. this._physicsEnginePlugin = null;
  64677. };
  64678. return PhysicsViewer;
  64679. }());
  64680. Debug.PhysicsViewer = PhysicsViewer;
  64681. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64682. })(BABYLON || (BABYLON = {}));
  64683. //# sourceMappingURL=babylon.physicsViewer.js.map
  64684. var BABYLON;
  64685. (function (BABYLON) {
  64686. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64687. get: function () {
  64688. return this._forceShowBoundingBoxes || false;
  64689. },
  64690. set: function (value) {
  64691. this._forceShowBoundingBoxes = value;
  64692. // Lazyly creates a BB renderer if needed.
  64693. if (value) {
  64694. this.getBoundingBoxRenderer();
  64695. }
  64696. },
  64697. enumerable: true,
  64698. configurable: true
  64699. });
  64700. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64701. if (!this._boundingBoxRenderer) {
  64702. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64703. }
  64704. return this._boundingBoxRenderer;
  64705. };
  64706. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64707. get: function () {
  64708. return this._showBoundingBox || false;
  64709. },
  64710. set: function (value) {
  64711. this._showBoundingBox = value;
  64712. // Lazyly creates a BB renderer if needed.
  64713. if (value) {
  64714. this.getScene().getBoundingBoxRenderer();
  64715. }
  64716. },
  64717. enumerable: true,
  64718. configurable: true
  64719. });
  64720. /**
  64721. * Component responsible of rendering the bounding box of the meshes in a scene.
  64722. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64723. */
  64724. var BoundingBoxRenderer = /** @class */ (function () {
  64725. /**
  64726. * Instantiates a new bounding box renderer in a scene.
  64727. * @param scene the scene the renderer renders in
  64728. */
  64729. function BoundingBoxRenderer(scene) {
  64730. /**
  64731. * The component name helpfull to identify the component in the list of scene components.
  64732. */
  64733. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64734. /**
  64735. * Color of the bounding box lines placed in front of an object
  64736. */
  64737. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64738. /**
  64739. * Color of the bounding box lines placed behind an object
  64740. */
  64741. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64742. /**
  64743. * Defines if the renderer should show the back lines or not
  64744. */
  64745. this.showBackLines = true;
  64746. /**
  64747. * @hidden
  64748. */
  64749. this.renderList = new BABYLON.SmartArray(32);
  64750. this._vertexBuffers = {};
  64751. this.scene = scene;
  64752. scene._addComponent(this);
  64753. }
  64754. /**
  64755. * Registers the component in a given scene
  64756. */
  64757. BoundingBoxRenderer.prototype.register = function () {
  64758. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64759. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64760. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64761. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64762. };
  64763. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64764. if (mesh.showSubMeshesBoundingBox) {
  64765. var boundingInfo = subMesh.getBoundingInfo();
  64766. if (boundingInfo !== null && boundingInfo !== undefined) {
  64767. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64768. this.renderList.push(boundingInfo.boundingBox);
  64769. }
  64770. }
  64771. };
  64772. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64773. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64774. var boundingInfo = sourceMesh.getBoundingInfo();
  64775. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64776. this.renderList.push(boundingInfo.boundingBox);
  64777. }
  64778. };
  64779. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64780. if (this._colorShader) {
  64781. return;
  64782. }
  64783. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64784. attributes: [BABYLON.VertexBuffer.PositionKind],
  64785. uniforms: ["world", "viewProjection", "color"]
  64786. });
  64787. var engine = this.scene.getEngine();
  64788. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64789. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64790. this._createIndexBuffer();
  64791. };
  64792. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64793. var engine = this.scene.getEngine();
  64794. 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]);
  64795. };
  64796. /**
  64797. * Rebuilds the elements related to this component in case of
  64798. * context lost for instance.
  64799. */
  64800. BoundingBoxRenderer.prototype.rebuild = function () {
  64801. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64802. if (vb) {
  64803. vb._rebuild();
  64804. }
  64805. this._createIndexBuffer();
  64806. };
  64807. /**
  64808. * @hidden
  64809. */
  64810. BoundingBoxRenderer.prototype.reset = function () {
  64811. this.renderList.reset();
  64812. };
  64813. /**
  64814. * Render the bounding boxes of a specific rendering group
  64815. * @param renderingGroupId defines the rendering group to render
  64816. */
  64817. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64818. if (this.renderList.length === 0) {
  64819. return;
  64820. }
  64821. this._prepareRessources();
  64822. if (!this._colorShader.isReady()) {
  64823. return;
  64824. }
  64825. var engine = this.scene.getEngine();
  64826. engine.setDepthWrite(false);
  64827. this._colorShader._preBind();
  64828. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64829. var boundingBox = this.renderList.data[boundingBoxIndex];
  64830. if (boundingBox._tag !== renderingGroupId) {
  64831. continue;
  64832. }
  64833. var min = boundingBox.minimum;
  64834. var max = boundingBox.maximum;
  64835. var diff = max.subtract(min);
  64836. var median = min.add(diff.scale(0.5));
  64837. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64838. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64839. .multiply(boundingBox.getWorldMatrix());
  64840. // VBOs
  64841. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64842. if (this.showBackLines) {
  64843. // Back
  64844. engine.setDepthFunctionToGreaterOrEqual();
  64845. this.scene.resetCachedMaterial();
  64846. this._colorShader.setColor4("color", this.backColor.toColor4());
  64847. this._colorShader.bind(worldMatrix);
  64848. // Draw order
  64849. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64850. }
  64851. // Front
  64852. engine.setDepthFunctionToLess();
  64853. this.scene.resetCachedMaterial();
  64854. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64855. this._colorShader.bind(worldMatrix);
  64856. // Draw order
  64857. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64858. }
  64859. this._colorShader.unbind();
  64860. engine.setDepthFunctionToLessOrEqual();
  64861. engine.setDepthWrite(true);
  64862. };
  64863. /**
  64864. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64865. * @param mesh Define the mesh to render the occlusion bounding box for
  64866. */
  64867. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64868. this._prepareRessources();
  64869. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64870. return;
  64871. }
  64872. var engine = this.scene.getEngine();
  64873. engine.setDepthWrite(false);
  64874. engine.setColorWrite(false);
  64875. this._colorShader._preBind();
  64876. var boundingBox = mesh._boundingInfo.boundingBox;
  64877. var min = boundingBox.minimum;
  64878. var max = boundingBox.maximum;
  64879. var diff = max.subtract(min);
  64880. var median = min.add(diff.scale(0.5));
  64881. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64882. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64883. .multiply(boundingBox.getWorldMatrix());
  64884. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64885. engine.setDepthFunctionToLess();
  64886. this.scene.resetCachedMaterial();
  64887. this._colorShader.bind(worldMatrix);
  64888. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64889. this._colorShader.unbind();
  64890. engine.setDepthFunctionToLessOrEqual();
  64891. engine.setDepthWrite(true);
  64892. engine.setColorWrite(true);
  64893. };
  64894. /**
  64895. * Dispose and release the resources attached to this renderer.
  64896. */
  64897. BoundingBoxRenderer.prototype.dispose = function () {
  64898. if (!this._colorShader) {
  64899. return;
  64900. }
  64901. this.renderList.dispose();
  64902. this._colorShader.dispose();
  64903. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64904. if (buffer) {
  64905. buffer.dispose();
  64906. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64907. }
  64908. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64909. };
  64910. return BoundingBoxRenderer;
  64911. }());
  64912. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64913. })(BABYLON || (BABYLON = {}));
  64914. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64915. var BABYLON;
  64916. (function (BABYLON) {
  64917. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64918. return this._gl.createTransformFeedback();
  64919. };
  64920. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64921. this._gl.deleteTransformFeedback(value);
  64922. };
  64923. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64924. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64925. };
  64926. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64927. if (usePoints === void 0) { usePoints = true; }
  64928. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64929. };
  64930. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64931. this._gl.endTransformFeedback();
  64932. };
  64933. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64934. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64935. };
  64936. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64937. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64938. };
  64939. })(BABYLON || (BABYLON = {}));
  64940. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64941. var BABYLON;
  64942. (function (BABYLON) {
  64943. /**
  64944. * This represents a GPU particle system in Babylon
  64945. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64946. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64947. */
  64948. var GPUParticleSystem = /** @class */ (function (_super) {
  64949. __extends(GPUParticleSystem, _super);
  64950. /**
  64951. * Instantiates a GPU particle system.
  64952. * 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.
  64953. * @param name The name of the particle system
  64954. * @param options The options used to create the system
  64955. * @param scene The scene the particle system belongs to
  64956. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64957. */
  64958. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64959. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64960. var _this = _super.call(this, name) || this;
  64961. /**
  64962. * The layer mask we are rendering the particles through.
  64963. */
  64964. _this.layerMask = 0x0FFFFFFF;
  64965. _this._accumulatedCount = 0;
  64966. _this._targetIndex = 0;
  64967. _this._currentRenderId = -1;
  64968. _this._started = false;
  64969. _this._stopped = false;
  64970. _this._timeDelta = 0;
  64971. _this._attributesStrideSize = 21;
  64972. _this._actualFrame = 0;
  64973. _this._rawTextureWidth = 256;
  64974. /**
  64975. * An event triggered when the system is disposed.
  64976. */
  64977. _this.onDisposeObservable = new BABYLON.Observable();
  64978. /**
  64979. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  64980. * to override the particles.
  64981. */
  64982. _this.forceDepthWrite = false;
  64983. _this._preWarmDone = false;
  64984. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64985. // Setup the default processing configuration to the scene.
  64986. _this._attachImageProcessingConfiguration(null);
  64987. _this._engine = _this._scene.getEngine();
  64988. if (!options.randomTextureSize) {
  64989. delete options.randomTextureSize;
  64990. }
  64991. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  64992. var optionsAsNumber = options;
  64993. if (isFinite(optionsAsNumber)) {
  64994. fullOptions.capacity = optionsAsNumber;
  64995. }
  64996. _this._capacity = fullOptions.capacity;
  64997. _this._activeCount = fullOptions.capacity;
  64998. _this._currentActiveCount = 0;
  64999. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  65000. _this._scene.particleSystems.push(_this);
  65001. _this._updateEffectOptions = {
  65002. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  65003. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  65004. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  65005. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  65006. uniformBuffersNames: [],
  65007. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  65008. defines: "",
  65009. fallbacks: null,
  65010. onCompiled: null,
  65011. onError: null,
  65012. indexParameters: null,
  65013. maxSimultaneousLights: 0,
  65014. transformFeedbackVaryings: []
  65015. };
  65016. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  65017. // Random data
  65018. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  65019. var d = [];
  65020. for (var i = 0; i < maxTextureSize; ++i) {
  65021. d.push(Math.random());
  65022. d.push(Math.random());
  65023. d.push(Math.random());
  65024. d.push(Math.random());
  65025. }
  65026. _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);
  65027. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65028. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65029. d = [];
  65030. for (var i = 0; i < maxTextureSize; ++i) {
  65031. d.push(Math.random());
  65032. d.push(Math.random());
  65033. d.push(Math.random());
  65034. d.push(Math.random());
  65035. }
  65036. _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);
  65037. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65038. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65039. _this._randomTextureSize = maxTextureSize;
  65040. return _this;
  65041. }
  65042. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65043. /**
  65044. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65045. */
  65046. get: function () {
  65047. if (!BABYLON.Engine.LastCreatedEngine) {
  65048. return false;
  65049. }
  65050. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65051. },
  65052. enumerable: true,
  65053. configurable: true
  65054. });
  65055. /**
  65056. * Gets the maximum number of particles active at the same time.
  65057. * @returns The max number of active particles.
  65058. */
  65059. GPUParticleSystem.prototype.getCapacity = function () {
  65060. return this._capacity;
  65061. };
  65062. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65063. /**
  65064. * Gets or set the number of active particles
  65065. */
  65066. get: function () {
  65067. return this._activeCount;
  65068. },
  65069. set: function (value) {
  65070. this._activeCount = Math.min(value, this._capacity);
  65071. },
  65072. enumerable: true,
  65073. configurable: true
  65074. });
  65075. /**
  65076. * Is this system ready to be used/rendered
  65077. * @return true if the system is ready
  65078. */
  65079. GPUParticleSystem.prototype.isReady = function () {
  65080. if (!this._updateEffect) {
  65081. this._recreateUpdateEffect();
  65082. this._recreateRenderEffect();
  65083. return false;
  65084. }
  65085. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65086. return false;
  65087. }
  65088. return true;
  65089. };
  65090. /**
  65091. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65092. * @returns True if it has been started, otherwise false.
  65093. */
  65094. GPUParticleSystem.prototype.isStarted = function () {
  65095. return this._started;
  65096. };
  65097. /**
  65098. * Starts the particle system and begins to emit
  65099. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65100. */
  65101. GPUParticleSystem.prototype.start = function (delay) {
  65102. var _this = this;
  65103. if (delay === void 0) { delay = this.startDelay; }
  65104. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65105. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65106. }
  65107. if (delay) {
  65108. setTimeout(function () {
  65109. _this.start(0);
  65110. }, delay);
  65111. return;
  65112. }
  65113. this._started = true;
  65114. this._stopped = false;
  65115. this._preWarmDone = false;
  65116. // Animations
  65117. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65118. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65119. }
  65120. };
  65121. /**
  65122. * Stops the particle system.
  65123. */
  65124. GPUParticleSystem.prototype.stop = function () {
  65125. this._stopped = true;
  65126. };
  65127. /**
  65128. * Remove all active particles
  65129. */
  65130. GPUParticleSystem.prototype.reset = function () {
  65131. this._releaseBuffers();
  65132. this._releaseVAOs();
  65133. this._currentActiveCount = 0;
  65134. this._targetIndex = 0;
  65135. };
  65136. /**
  65137. * Returns the string "GPUParticleSystem"
  65138. * @returns a string containing the class name
  65139. */
  65140. GPUParticleSystem.prototype.getClassName = function () {
  65141. return "GPUParticleSystem";
  65142. };
  65143. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65144. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65145. this._releaseBuffers();
  65146. return this;
  65147. };
  65148. /**
  65149. * Adds a new color gradient
  65150. * @param gradient defines the gradient to use (between 0 and 1)
  65151. * @param color1 defines the color to affect to the specified gradient
  65152. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65153. * @returns the current particle system
  65154. */
  65155. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65156. if (!this._colorGradients) {
  65157. this._colorGradients = [];
  65158. }
  65159. var colorGradient = new BABYLON.ColorGradient();
  65160. colorGradient.gradient = gradient;
  65161. colorGradient.color1 = color1;
  65162. this._colorGradients.push(colorGradient);
  65163. this._colorGradients.sort(function (a, b) {
  65164. if (a.gradient < b.gradient) {
  65165. return -1;
  65166. }
  65167. else if (a.gradient > b.gradient) {
  65168. return 1;
  65169. }
  65170. return 0;
  65171. });
  65172. if (this._colorGradientsTexture) {
  65173. this._colorGradientsTexture.dispose();
  65174. this._colorGradientsTexture = null;
  65175. }
  65176. this._releaseBuffers();
  65177. return this;
  65178. };
  65179. /**
  65180. * Remove a specific color gradient
  65181. * @param gradient defines the gradient to remove
  65182. * @returns the current particle system
  65183. */
  65184. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65185. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65186. this._colorGradientsTexture = null;
  65187. return this;
  65188. };
  65189. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65190. var valueGradient = new BABYLON.FactorGradient();
  65191. valueGradient.gradient = gradient;
  65192. valueGradient.factor1 = factor;
  65193. factorGradients.push(valueGradient);
  65194. factorGradients.sort(function (a, b) {
  65195. if (a.gradient < b.gradient) {
  65196. return -1;
  65197. }
  65198. else if (a.gradient > b.gradient) {
  65199. return 1;
  65200. }
  65201. return 0;
  65202. });
  65203. this._releaseBuffers();
  65204. };
  65205. /**
  65206. * Adds a new size gradient
  65207. * @param gradient defines the gradient to use (between 0 and 1)
  65208. * @param factor defines the size factor to affect to the specified gradient
  65209. * @returns the current particle system
  65210. */
  65211. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65212. if (!this._sizeGradients) {
  65213. this._sizeGradients = [];
  65214. }
  65215. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65216. if (this._sizeGradientsTexture) {
  65217. this._sizeGradientsTexture.dispose();
  65218. this._sizeGradientsTexture = null;
  65219. }
  65220. this._releaseBuffers();
  65221. return this;
  65222. };
  65223. /**
  65224. * Remove a specific size gradient
  65225. * @param gradient defines the gradient to remove
  65226. * @returns the current particle system
  65227. */
  65228. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65229. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65230. this._sizeGradientsTexture = null;
  65231. return this;
  65232. };
  65233. /**
  65234. * Adds a new angular speed gradient
  65235. * @param gradient defines the gradient to use (between 0 and 1)
  65236. * @param factor defines the angular speed to affect to the specified gradient
  65237. * @returns the current particle system
  65238. */
  65239. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65240. if (!this._angularSpeedGradients) {
  65241. this._angularSpeedGradients = [];
  65242. }
  65243. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65244. if (this._angularSpeedGradientsTexture) {
  65245. this._angularSpeedGradientsTexture.dispose();
  65246. this._angularSpeedGradientsTexture = null;
  65247. }
  65248. this._releaseBuffers();
  65249. return this;
  65250. };
  65251. /**
  65252. * Remove a specific angular speed gradient
  65253. * @param gradient defines the gradient to remove
  65254. * @returns the current particle system
  65255. */
  65256. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65257. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65258. this._angularSpeedGradientsTexture = null;
  65259. return this;
  65260. };
  65261. /**
  65262. * Adds a new velocity gradient
  65263. * @param gradient defines the gradient to use (between 0 and 1)
  65264. * @param factor defines the velocity to affect to the specified gradient
  65265. * @returns the current particle system
  65266. */
  65267. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65268. if (!this._velocityGradients) {
  65269. this._velocityGradients = [];
  65270. }
  65271. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65272. if (this._velocityGradientsTexture) {
  65273. this._velocityGradientsTexture.dispose();
  65274. this._velocityGradientsTexture = null;
  65275. }
  65276. this._releaseBuffers();
  65277. return this;
  65278. };
  65279. /**
  65280. * Remove a specific velocity gradient
  65281. * @param gradient defines the gradient to remove
  65282. * @returns the current particle system
  65283. */
  65284. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65285. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65286. this._velocityGradientsTexture = null;
  65287. return this;
  65288. };
  65289. /**
  65290. * Adds a new limit velocity gradient
  65291. * @param gradient defines the gradient to use (between 0 and 1)
  65292. * @param factor defines the limit velocity value to affect to the specified gradient
  65293. * @returns the current particle system
  65294. */
  65295. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65296. if (!this._limitVelocityGradients) {
  65297. this._limitVelocityGradients = [];
  65298. }
  65299. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65300. if (this._limitVelocityGradientsTexture) {
  65301. this._limitVelocityGradientsTexture.dispose();
  65302. this._limitVelocityGradientsTexture = null;
  65303. }
  65304. this._releaseBuffers();
  65305. return this;
  65306. };
  65307. /**
  65308. * Remove a specific limit velocity gradient
  65309. * @param gradient defines the gradient to remove
  65310. * @returns the current particle system
  65311. */
  65312. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65313. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65314. this._limitVelocityGradientsTexture = null;
  65315. return this;
  65316. };
  65317. /**
  65318. * Adds a new drag gradient
  65319. * @param gradient defines the gradient to use (between 0 and 1)
  65320. * @param factor defines the drag value to affect to the specified gradient
  65321. * @returns the current particle system
  65322. */
  65323. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65324. if (!this._dragGradients) {
  65325. this._dragGradients = [];
  65326. }
  65327. this._addFactorGradient(this._dragGradients, gradient, factor);
  65328. if (this._dragGradientsTexture) {
  65329. this._dragGradientsTexture.dispose();
  65330. this._dragGradientsTexture = null;
  65331. }
  65332. this._releaseBuffers();
  65333. return this;
  65334. };
  65335. /**
  65336. * Remove a specific drag gradient
  65337. * @param gradient defines the gradient to remove
  65338. * @returns the current particle system
  65339. */
  65340. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65341. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65342. this._dragGradientsTexture = null;
  65343. return this;
  65344. };
  65345. /**
  65346. * Not supported by GPUParticleSystem
  65347. * @param gradient defines the gradient to use (between 0 and 1)
  65348. * @param factor defines the emit rate value to affect to the specified gradient
  65349. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65350. * @returns the current particle system
  65351. */
  65352. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65353. // Do nothing as emit rate is not supported by GPUParticleSystem
  65354. return this;
  65355. };
  65356. /**
  65357. * Not supported by GPUParticleSystem
  65358. * @param gradient defines the gradient to remove
  65359. * @returns the current particle system
  65360. */
  65361. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65362. // Do nothing as emit rate is not supported by GPUParticleSystem
  65363. return this;
  65364. };
  65365. /**
  65366. * Not supported by GPUParticleSystem
  65367. * @param gradient defines the gradient to use (between 0 and 1)
  65368. * @param factor defines the start size value to affect to the specified gradient
  65369. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65370. * @returns the current particle system
  65371. */
  65372. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65373. // Do nothing as start size is not supported by GPUParticleSystem
  65374. return this;
  65375. };
  65376. /**
  65377. * Not supported by GPUParticleSystem
  65378. * @param gradient defines the gradient to remove
  65379. * @returns the current particle system
  65380. */
  65381. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65382. // Do nothing as start size is not supported by GPUParticleSystem
  65383. return this;
  65384. };
  65385. /**
  65386. * Not supported by GPUParticleSystem
  65387. * @param gradient defines the gradient to use (between 0 and 1)
  65388. * @param min defines the color remap minimal range
  65389. * @param max defines the color remap maximal range
  65390. * @returns the current particle system
  65391. */
  65392. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65393. // Do nothing as start size is not supported by GPUParticleSystem
  65394. return this;
  65395. };
  65396. /**
  65397. * Not supported by GPUParticleSystem
  65398. * @param gradient defines the gradient to remove
  65399. * @returns the current particle system
  65400. */
  65401. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65402. // Do nothing as start size is not supported by GPUParticleSystem
  65403. return this;
  65404. };
  65405. /**
  65406. * Not supported by GPUParticleSystem
  65407. * @param gradient defines the gradient to use (between 0 and 1)
  65408. * @param min defines the alpha remap minimal range
  65409. * @param max defines the alpha remap maximal range
  65410. * @returns the current particle system
  65411. */
  65412. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65413. // Do nothing as start size is not supported by GPUParticleSystem
  65414. return this;
  65415. };
  65416. /**
  65417. * Not supported by GPUParticleSystem
  65418. * @param gradient defines the gradient to remove
  65419. * @returns the current particle system
  65420. */
  65421. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65422. // Do nothing as start size is not supported by GPUParticleSystem
  65423. return this;
  65424. };
  65425. /**
  65426. * Not supported by GPUParticleSystem
  65427. * @param gradient defines the gradient to use (between 0 and 1)
  65428. * @param color defines the color to affect to the specified gradient
  65429. * @returns the current particle system
  65430. */
  65431. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65432. //Not supported by GPUParticleSystem
  65433. return this;
  65434. };
  65435. /**
  65436. * Not supported by GPUParticleSystem
  65437. * @param gradient defines the gradient to remove
  65438. * @returns the current particle system
  65439. */
  65440. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65441. //Not supported by GPUParticleSystem
  65442. return this;
  65443. };
  65444. /**
  65445. * Not supported by GPUParticleSystem
  65446. * @returns the list of ramp gradients
  65447. */
  65448. GPUParticleSystem.prototype.getRampGradients = function () {
  65449. return null;
  65450. };
  65451. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65452. /**
  65453. * Not supported by GPUParticleSystem
  65454. * Gets or sets a boolean indicating that ramp gradients must be used
  65455. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65456. */
  65457. get: function () {
  65458. //Not supported by GPUParticleSystem
  65459. return false;
  65460. },
  65461. set: function (value) {
  65462. //Not supported by GPUParticleSystem
  65463. },
  65464. enumerable: true,
  65465. configurable: true
  65466. });
  65467. /**
  65468. * Not supported by GPUParticleSystem
  65469. * @param gradient defines the gradient to use (between 0 and 1)
  65470. * @param factor defines the life time factor to affect to the specified gradient
  65471. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65472. * @returns the current particle system
  65473. */
  65474. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65475. //Not supported by GPUParticleSystem
  65476. return this;
  65477. };
  65478. /**
  65479. * Not supported by GPUParticleSystem
  65480. * @param gradient defines the gradient to remove
  65481. * @returns the current particle system
  65482. */
  65483. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65484. //Not supported by GPUParticleSystem
  65485. return this;
  65486. };
  65487. GPUParticleSystem.prototype._reset = function () {
  65488. this._releaseBuffers();
  65489. };
  65490. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65491. var updateVertexBuffers = {};
  65492. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65493. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65494. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65495. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65496. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65497. var offset = 12;
  65498. if (!this._colorGradientsTexture) {
  65499. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65500. offset += 4;
  65501. }
  65502. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65503. offset += 3;
  65504. if (!this._isBillboardBased) {
  65505. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65506. offset += 3;
  65507. }
  65508. if (this._angularSpeedGradientsTexture) {
  65509. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65510. offset += 1;
  65511. }
  65512. else {
  65513. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65514. offset += 2;
  65515. }
  65516. if (this._isAnimationSheetEnabled) {
  65517. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65518. offset += 1;
  65519. if (this.spriteRandomStartCell) {
  65520. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65521. offset += 1;
  65522. }
  65523. }
  65524. if (this.noiseTexture) {
  65525. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65526. offset += 3;
  65527. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65528. offset += 3;
  65529. }
  65530. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65531. this._engine.bindArrayBuffer(null);
  65532. return vao;
  65533. };
  65534. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65535. var renderVertexBuffers = {};
  65536. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65537. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65538. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65539. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65540. var offset = 12;
  65541. if (!this._colorGradientsTexture) {
  65542. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65543. offset += 4;
  65544. }
  65545. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65546. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65547. }
  65548. offset += 3; // Direction
  65549. if (!this._isBillboardBased) {
  65550. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65551. offset += 3;
  65552. }
  65553. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65554. if (this._angularSpeedGradientsTexture) {
  65555. offset++;
  65556. }
  65557. else {
  65558. offset += 2;
  65559. }
  65560. if (this._isAnimationSheetEnabled) {
  65561. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65562. offset += 1;
  65563. if (this.spriteRandomStartCell) {
  65564. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65565. offset += 1;
  65566. }
  65567. }
  65568. if (this.noiseTexture) {
  65569. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65570. offset += 3;
  65571. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65572. offset += 3;
  65573. }
  65574. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65575. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65576. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65577. this._engine.bindArrayBuffer(null);
  65578. return vao;
  65579. };
  65580. GPUParticleSystem.prototype._initialize = function (force) {
  65581. if (force === void 0) { force = false; }
  65582. if (this._buffer0 && !force) {
  65583. return;
  65584. }
  65585. var engine = this._scene.getEngine();
  65586. var data = new Array();
  65587. if (!this.isBillboardBased) {
  65588. this._attributesStrideSize += 3;
  65589. }
  65590. if (this._colorGradientsTexture) {
  65591. this._attributesStrideSize -= 4;
  65592. }
  65593. if (this._angularSpeedGradientsTexture) {
  65594. this._attributesStrideSize -= 1;
  65595. }
  65596. if (this._isAnimationSheetEnabled) {
  65597. this._attributesStrideSize += 1;
  65598. if (this.spriteRandomStartCell) {
  65599. this._attributesStrideSize += 1;
  65600. }
  65601. }
  65602. if (this.noiseTexture) {
  65603. this._attributesStrideSize += 6;
  65604. }
  65605. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65606. // position
  65607. data.push(0.0);
  65608. data.push(0.0);
  65609. data.push(0.0);
  65610. // Age and life
  65611. data.push(0.0); // create the particle as a dead one to create a new one at start
  65612. data.push(0.0);
  65613. // Seed
  65614. data.push(Math.random());
  65615. data.push(Math.random());
  65616. data.push(Math.random());
  65617. data.push(Math.random());
  65618. // Size
  65619. data.push(0.0);
  65620. data.push(0.0);
  65621. data.push(0.0);
  65622. if (!this._colorGradientsTexture) {
  65623. // color
  65624. data.push(0.0);
  65625. data.push(0.0);
  65626. data.push(0.0);
  65627. data.push(0.0);
  65628. }
  65629. // direction
  65630. data.push(0.0);
  65631. data.push(0.0);
  65632. data.push(0.0);
  65633. if (!this.isBillboardBased) {
  65634. // initialDirection
  65635. data.push(0.0);
  65636. data.push(0.0);
  65637. data.push(0.0);
  65638. }
  65639. // angle
  65640. data.push(0.0);
  65641. if (!this._angularSpeedGradientsTexture) {
  65642. data.push(0.0);
  65643. }
  65644. if (this._isAnimationSheetEnabled) {
  65645. data.push(0.0);
  65646. if (this.spriteRandomStartCell) {
  65647. data.push(0.0);
  65648. }
  65649. }
  65650. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65651. data.push(Math.random());
  65652. data.push(Math.random());
  65653. data.push(Math.random());
  65654. data.push(Math.random());
  65655. data.push(Math.random());
  65656. data.push(Math.random());
  65657. }
  65658. }
  65659. // Sprite data
  65660. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65661. -0.5, 0.5, 0, 1,
  65662. -0.5, -0.5, 0, 0,
  65663. 0.5, -0.5, 1, 0]);
  65664. // Buffers
  65665. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65666. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65667. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65668. // Update VAO
  65669. this._updateVAO = [];
  65670. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65671. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65672. // Render VAO
  65673. this._renderVAO = [];
  65674. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65675. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65676. // Links
  65677. this._sourceBuffer = this._buffer0;
  65678. this._targetBuffer = this._buffer1;
  65679. };
  65680. /** @hidden */
  65681. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65682. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65683. if (this._isBillboardBased) {
  65684. defines += "\n#define BILLBOARD";
  65685. }
  65686. if (this._colorGradientsTexture) {
  65687. defines += "\n#define COLORGRADIENTS";
  65688. }
  65689. if (this._sizeGradientsTexture) {
  65690. defines += "\n#define SIZEGRADIENTS";
  65691. }
  65692. if (this._angularSpeedGradientsTexture) {
  65693. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65694. }
  65695. if (this._velocityGradientsTexture) {
  65696. defines += "\n#define VELOCITYGRADIENTS";
  65697. }
  65698. if (this._limitVelocityGradientsTexture) {
  65699. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65700. }
  65701. if (this._dragGradientsTexture) {
  65702. defines += "\n#define DRAGGRADIENTS";
  65703. }
  65704. if (this.isAnimationSheetEnabled) {
  65705. defines += "\n#define ANIMATESHEET";
  65706. if (this.spriteRandomStartCell) {
  65707. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65708. }
  65709. }
  65710. if (this.noiseTexture) {
  65711. defines += "\n#define NOISE";
  65712. }
  65713. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65714. return;
  65715. }
  65716. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65717. if (!this._colorGradientsTexture) {
  65718. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65719. }
  65720. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65721. if (!this._isBillboardBased) {
  65722. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65723. }
  65724. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65725. if (this.isAnimationSheetEnabled) {
  65726. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65727. if (this.spriteRandomStartCell) {
  65728. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65729. }
  65730. }
  65731. if (this.noiseTexture) {
  65732. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65733. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65734. }
  65735. this._updateEffectOptions.defines = defines;
  65736. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65737. };
  65738. /** @hidden */
  65739. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65740. var defines = "";
  65741. if (this._scene.clipPlane) {
  65742. defines = "\n#define CLIPPLANE";
  65743. }
  65744. if (this._scene.clipPlane2) {
  65745. defines = "\n#define CLIPPLANE2";
  65746. }
  65747. if (this._scene.clipPlane3) {
  65748. defines = "\n#define CLIPPLANE3";
  65749. }
  65750. if (this._scene.clipPlane4) {
  65751. defines = "\n#define CLIPPLANE4";
  65752. }
  65753. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  65754. defines = "\n#define BLENDMULTIPLYMODE";
  65755. }
  65756. if (this._isBillboardBased) {
  65757. defines += "\n#define BILLBOARD";
  65758. switch (this.billboardMode) {
  65759. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65760. defines += "\n#define BILLBOARDY";
  65761. break;
  65762. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65763. defines += "\n#define BILLBOARDSTRETCHED";
  65764. break;
  65765. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65766. default:
  65767. break;
  65768. }
  65769. }
  65770. if (this._colorGradientsTexture) {
  65771. defines += "\n#define COLORGRADIENTS";
  65772. }
  65773. if (this.isAnimationSheetEnabled) {
  65774. defines += "\n#define ANIMATESHEET";
  65775. }
  65776. if (this._imageProcessingConfiguration) {
  65777. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65778. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65779. }
  65780. if (this._renderEffect && this._renderEffect.defines === defines) {
  65781. return;
  65782. }
  65783. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65784. var samplers = ["textureSampler", "colorGradientSampler"];
  65785. if (BABYLON.ImageProcessingConfiguration) {
  65786. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65787. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65788. }
  65789. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65790. };
  65791. /**
  65792. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65793. * @param preWarm defines if we are in the pre-warmimg phase
  65794. */
  65795. GPUParticleSystem.prototype.animate = function (preWarm) {
  65796. if (preWarm === void 0) { preWarm = false; }
  65797. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65798. this._actualFrame += this._timeDelta;
  65799. if (!this._stopped) {
  65800. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65801. this.stop();
  65802. }
  65803. }
  65804. };
  65805. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65806. var texture = this[textureName];
  65807. if (!factorGradients || !factorGradients.length || texture) {
  65808. return;
  65809. }
  65810. var data = new Float32Array(this._rawTextureWidth);
  65811. for (var x = 0; x < this._rawTextureWidth; x++) {
  65812. var ratio = x / this._rawTextureWidth;
  65813. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65814. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65815. });
  65816. }
  65817. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65818. };
  65819. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65820. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65821. };
  65822. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65823. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65824. };
  65825. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65826. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65827. };
  65828. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65829. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65830. };
  65831. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65832. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65833. };
  65834. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65835. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65836. return;
  65837. }
  65838. var data = new Uint8Array(this._rawTextureWidth * 4);
  65839. var tmpColor = BABYLON.Tmp.Color4[0];
  65840. for (var x = 0; x < this._rawTextureWidth; x++) {
  65841. var ratio = x / this._rawTextureWidth;
  65842. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65843. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65844. data[x * 4] = tmpColor.r * 255;
  65845. data[x * 4 + 1] = tmpColor.g * 255;
  65846. data[x * 4 + 2] = tmpColor.b * 255;
  65847. data[x * 4 + 3] = tmpColor.a * 255;
  65848. });
  65849. }
  65850. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65851. };
  65852. /**
  65853. * Renders the particle system in its current state
  65854. * @param preWarm defines if the system should only update the particles but not render them
  65855. * @returns the current number of particles
  65856. */
  65857. GPUParticleSystem.prototype.render = function (preWarm) {
  65858. if (preWarm === void 0) { preWarm = false; }
  65859. if (!this._started) {
  65860. return 0;
  65861. }
  65862. this._createColorGradientTexture();
  65863. this._createSizeGradientTexture();
  65864. this._createAngularSpeedGradientTexture();
  65865. this._createVelocityGradientTexture();
  65866. this._createLimitVelocityGradientTexture();
  65867. this._createDragGradientTexture();
  65868. this._recreateUpdateEffect();
  65869. this._recreateRenderEffect();
  65870. if (!this.isReady()) {
  65871. return 0;
  65872. }
  65873. if (!preWarm) {
  65874. if (!this._preWarmDone && this.preWarmCycles) {
  65875. for (var index = 0; index < this.preWarmCycles; index++) {
  65876. this.animate(true);
  65877. this.render(true);
  65878. }
  65879. this._preWarmDone = true;
  65880. }
  65881. if (this._currentRenderId === this._scene.getRenderId()) {
  65882. return 0;
  65883. }
  65884. this._currentRenderId = this._scene.getRenderId();
  65885. }
  65886. // Get everything ready to render
  65887. this._initialize();
  65888. this._accumulatedCount += this.emitRate * this._timeDelta;
  65889. if (this._accumulatedCount > 1) {
  65890. var intPart = this._accumulatedCount | 0;
  65891. this._accumulatedCount -= intPart;
  65892. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65893. }
  65894. if (!this._currentActiveCount) {
  65895. return 0;
  65896. }
  65897. // Enable update effect
  65898. this._engine.enableEffect(this._updateEffect);
  65899. this._engine.setState(false);
  65900. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65901. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65902. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65903. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65904. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65905. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65906. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65907. if (!this._colorGradientsTexture) {
  65908. this._updateEffect.setDirectColor4("color1", this.color1);
  65909. this._updateEffect.setDirectColor4("color2", this.color2);
  65910. }
  65911. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65912. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65913. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65914. this._updateEffect.setVector3("gravity", this.gravity);
  65915. if (this._sizeGradientsTexture) {
  65916. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65917. }
  65918. if (this._angularSpeedGradientsTexture) {
  65919. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65920. }
  65921. if (this._velocityGradientsTexture) {
  65922. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65923. }
  65924. if (this._limitVelocityGradientsTexture) {
  65925. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65926. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65927. }
  65928. if (this._dragGradientsTexture) {
  65929. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65930. }
  65931. if (this.particleEmitterType) {
  65932. this.particleEmitterType.applyToShader(this._updateEffect);
  65933. }
  65934. if (this._isAnimationSheetEnabled) {
  65935. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65936. }
  65937. if (this.noiseTexture) {
  65938. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65939. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65940. }
  65941. var emitterWM;
  65942. if (this.emitter.position) {
  65943. var emitterMesh = this.emitter;
  65944. emitterWM = emitterMesh.getWorldMatrix();
  65945. }
  65946. else {
  65947. var emitterPosition = this.emitter;
  65948. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65949. }
  65950. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65951. // Bind source VAO
  65952. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65953. // Update
  65954. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65955. this._engine.setRasterizerState(false);
  65956. this._engine.beginTransformFeedback(true);
  65957. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65958. this._engine.endTransformFeedback();
  65959. this._engine.setRasterizerState(true);
  65960. this._engine.bindTransformFeedbackBuffer(null);
  65961. if (!preWarm) {
  65962. // Enable render effect
  65963. this._engine.enableEffect(this._renderEffect);
  65964. var viewMatrix = this._scene.getViewMatrix();
  65965. this._renderEffect.setMatrix("view", viewMatrix);
  65966. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65967. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65968. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65969. if (this._colorGradientsTexture) {
  65970. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65971. }
  65972. else {
  65973. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  65974. }
  65975. if (this._isAnimationSheetEnabled && this.particleTexture) {
  65976. var baseSize = this.particleTexture.getBaseSize();
  65977. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  65978. }
  65979. if (this._isBillboardBased) {
  65980. var camera = this._scene.activeCamera;
  65981. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  65982. }
  65983. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  65984. var invView = viewMatrix.clone();
  65985. invView.invert();
  65986. this._renderEffect.setMatrix("invView", invView);
  65987. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  65988. }
  65989. // image processing
  65990. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  65991. this._imageProcessingConfiguration.bind(this._renderEffect);
  65992. }
  65993. // Draw order
  65994. switch (this.blendMode) {
  65995. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  65996. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  65997. break;
  65998. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  65999. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  66000. break;
  66001. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  66002. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66003. break;
  66004. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  66005. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  66006. break;
  66007. }
  66008. if (this.forceDepthWrite) {
  66009. this._engine.setDepthWrite(true);
  66010. }
  66011. // Bind source VAO
  66012. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  66013. // Render
  66014. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  66015. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66016. }
  66017. // Switch VAOs
  66018. this._targetIndex++;
  66019. if (this._targetIndex === 2) {
  66020. this._targetIndex = 0;
  66021. }
  66022. // Switch buffers
  66023. var tmpBuffer = this._sourceBuffer;
  66024. this._sourceBuffer = this._targetBuffer;
  66025. this._targetBuffer = tmpBuffer;
  66026. return this._currentActiveCount;
  66027. };
  66028. /**
  66029. * Rebuilds the particle system
  66030. */
  66031. GPUParticleSystem.prototype.rebuild = function () {
  66032. this._initialize(true);
  66033. };
  66034. GPUParticleSystem.prototype._releaseBuffers = function () {
  66035. if (this._buffer0) {
  66036. this._buffer0.dispose();
  66037. this._buffer0 = null;
  66038. }
  66039. if (this._buffer1) {
  66040. this._buffer1.dispose();
  66041. this._buffer1 = null;
  66042. }
  66043. if (this._spriteBuffer) {
  66044. this._spriteBuffer.dispose();
  66045. this._spriteBuffer = null;
  66046. }
  66047. };
  66048. GPUParticleSystem.prototype._releaseVAOs = function () {
  66049. if (!this._updateVAO) {
  66050. return;
  66051. }
  66052. for (var index = 0; index < this._updateVAO.length; index++) {
  66053. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66054. }
  66055. this._updateVAO = [];
  66056. for (var index = 0; index < this._renderVAO.length; index++) {
  66057. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66058. }
  66059. this._renderVAO = [];
  66060. };
  66061. /**
  66062. * Disposes the particle system and free the associated resources
  66063. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66064. */
  66065. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66066. if (disposeTexture === void 0) { disposeTexture = true; }
  66067. var index = this._scene.particleSystems.indexOf(this);
  66068. if (index > -1) {
  66069. this._scene.particleSystems.splice(index, 1);
  66070. }
  66071. this._releaseBuffers();
  66072. this._releaseVAOs();
  66073. if (this._colorGradientsTexture) {
  66074. this._colorGradientsTexture.dispose();
  66075. this._colorGradientsTexture = null;
  66076. }
  66077. if (this._sizeGradientsTexture) {
  66078. this._sizeGradientsTexture.dispose();
  66079. this._sizeGradientsTexture = null;
  66080. }
  66081. if (this._angularSpeedGradientsTexture) {
  66082. this._angularSpeedGradientsTexture.dispose();
  66083. this._angularSpeedGradientsTexture = null;
  66084. }
  66085. if (this._velocityGradientsTexture) {
  66086. this._velocityGradientsTexture.dispose();
  66087. this._velocityGradientsTexture = null;
  66088. }
  66089. if (this._limitVelocityGradientsTexture) {
  66090. this._limitVelocityGradientsTexture.dispose();
  66091. this._limitVelocityGradientsTexture = null;
  66092. }
  66093. if (this._dragGradientsTexture) {
  66094. this._dragGradientsTexture.dispose();
  66095. this._dragGradientsTexture = null;
  66096. }
  66097. if (this._randomTexture) {
  66098. this._randomTexture.dispose();
  66099. this._randomTexture = null;
  66100. }
  66101. if (this._randomTexture2) {
  66102. this._randomTexture2.dispose();
  66103. this._randomTexture2 = null;
  66104. }
  66105. if (disposeTexture && this.particleTexture) {
  66106. this.particleTexture.dispose();
  66107. this.particleTexture = null;
  66108. }
  66109. if (disposeTexture && this.noiseTexture) {
  66110. this.noiseTexture.dispose();
  66111. this.noiseTexture = null;
  66112. }
  66113. // Callback
  66114. this.onDisposeObservable.notifyObservers(this);
  66115. this.onDisposeObservable.clear();
  66116. };
  66117. /**
  66118. * Clones the particle system.
  66119. * @param name The name of the cloned object
  66120. * @param newEmitter The new emitter to use
  66121. * @returns the cloned particle system
  66122. */
  66123. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66124. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66125. BABYLON.Tools.DeepCopy(this, result);
  66126. if (newEmitter === undefined) {
  66127. newEmitter = this.emitter;
  66128. }
  66129. result.emitter = newEmitter;
  66130. if (this.particleTexture) {
  66131. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66132. }
  66133. return result;
  66134. };
  66135. /**
  66136. * Serializes the particle system to a JSON object.
  66137. * @returns the JSON object
  66138. */
  66139. GPUParticleSystem.prototype.serialize = function () {
  66140. var serializationObject = {};
  66141. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66142. serializationObject.activeParticleCount = this.activeParticleCount;
  66143. return serializationObject;
  66144. };
  66145. /**
  66146. * Parses a JSON object to create a GPU particle system.
  66147. * @param parsedParticleSystem The JSON object to parse
  66148. * @param scene The scene to create the particle system in
  66149. * @param rootUrl The root url to use to load external dependencies like texture
  66150. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66151. * @returns the parsed GPU particle system
  66152. */
  66153. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66154. if (doNotStart === void 0) { doNotStart = false; }
  66155. var name = parsedParticleSystem.name;
  66156. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66157. if (parsedParticleSystem.activeParticleCount) {
  66158. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66159. }
  66160. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66161. // Auto start
  66162. if (parsedParticleSystem.preventAutoStart) {
  66163. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66164. }
  66165. if (!doNotStart && !particleSystem.preventAutoStart) {
  66166. particleSystem.start();
  66167. }
  66168. return particleSystem;
  66169. };
  66170. return GPUParticleSystem;
  66171. }(BABYLON.BaseParticleSystem));
  66172. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66173. })(BABYLON || (BABYLON = {}));
  66174. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66175. var BABYLON;
  66176. (function (BABYLON) {
  66177. /**
  66178. * Represents one particle of a solid particle system.
  66179. */
  66180. var SolidParticle = /** @class */ (function () {
  66181. /**
  66182. * Creates a Solid Particle object.
  66183. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66184. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66185. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66186. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66187. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66188. * @param shapeId (integer) is the model shape identifier in the SPS.
  66189. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66190. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66191. */
  66192. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66193. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66194. /**
  66195. * particle global index
  66196. */
  66197. this.idx = 0;
  66198. /**
  66199. * The color of the particle
  66200. */
  66201. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66202. /**
  66203. * The world space position of the particle.
  66204. */
  66205. this.position = BABYLON.Vector3.Zero();
  66206. /**
  66207. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66208. */
  66209. this.rotation = BABYLON.Vector3.Zero();
  66210. /**
  66211. * The scaling of the particle.
  66212. */
  66213. this.scaling = BABYLON.Vector3.One();
  66214. /**
  66215. * The uvs of the particle.
  66216. */
  66217. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66218. /**
  66219. * The current speed of the particle.
  66220. */
  66221. this.velocity = BABYLON.Vector3.Zero();
  66222. /**
  66223. * The pivot point in the particle local space.
  66224. */
  66225. this.pivot = BABYLON.Vector3.Zero();
  66226. /**
  66227. * Must the particle be translated from its pivot point in its local space ?
  66228. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66229. * Default : false
  66230. */
  66231. this.translateFromPivot = false;
  66232. /**
  66233. * Is the particle active or not ?
  66234. */
  66235. this.alive = true;
  66236. /**
  66237. * Is the particle visible or not ?
  66238. */
  66239. this.isVisible = true;
  66240. /**
  66241. * Index of this particle in the global "positions" array (Internal use)
  66242. * @hidden
  66243. */
  66244. this._pos = 0;
  66245. /**
  66246. * @hidden Index of this particle in the global "indices" array (Internal use)
  66247. */
  66248. this._ind = 0;
  66249. /**
  66250. * ModelShape id of this particle
  66251. */
  66252. this.shapeId = 0;
  66253. /**
  66254. * Index of the particle in its shape id (Internal use)
  66255. */
  66256. this.idxInShape = 0;
  66257. /**
  66258. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66259. */
  66260. this._stillInvisible = false;
  66261. /**
  66262. * @hidden Last computed particle rotation matrix
  66263. */
  66264. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66265. /**
  66266. * Parent particle Id, if any.
  66267. * Default null.
  66268. */
  66269. this.parentId = null;
  66270. /**
  66271. * @hidden Internal global position in the SPS.
  66272. */
  66273. this._globalPosition = BABYLON.Vector3.Zero();
  66274. this.idx = particleIndex;
  66275. this._pos = positionIndex;
  66276. this._ind = indiceIndex;
  66277. this._model = model;
  66278. this.shapeId = shapeId;
  66279. this.idxInShape = idxInShape;
  66280. this._sps = sps;
  66281. if (modelBoundingInfo) {
  66282. this._modelBoundingInfo = modelBoundingInfo;
  66283. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66284. }
  66285. }
  66286. Object.defineProperty(SolidParticle.prototype, "scale", {
  66287. /**
  66288. * Legacy support, changed scale to scaling
  66289. */
  66290. get: function () {
  66291. return this.scaling;
  66292. },
  66293. /**
  66294. * Legacy support, changed scale to scaling
  66295. */
  66296. set: function (scale) {
  66297. this.scaling = scale;
  66298. },
  66299. enumerable: true,
  66300. configurable: true
  66301. });
  66302. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66303. /**
  66304. * Legacy support, changed quaternion to rotationQuaternion
  66305. */
  66306. get: function () {
  66307. return this.rotationQuaternion;
  66308. },
  66309. /**
  66310. * Legacy support, changed quaternion to rotationQuaternion
  66311. */
  66312. set: function (q) {
  66313. this.rotationQuaternion = q;
  66314. },
  66315. enumerable: true,
  66316. configurable: true
  66317. });
  66318. /**
  66319. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66320. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66321. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66322. * @returns true if it intersects
  66323. */
  66324. SolidParticle.prototype.intersectsMesh = function (target) {
  66325. if (!this._boundingInfo || !target._boundingInfo) {
  66326. return false;
  66327. }
  66328. if (this._sps._bSphereOnly) {
  66329. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66330. }
  66331. return this._boundingInfo.intersects(target._boundingInfo, false);
  66332. };
  66333. return SolidParticle;
  66334. }());
  66335. BABYLON.SolidParticle = SolidParticle;
  66336. /**
  66337. * Represents the shape of the model used by one particle of a solid particle system.
  66338. * SPS internal tool, don't use it manually.
  66339. */
  66340. var ModelShape = /** @class */ (function () {
  66341. /**
  66342. * 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.
  66343. * SPS internal tool, don't use it manually.
  66344. * @hidden
  66345. */
  66346. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66347. /**
  66348. * length of the shape in the model indices array (internal use)
  66349. * @hidden
  66350. */
  66351. this._indicesLength = 0;
  66352. this.shapeID = id;
  66353. this._shape = shape;
  66354. this._indicesLength = indicesLength;
  66355. this._shapeUV = shapeUV;
  66356. this._positionFunction = posFunction;
  66357. this._vertexFunction = vtxFunction;
  66358. }
  66359. return ModelShape;
  66360. }());
  66361. BABYLON.ModelShape = ModelShape;
  66362. /**
  66363. * Represents a Depth Sorted Particle in the solid particle system.
  66364. */
  66365. var DepthSortedParticle = /** @class */ (function () {
  66366. function DepthSortedParticle() {
  66367. /**
  66368. * Index of the particle in the "indices" array
  66369. */
  66370. this.ind = 0;
  66371. /**
  66372. * Length of the particle shape in the "indices" array
  66373. */
  66374. this.indicesLength = 0;
  66375. /**
  66376. * Squared distance from the particle to the camera
  66377. */
  66378. this.sqDistance = 0.0;
  66379. }
  66380. return DepthSortedParticle;
  66381. }());
  66382. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66383. })(BABYLON || (BABYLON = {}));
  66384. //# sourceMappingURL=babylon.solidParticle.js.map
  66385. var BABYLON;
  66386. (function (BABYLON) {
  66387. /**
  66388. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66389. *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.
  66390. * The SPS is also a particle system. It provides some methods to manage the particles.
  66391. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66392. *
  66393. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66394. */
  66395. var SolidParticleSystem = /** @class */ (function () {
  66396. /**
  66397. * Creates a SPS (Solid Particle System) object.
  66398. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66399. * @param scene (Scene) is the scene in which the SPS is added.
  66400. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66401. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66402. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66403. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66404. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66405. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66406. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66407. */
  66408. function SolidParticleSystem(name, scene, options) {
  66409. /**
  66410. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66411. * Example : var p = SPS.particles[i];
  66412. */
  66413. this.particles = new Array();
  66414. /**
  66415. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66416. */
  66417. this.nbParticles = 0;
  66418. /**
  66419. * If the particles must ever face the camera (default false). Useful for planar particles.
  66420. */
  66421. this.billboard = false;
  66422. /**
  66423. * Recompute normals when adding a shape
  66424. */
  66425. this.recomputeNormals = true;
  66426. /**
  66427. * This a counter ofr your own usage. It's not set by any SPS functions.
  66428. */
  66429. this.counter = 0;
  66430. /**
  66431. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66432. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66433. */
  66434. this.vars = {};
  66435. /**
  66436. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66437. * @hidden
  66438. */
  66439. this._bSphereOnly = false;
  66440. /**
  66441. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66442. * @hidden
  66443. */
  66444. this._bSphereRadiusFactor = 1.0;
  66445. this._positions = new Array();
  66446. this._indices = new Array();
  66447. this._normals = new Array();
  66448. this._colors = new Array();
  66449. this._uvs = new Array();
  66450. this._index = 0; // indices index
  66451. this._updatable = true;
  66452. this._pickable = false;
  66453. this._isVisibilityBoxLocked = false;
  66454. this._alwaysVisible = false;
  66455. this._depthSort = false;
  66456. this._shapeCounter = 0;
  66457. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66458. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66459. this._computeParticleColor = true;
  66460. this._computeParticleTexture = true;
  66461. this._computeParticleRotation = true;
  66462. this._computeParticleVertex = false;
  66463. this._computeBoundingBox = false;
  66464. this._depthSortParticles = true;
  66465. this._cam_axisZ = BABYLON.Vector3.Zero();
  66466. this._cam_axisY = BABYLON.Vector3.Zero();
  66467. this._cam_axisX = BABYLON.Vector3.Zero();
  66468. this._axisZ = BABYLON.Axis.Z;
  66469. this._camDir = BABYLON.Vector3.Zero();
  66470. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66471. this._rotMatrix = new BABYLON.Matrix();
  66472. this._invertMatrix = new BABYLON.Matrix();
  66473. this._rotated = BABYLON.Vector3.Zero();
  66474. this._quaternion = new BABYLON.Quaternion();
  66475. this._vertex = BABYLON.Vector3.Zero();
  66476. this._normal = BABYLON.Vector3.Zero();
  66477. this._yaw = 0.0;
  66478. this._pitch = 0.0;
  66479. this._roll = 0.0;
  66480. this._halfroll = 0.0;
  66481. this._halfpitch = 0.0;
  66482. this._halfyaw = 0.0;
  66483. this._sinRoll = 0.0;
  66484. this._cosRoll = 0.0;
  66485. this._sinPitch = 0.0;
  66486. this._cosPitch = 0.0;
  66487. this._sinYaw = 0.0;
  66488. this._cosYaw = 0.0;
  66489. this._mustUnrotateFixedNormals = false;
  66490. this._minimum = BABYLON.Vector3.Zero();
  66491. this._maximum = BABYLON.Vector3.Zero();
  66492. this._minBbox = BABYLON.Vector3.Zero();
  66493. this._maxBbox = BABYLON.Vector3.Zero();
  66494. this._particlesIntersect = false;
  66495. this._depthSortFunction = function (p1, p2) {
  66496. return (p2.sqDistance - p1.sqDistance);
  66497. };
  66498. this._needs32Bits = false;
  66499. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66500. this._scaledPivot = BABYLON.Vector3.Zero();
  66501. this._particleHasParent = false;
  66502. this.name = name;
  66503. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66504. this._camera = scene.activeCamera;
  66505. this._pickable = options ? options.isPickable : false;
  66506. this._depthSort = options ? options.enableDepthSort : false;
  66507. this._particlesIntersect = options ? options.particleIntersection : false;
  66508. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66509. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66510. if (options && options.updatable !== undefined) {
  66511. this._updatable = options.updatable;
  66512. }
  66513. else {
  66514. this._updatable = true;
  66515. }
  66516. if (this._pickable) {
  66517. this.pickedParticles = [];
  66518. }
  66519. if (this._depthSort) {
  66520. this.depthSortedParticles = [];
  66521. }
  66522. }
  66523. /**
  66524. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66525. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66526. * @returns the created mesh
  66527. */
  66528. SolidParticleSystem.prototype.buildMesh = function () {
  66529. if (this.nbParticles === 0) {
  66530. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66531. this.addShape(triangle, 1);
  66532. triangle.dispose();
  66533. }
  66534. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66535. this._positions32 = new Float32Array(this._positions);
  66536. this._uvs32 = new Float32Array(this._uvs);
  66537. this._colors32 = new Float32Array(this._colors);
  66538. if (this.recomputeNormals) {
  66539. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66540. }
  66541. this._normals32 = new Float32Array(this._normals);
  66542. this._fixedNormal32 = new Float32Array(this._normals);
  66543. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66544. this._unrotateFixedNormals();
  66545. }
  66546. var vertexData = new BABYLON.VertexData();
  66547. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66548. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66549. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66550. if (this._uvs32.length > 0) {
  66551. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66552. }
  66553. if (this._colors32.length > 0) {
  66554. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66555. }
  66556. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66557. vertexData.applyToMesh(mesh, this._updatable);
  66558. this.mesh = mesh;
  66559. this.mesh.isPickable = this._pickable;
  66560. // free memory
  66561. if (!this._depthSort) {
  66562. this._indices = null;
  66563. }
  66564. this._positions = null;
  66565. this._normals = null;
  66566. this._uvs = null;
  66567. this._colors = null;
  66568. if (!this._updatable) {
  66569. this.particles.length = 0;
  66570. }
  66571. return mesh;
  66572. };
  66573. /**
  66574. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66575. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66576. * Thus the particles generated from `digest()` have their property `position` set yet.
  66577. * @param mesh ( Mesh ) is the mesh to be digested
  66578. * @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
  66579. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66580. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66581. * @returns the current SPS
  66582. */
  66583. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66584. var size = (options && options.facetNb) || 1;
  66585. var number = (options && options.number) || 0;
  66586. var delta = (options && options.delta) || 0;
  66587. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66588. var meshInd = mesh.getIndices();
  66589. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66590. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66591. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66592. var f = 0; // facet counter
  66593. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66594. // compute size from number
  66595. if (number) {
  66596. number = (number > totalFacets) ? totalFacets : number;
  66597. size = Math.round(totalFacets / number);
  66598. delta = 0;
  66599. }
  66600. else {
  66601. size = (size > totalFacets) ? totalFacets : size;
  66602. }
  66603. var facetPos = []; // submesh positions
  66604. var facetInd = []; // submesh indices
  66605. var facetUV = []; // submesh UV
  66606. var facetCol = []; // submesh colors
  66607. var barycenter = BABYLON.Vector3.Zero();
  66608. var sizeO = size;
  66609. while (f < totalFacets) {
  66610. size = sizeO + Math.floor((1 + delta) * Math.random());
  66611. if (f > totalFacets - size) {
  66612. size = totalFacets - f;
  66613. }
  66614. // reset temp arrays
  66615. facetPos.length = 0;
  66616. facetInd.length = 0;
  66617. facetUV.length = 0;
  66618. facetCol.length = 0;
  66619. // iterate over "size" facets
  66620. var fi = 0;
  66621. for (var j = f * 3; j < (f + size) * 3; j++) {
  66622. facetInd.push(fi);
  66623. var i = meshInd[j];
  66624. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66625. if (meshUV) {
  66626. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66627. }
  66628. if (meshCol) {
  66629. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66630. }
  66631. fi++;
  66632. }
  66633. // create a model shape for each single particle
  66634. var idx = this.nbParticles;
  66635. var shape = this._posToShape(facetPos);
  66636. var shapeUV = this._uvsToShapeUV(facetUV);
  66637. // compute the barycenter of the shape
  66638. var v;
  66639. for (v = 0; v < shape.length; v++) {
  66640. barycenter.addInPlace(shape[v]);
  66641. }
  66642. barycenter.scaleInPlace(1 / shape.length);
  66643. // shift the shape from its barycenter to the origin
  66644. for (v = 0; v < shape.length; v++) {
  66645. shape[v].subtractInPlace(barycenter);
  66646. }
  66647. var bInfo;
  66648. if (this._particlesIntersect) {
  66649. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66650. }
  66651. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66652. // add the particle in the SPS
  66653. var currentPos = this._positions.length;
  66654. var currentInd = this._indices.length;
  66655. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66656. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66657. // initialize the particle position
  66658. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66659. this._index += shape.length;
  66660. idx++;
  66661. this.nbParticles++;
  66662. this._shapeCounter++;
  66663. f += size;
  66664. }
  66665. return this;
  66666. };
  66667. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66668. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66669. var index = 0;
  66670. var idx = 0;
  66671. for (var p = 0; p < this.particles.length; p++) {
  66672. this._particle = this.particles[p];
  66673. this._shape = this._particle._model._shape;
  66674. if (this._particle.rotationQuaternion) {
  66675. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66676. }
  66677. else {
  66678. this._yaw = this._particle.rotation.y;
  66679. this._pitch = this._particle.rotation.x;
  66680. this._roll = this._particle.rotation.z;
  66681. this._quaternionRotationYPR();
  66682. }
  66683. this._quaternionToRotationMatrix();
  66684. this._rotMatrix.invertToRef(this._invertMatrix);
  66685. for (var pt = 0; pt < this._shape.length; pt++) {
  66686. idx = index + pt * 3;
  66687. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66688. this._fixedNormal32[idx] = this._normal.x;
  66689. this._fixedNormal32[idx + 1] = this._normal.y;
  66690. this._fixedNormal32[idx + 2] = this._normal.z;
  66691. }
  66692. index = idx + 3;
  66693. }
  66694. };
  66695. //reset copy
  66696. SolidParticleSystem.prototype._resetCopy = function () {
  66697. this._copy.position.x = 0;
  66698. this._copy.position.y = 0;
  66699. this._copy.position.z = 0;
  66700. this._copy.rotation.x = 0;
  66701. this._copy.rotation.y = 0;
  66702. this._copy.rotation.z = 0;
  66703. this._copy.rotationQuaternion = null;
  66704. this._copy.scaling.x = 1.0;
  66705. this._copy.scaling.y = 1.0;
  66706. this._copy.scaling.z = 1.0;
  66707. this._copy.uvs.x = 0;
  66708. this._copy.uvs.y = 0;
  66709. this._copy.uvs.z = 1.0;
  66710. this._copy.uvs.w = 1.0;
  66711. this._copy.color = null;
  66712. this._copy.translateFromPivot = false;
  66713. };
  66714. // _meshBuilder : inserts the shape model in the global SPS mesh
  66715. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66716. var i;
  66717. var u = 0;
  66718. var c = 0;
  66719. var n = 0;
  66720. this._resetCopy();
  66721. if (options && options.positionFunction) { // call to custom positionFunction
  66722. options.positionFunction(this._copy, idx, idxInShape);
  66723. this._mustUnrotateFixedNormals = true;
  66724. }
  66725. if (this._copy.rotationQuaternion) {
  66726. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66727. }
  66728. else {
  66729. this._yaw = this._copy.rotation.y;
  66730. this._pitch = this._copy.rotation.x;
  66731. this._roll = this._copy.rotation.z;
  66732. this._quaternionRotationYPR();
  66733. }
  66734. this._quaternionToRotationMatrix();
  66735. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66736. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66737. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66738. if (this._copy.translateFromPivot) {
  66739. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66740. }
  66741. else {
  66742. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66743. }
  66744. for (i = 0; i < shape.length; i++) {
  66745. this._vertex.x = shape[i].x;
  66746. this._vertex.y = shape[i].y;
  66747. this._vertex.z = shape[i].z;
  66748. if (options && options.vertexFunction) {
  66749. options.vertexFunction(this._copy, this._vertex, i);
  66750. }
  66751. this._vertex.x *= this._copy.scaling.x;
  66752. this._vertex.y *= this._copy.scaling.y;
  66753. this._vertex.z *= this._copy.scaling.z;
  66754. this._vertex.x -= this._scaledPivot.x;
  66755. this._vertex.y -= this._scaledPivot.y;
  66756. this._vertex.z -= this._scaledPivot.z;
  66757. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66758. this._rotated.addInPlace(this._pivotBackTranslation);
  66759. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66760. if (meshUV) {
  66761. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  66762. u += 2;
  66763. }
  66764. if (this._copy.color) {
  66765. this._color = this._copy.color;
  66766. }
  66767. else if (meshCol && meshCol[c] !== undefined) {
  66768. this._color.r = meshCol[c];
  66769. this._color.g = meshCol[c + 1];
  66770. this._color.b = meshCol[c + 2];
  66771. this._color.a = meshCol[c + 3];
  66772. }
  66773. else {
  66774. this._color.r = 1.0;
  66775. this._color.g = 1.0;
  66776. this._color.b = 1.0;
  66777. this._color.a = 1.0;
  66778. }
  66779. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66780. c += 4;
  66781. if (!this.recomputeNormals && meshNor) {
  66782. this._normal.x = meshNor[n];
  66783. this._normal.y = meshNor[n + 1];
  66784. this._normal.z = meshNor[n + 2];
  66785. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66786. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66787. n += 3;
  66788. }
  66789. }
  66790. for (i = 0; i < meshInd.length; i++) {
  66791. var current_ind = p + meshInd[i];
  66792. indices.push(current_ind);
  66793. if (current_ind > 65535) {
  66794. this._needs32Bits = true;
  66795. }
  66796. }
  66797. if (this._pickable) {
  66798. var nbfaces = meshInd.length / 3;
  66799. for (i = 0; i < nbfaces; i++) {
  66800. this.pickedParticles.push({ idx: idx, faceId: i });
  66801. }
  66802. }
  66803. if (this._depthSort) {
  66804. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66805. }
  66806. return this._copy;
  66807. };
  66808. // returns a shape array from positions array
  66809. SolidParticleSystem.prototype._posToShape = function (positions) {
  66810. var shape = [];
  66811. for (var i = 0; i < positions.length; i += 3) {
  66812. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66813. }
  66814. return shape;
  66815. };
  66816. // returns a shapeUV array from a Vector4 uvs
  66817. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66818. var shapeUV = [];
  66819. if (uvs) {
  66820. for (var i = 0; i < uvs.length; i++)
  66821. shapeUV.push(uvs[i]);
  66822. }
  66823. return shapeUV;
  66824. };
  66825. // adds a new particle object in the particles array
  66826. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66827. if (bInfo === void 0) { bInfo = null; }
  66828. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66829. this.particles.push(sp);
  66830. return sp;
  66831. };
  66832. /**
  66833. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66834. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66835. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66836. * @param nb (positive integer) the number of particles to be created from this model
  66837. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66838. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66839. * @returns the number of shapes in the system
  66840. */
  66841. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66842. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66843. var meshInd = mesh.getIndices();
  66844. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66845. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66846. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66847. var bbInfo;
  66848. if (this._particlesIntersect) {
  66849. bbInfo = mesh.getBoundingInfo();
  66850. }
  66851. var shape = this._posToShape(meshPos);
  66852. var shapeUV = this._uvsToShapeUV(meshUV);
  66853. var posfunc = options ? options.positionFunction : null;
  66854. var vtxfunc = options ? options.vertexFunction : null;
  66855. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66856. // particles
  66857. var sp;
  66858. var currentCopy;
  66859. var idx = this.nbParticles;
  66860. for (var i = 0; i < nb; i++) {
  66861. var currentPos = this._positions.length;
  66862. var currentInd = this._indices.length;
  66863. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66864. if (this._updatable) {
  66865. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66866. sp.position.copyFrom(currentCopy.position);
  66867. sp.rotation.copyFrom(currentCopy.rotation);
  66868. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66869. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66870. }
  66871. if (currentCopy.color && sp.color) {
  66872. sp.color.copyFrom(currentCopy.color);
  66873. }
  66874. sp.scaling.copyFrom(currentCopy.scaling);
  66875. sp.uvs.copyFrom(currentCopy.uvs);
  66876. }
  66877. this._index += shape.length;
  66878. idx++;
  66879. }
  66880. this.nbParticles += nb;
  66881. this._shapeCounter++;
  66882. return this._shapeCounter - 1;
  66883. };
  66884. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66885. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66886. this._resetCopy();
  66887. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66888. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66889. }
  66890. if (this._copy.rotationQuaternion) {
  66891. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66892. }
  66893. else {
  66894. this._yaw = this._copy.rotation.y;
  66895. this._pitch = this._copy.rotation.x;
  66896. this._roll = this._copy.rotation.z;
  66897. this._quaternionRotationYPR();
  66898. }
  66899. this._quaternionToRotationMatrix();
  66900. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66901. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66902. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66903. if (this._copy.translateFromPivot) {
  66904. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66905. }
  66906. else {
  66907. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66908. }
  66909. this._shape = particle._model._shape;
  66910. for (var pt = 0; pt < this._shape.length; pt++) {
  66911. this._vertex.x = this._shape[pt].x;
  66912. this._vertex.y = this._shape[pt].y;
  66913. this._vertex.z = this._shape[pt].z;
  66914. if (particle._model._vertexFunction) {
  66915. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66916. }
  66917. this._vertex.x *= this._copy.scaling.x;
  66918. this._vertex.y *= this._copy.scaling.y;
  66919. this._vertex.z *= this._copy.scaling.z;
  66920. this._vertex.x -= this._scaledPivot.x;
  66921. this._vertex.y -= this._scaledPivot.y;
  66922. this._vertex.z -= this._scaledPivot.z;
  66923. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66924. this._rotated.addInPlace(this._pivotBackTranslation);
  66925. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66926. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66927. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66928. }
  66929. particle.position.x = 0.0;
  66930. particle.position.y = 0.0;
  66931. particle.position.z = 0.0;
  66932. particle.rotation.x = 0.0;
  66933. particle.rotation.y = 0.0;
  66934. particle.rotation.z = 0.0;
  66935. particle.rotationQuaternion = null;
  66936. particle.scaling.x = 1.0;
  66937. particle.scaling.y = 1.0;
  66938. particle.scaling.z = 1.0;
  66939. particle.uvs.x = 0.0;
  66940. particle.uvs.y = 0.0;
  66941. particle.uvs.z = 1.0;
  66942. particle.uvs.w = 1.0;
  66943. particle.pivot.x = 0.0;
  66944. particle.pivot.y = 0.0;
  66945. particle.pivot.z = 0.0;
  66946. particle.translateFromPivot = false;
  66947. particle.parentId = null;
  66948. };
  66949. /**
  66950. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66951. * @returns the SPS.
  66952. */
  66953. SolidParticleSystem.prototype.rebuildMesh = function () {
  66954. for (var p = 0; p < this.particles.length; p++) {
  66955. this._rebuildParticle(this.particles[p]);
  66956. }
  66957. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66958. return this;
  66959. };
  66960. /**
  66961. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66962. * This method calls `updateParticle()` for each particle of the SPS.
  66963. * For an animated SPS, it is usually called within the render loop.
  66964. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66965. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66966. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66967. * @returns the SPS.
  66968. */
  66969. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66970. if (start === void 0) { start = 0; }
  66971. if (end === void 0) { end = this.nbParticles - 1; }
  66972. if (update === void 0) { update = true; }
  66973. if (!this._updatable) {
  66974. return this;
  66975. }
  66976. // custom beforeUpdate
  66977. this.beforeUpdateParticles(start, end, update);
  66978. this._cam_axisX.x = 1.0;
  66979. this._cam_axisX.y = 0.0;
  66980. this._cam_axisX.z = 0.0;
  66981. this._cam_axisY.x = 0.0;
  66982. this._cam_axisY.y = 1.0;
  66983. this._cam_axisY.z = 0.0;
  66984. this._cam_axisZ.x = 0.0;
  66985. this._cam_axisZ.y = 0.0;
  66986. this._cam_axisZ.z = 1.0;
  66987. // cases when the World Matrix is to be computed first
  66988. if (this.billboard || this._depthSort) {
  66989. this.mesh.computeWorldMatrix(true);
  66990. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  66991. }
  66992. // if the particles will always face the camera
  66993. if (this.billboard) {
  66994. // compute the camera position and un-rotate it by the current mesh rotation
  66995. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  66996. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  66997. this._cam_axisZ.normalize();
  66998. // same for camera up vector extracted from the cam view matrix
  66999. var view = this._camera.getViewMatrix(true);
  67000. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  67001. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  67002. this._cam_axisY.normalize();
  67003. this._cam_axisX.normalize();
  67004. }
  67005. // if depthSort, compute the camera global position in the mesh local system
  67006. if (this._depthSort) {
  67007. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  67008. }
  67009. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  67010. var idx = 0; // current position index in the global array positions32
  67011. var index = 0; // position start index in the global array positions32 of the current particle
  67012. var colidx = 0; // current color index in the global array colors32
  67013. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  67014. var uvidx = 0; // current uv index in the global array uvs32
  67015. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  67016. var pt = 0; // current index in the particle model shape
  67017. if (this.mesh.isFacetDataEnabled) {
  67018. this._computeBoundingBox = true;
  67019. }
  67020. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  67021. if (this._computeBoundingBox) {
  67022. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  67023. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  67024. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  67025. }
  67026. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  67027. if (this.mesh._boundingInfo) {
  67028. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  67029. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  67030. }
  67031. }
  67032. }
  67033. // particle loop
  67034. index = this.particles[start]._pos;
  67035. var vpos = (index / 3) | 0;
  67036. colorIndex = vpos * 4;
  67037. uvIndex = vpos * 2;
  67038. for (var p = start; p <= end; p++) {
  67039. this._particle = this.particles[p];
  67040. this._shape = this._particle._model._shape;
  67041. this._shapeUV = this._particle._model._shapeUV;
  67042. // call to custom user function to update the particle properties
  67043. this.updateParticle(this._particle);
  67044. // camera-particle distance for depth sorting
  67045. if (this._depthSort && this._depthSortParticles) {
  67046. var dsp = this.depthSortedParticles[p];
  67047. dsp.ind = this._particle._ind;
  67048. dsp.indicesLength = this._particle._model._indicesLength;
  67049. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67050. }
  67051. // skip the computations for inactive or already invisible particles
  67052. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67053. // increment indexes for the next particle
  67054. pt = this._shape.length;
  67055. index += pt * 3;
  67056. colorIndex += pt * 4;
  67057. uvIndex += pt * 2;
  67058. continue;
  67059. }
  67060. if (this._particle.isVisible) {
  67061. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67062. this._particleHasParent = (this._particle.parentId !== null);
  67063. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67064. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67065. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67066. // particle rotation matrix
  67067. if (this.billboard) {
  67068. this._particle.rotation.x = 0.0;
  67069. this._particle.rotation.y = 0.0;
  67070. }
  67071. if (this._computeParticleRotation || this.billboard) {
  67072. if (this._particle.rotationQuaternion) {
  67073. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67074. }
  67075. else {
  67076. this._yaw = this._particle.rotation.y;
  67077. this._pitch = this._particle.rotation.x;
  67078. this._roll = this._particle.rotation.z;
  67079. this._quaternionRotationYPR();
  67080. }
  67081. this._quaternionToRotationMatrix();
  67082. }
  67083. if (this._particleHasParent) {
  67084. this._parent = this.particles[this._particle.parentId];
  67085. this._rotated.x = this._particle.position.x * this._parent._rotationMatrix[0] + this._particle.position.y * this._parent._rotationMatrix[3] + this._particle.position.z * this._parent._rotationMatrix[6];
  67086. this._rotated.y = this._particle.position.x * this._parent._rotationMatrix[1] + this._particle.position.y * this._parent._rotationMatrix[4] + this._particle.position.z * this._parent._rotationMatrix[7];
  67087. this._rotated.z = this._particle.position.x * this._parent._rotationMatrix[2] + this._particle.position.y * this._parent._rotationMatrix[5] + this._particle.position.z * this._parent._rotationMatrix[8];
  67088. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67089. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67090. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67091. if (this._computeParticleRotation || this.billboard) {
  67092. this._particle._rotationMatrix[0] = this._rotMatrix.m[0] * this._parent._rotationMatrix[0] + this._rotMatrix.m[1] * this._parent._rotationMatrix[3] + this._rotMatrix.m[2] * this._parent._rotationMatrix[6];
  67093. this._particle._rotationMatrix[1] = this._rotMatrix.m[0] * this._parent._rotationMatrix[1] + this._rotMatrix.m[1] * this._parent._rotationMatrix[4] + this._rotMatrix.m[2] * this._parent._rotationMatrix[7];
  67094. this._particle._rotationMatrix[2] = this._rotMatrix.m[0] * this._parent._rotationMatrix[2] + this._rotMatrix.m[1] * this._parent._rotationMatrix[5] + this._rotMatrix.m[2] * this._parent._rotationMatrix[8];
  67095. this._particle._rotationMatrix[3] = this._rotMatrix.m[4] * this._parent._rotationMatrix[0] + this._rotMatrix.m[5] * this._parent._rotationMatrix[3] + this._rotMatrix.m[6] * this._parent._rotationMatrix[6];
  67096. this._particle._rotationMatrix[4] = this._rotMatrix.m[4] * this._parent._rotationMatrix[1] + this._rotMatrix.m[5] * this._parent._rotationMatrix[4] + this._rotMatrix.m[6] * this._parent._rotationMatrix[7];
  67097. this._particle._rotationMatrix[5] = this._rotMatrix.m[4] * this._parent._rotationMatrix[2] + this._rotMatrix.m[5] * this._parent._rotationMatrix[5] + this._rotMatrix.m[6] * this._parent._rotationMatrix[8];
  67098. this._particle._rotationMatrix[6] = this._rotMatrix.m[8] * this._parent._rotationMatrix[0] + this._rotMatrix.m[9] * this._parent._rotationMatrix[3] + this._rotMatrix.m[10] * this._parent._rotationMatrix[6];
  67099. this._particle._rotationMatrix[7] = this._rotMatrix.m[8] * this._parent._rotationMatrix[1] + this._rotMatrix.m[9] * this._parent._rotationMatrix[4] + this._rotMatrix.m[10] * this._parent._rotationMatrix[7];
  67100. this._particle._rotationMatrix[8] = this._rotMatrix.m[8] * this._parent._rotationMatrix[2] + this._rotMatrix.m[9] * this._parent._rotationMatrix[5] + this._rotMatrix.m[10] * this._parent._rotationMatrix[8];
  67101. }
  67102. }
  67103. else {
  67104. this._particle._globalPosition.x = this._particle.position.x;
  67105. this._particle._globalPosition.y = this._particle.position.y;
  67106. this._particle._globalPosition.z = this._particle.position.z;
  67107. if (this._computeParticleRotation || this.billboard) {
  67108. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67109. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67110. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67111. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67112. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67113. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67114. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67115. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67116. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67117. }
  67118. }
  67119. if (this._particle.translateFromPivot) {
  67120. this._pivotBackTranslation.x = 0.0;
  67121. this._pivotBackTranslation.y = 0.0;
  67122. this._pivotBackTranslation.z = 0.0;
  67123. }
  67124. else {
  67125. this._pivotBackTranslation.x = this._scaledPivot.x;
  67126. this._pivotBackTranslation.y = this._scaledPivot.y;
  67127. this._pivotBackTranslation.z = this._scaledPivot.z;
  67128. }
  67129. // particle vertex loop
  67130. for (pt = 0; pt < this._shape.length; pt++) {
  67131. idx = index + pt * 3;
  67132. colidx = colorIndex + pt * 4;
  67133. uvidx = uvIndex + pt * 2;
  67134. this._vertex.x = this._shape[pt].x;
  67135. this._vertex.y = this._shape[pt].y;
  67136. this._vertex.z = this._shape[pt].z;
  67137. if (this._computeParticleVertex) {
  67138. this.updateParticleVertex(this._particle, this._vertex, pt);
  67139. }
  67140. // positions
  67141. this._vertex.x *= this._particle.scaling.x;
  67142. this._vertex.y *= this._particle.scaling.y;
  67143. this._vertex.z *= this._particle.scaling.z;
  67144. this._vertex.x -= this._scaledPivot.x;
  67145. this._vertex.y -= this._scaledPivot.y;
  67146. this._vertex.z -= this._scaledPivot.z;
  67147. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67148. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67149. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67150. this._rotated.x += this._pivotBackTranslation.x;
  67151. this._rotated.y += this._pivotBackTranslation.y;
  67152. this._rotated.z += this._pivotBackTranslation.z;
  67153. this._positions32[idx] = this._particle._globalPosition.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67154. this._positions32[idx + 1] = this._particle._globalPosition.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  67155. this._positions32[idx + 2] = this._particle._globalPosition.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  67156. if (this._computeBoundingBox) {
  67157. if (this._positions32[idx] < this._minimum.x) {
  67158. this._minimum.x = this._positions32[idx];
  67159. }
  67160. if (this._positions32[idx] > this._maximum.x) {
  67161. this._maximum.x = this._positions32[idx];
  67162. }
  67163. if (this._positions32[idx + 1] < this._minimum.y) {
  67164. this._minimum.y = this._positions32[idx + 1];
  67165. }
  67166. if (this._positions32[idx + 1] > this._maximum.y) {
  67167. this._maximum.y = this._positions32[idx + 1];
  67168. }
  67169. if (this._positions32[idx + 2] < this._minimum.z) {
  67170. this._minimum.z = this._positions32[idx + 2];
  67171. }
  67172. if (this._positions32[idx + 2] > this._maximum.z) {
  67173. this._maximum.z = this._positions32[idx + 2];
  67174. }
  67175. }
  67176. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67177. if (!this._computeParticleVertex) {
  67178. this._normal.x = this._fixedNormal32[idx];
  67179. this._normal.y = this._fixedNormal32[idx + 1];
  67180. this._normal.z = this._fixedNormal32[idx + 2];
  67181. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67182. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67183. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67184. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67185. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  67186. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  67187. }
  67188. if (this._computeParticleColor && this._particle.color) {
  67189. this._colors32[colidx] = this._particle.color.r;
  67190. this._colors32[colidx + 1] = this._particle.color.g;
  67191. this._colors32[colidx + 2] = this._particle.color.b;
  67192. this._colors32[colidx + 3] = this._particle.color.a;
  67193. }
  67194. if (this._computeParticleTexture) {
  67195. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67196. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67197. }
  67198. }
  67199. }
  67200. // particle just set invisible : scaled to zero and positioned at the origin
  67201. else {
  67202. this._particle._stillInvisible = true; // mark the particle as invisible
  67203. for (pt = 0; pt < this._shape.length; pt++) {
  67204. idx = index + pt * 3;
  67205. colidx = colorIndex + pt * 4;
  67206. uvidx = uvIndex + pt * 2;
  67207. this._positions32[idx] = 0.0;
  67208. this._positions32[idx + 1] = 0.0;
  67209. this._positions32[idx + 2] = 0.0;
  67210. this._normals32[idx] = 0.0;
  67211. this._normals32[idx + 1] = 0.0;
  67212. this._normals32[idx + 2] = 0.0;
  67213. if (this._computeParticleColor && this._particle.color) {
  67214. this._colors32[colidx] = this._particle.color.r;
  67215. this._colors32[colidx + 1] = this._particle.color.g;
  67216. this._colors32[colidx + 2] = this._particle.color.b;
  67217. this._colors32[colidx + 3] = this._particle.color.a;
  67218. }
  67219. if (this._computeParticleTexture) {
  67220. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67221. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67222. }
  67223. }
  67224. }
  67225. // if the particle intersections must be computed : update the bbInfo
  67226. if (this._particlesIntersect) {
  67227. var bInfo = this._particle._boundingInfo;
  67228. var bBox = bInfo.boundingBox;
  67229. var bSphere = bInfo.boundingSphere;
  67230. if (!this._bSphereOnly) {
  67231. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67232. for (var b = 0; b < bBox.vectors.length; b++) {
  67233. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67234. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67235. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67236. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67237. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67238. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67239. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67240. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  67241. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  67242. }
  67243. bBox._update(this.mesh._worldMatrix);
  67244. }
  67245. // place and scale the particle bouding sphere in the SPS local system, then update it
  67246. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67247. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67248. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67249. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67250. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67251. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67252. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67253. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67254. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67255. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  67256. bSphere._update(this.mesh._worldMatrix);
  67257. }
  67258. // increment indexes for the next particle
  67259. index = idx + 3;
  67260. colorIndex = colidx + 4;
  67261. uvIndex = uvidx + 2;
  67262. }
  67263. // if the VBO must be updated
  67264. if (update) {
  67265. if (this._computeParticleColor) {
  67266. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67267. }
  67268. if (this._computeParticleTexture) {
  67269. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67270. }
  67271. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67272. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67273. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67274. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67275. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67276. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67277. for (var i = 0; i < this._normals32.length; i++) {
  67278. this._fixedNormal32[i] = this._normals32[i];
  67279. }
  67280. }
  67281. if (!this.mesh.areNormalsFrozen) {
  67282. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67283. }
  67284. }
  67285. if (this._depthSort && this._depthSortParticles) {
  67286. this.depthSortedParticles.sort(this._depthSortFunction);
  67287. var dspl = this.depthSortedParticles.length;
  67288. var sorted = 0;
  67289. var lind = 0;
  67290. var sind = 0;
  67291. var sid = 0;
  67292. for (sorted = 0; sorted < dspl; sorted++) {
  67293. lind = this.depthSortedParticles[sorted].indicesLength;
  67294. sind = this.depthSortedParticles[sorted].ind;
  67295. for (var i = 0; i < lind; i++) {
  67296. this._indices32[sid] = this._indices[sind + i];
  67297. sid++;
  67298. }
  67299. }
  67300. this.mesh.updateIndices(this._indices32);
  67301. }
  67302. }
  67303. if (this._computeBoundingBox) {
  67304. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67305. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67306. }
  67307. this.afterUpdateParticles(start, end, update);
  67308. return this;
  67309. };
  67310. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67311. this._halfroll = this._roll * 0.5;
  67312. this._halfpitch = this._pitch * 0.5;
  67313. this._halfyaw = this._yaw * 0.5;
  67314. this._sinRoll = Math.sin(this._halfroll);
  67315. this._cosRoll = Math.cos(this._halfroll);
  67316. this._sinPitch = Math.sin(this._halfpitch);
  67317. this._cosPitch = Math.cos(this._halfpitch);
  67318. this._sinYaw = Math.sin(this._halfyaw);
  67319. this._cosYaw = Math.cos(this._halfyaw);
  67320. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67321. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67322. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67323. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67324. };
  67325. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67326. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67327. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67328. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67329. this._rotMatrix.m[3] = 0;
  67330. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67331. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67332. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67333. this._rotMatrix.m[7] = 0;
  67334. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67335. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67336. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67337. this._rotMatrix.m[11] = 0;
  67338. this._rotMatrix.m[12] = 0;
  67339. this._rotMatrix.m[13] = 0;
  67340. this._rotMatrix.m[14] = 0;
  67341. this._rotMatrix.m[15] = 1.0;
  67342. };
  67343. /**
  67344. * Disposes the SPS.
  67345. */
  67346. SolidParticleSystem.prototype.dispose = function () {
  67347. this.mesh.dispose();
  67348. this.vars = null;
  67349. // drop references to internal big arrays for the GC
  67350. this._positions = null;
  67351. this._indices = null;
  67352. this._normals = null;
  67353. this._uvs = null;
  67354. this._colors = null;
  67355. this._indices32 = null;
  67356. this._positions32 = null;
  67357. this._normals32 = null;
  67358. this._fixedNormal32 = null;
  67359. this._uvs32 = null;
  67360. this._colors32 = null;
  67361. this.pickedParticles = null;
  67362. };
  67363. /**
  67364. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67365. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67366. * @returns the SPS.
  67367. */
  67368. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67369. if (!this._isVisibilityBoxLocked) {
  67370. this.mesh.refreshBoundingInfo();
  67371. }
  67372. return this;
  67373. };
  67374. /**
  67375. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67376. * @param size the size (float) of the visibility box
  67377. * note : this doesn't lock the SPS mesh bounding box.
  67378. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67379. */
  67380. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67381. var vis = size / 2;
  67382. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67383. };
  67384. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67385. /**
  67386. * Gets whether the SPS as always visible or not
  67387. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67388. */
  67389. get: function () {
  67390. return this._alwaysVisible;
  67391. },
  67392. /**
  67393. * Sets the SPS as always visible or not
  67394. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67395. */
  67396. set: function (val) {
  67397. this._alwaysVisible = val;
  67398. this.mesh.alwaysSelectAsActiveMesh = val;
  67399. },
  67400. enumerable: true,
  67401. configurable: true
  67402. });
  67403. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67404. /**
  67405. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67406. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67407. */
  67408. get: function () {
  67409. return this._isVisibilityBoxLocked;
  67410. },
  67411. /**
  67412. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67413. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67414. */
  67415. set: function (val) {
  67416. this._isVisibilityBoxLocked = val;
  67417. var boundingInfo = this.mesh.getBoundingInfo();
  67418. boundingInfo.isLocked = val;
  67419. },
  67420. enumerable: true,
  67421. configurable: true
  67422. });
  67423. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67424. /**
  67425. * Gets if `setParticles()` computes the particle rotations or not.
  67426. * Default value : true. The SPS is faster when it's set to false.
  67427. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67428. */
  67429. get: function () {
  67430. return this._computeParticleRotation;
  67431. },
  67432. /**
  67433. * Tells to `setParticles()` to compute the particle rotations or not.
  67434. * Default value : true. The SPS is faster when it's set to false.
  67435. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67436. */
  67437. set: function (val) {
  67438. this._computeParticleRotation = val;
  67439. },
  67440. enumerable: true,
  67441. configurable: true
  67442. });
  67443. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67444. /**
  67445. * Gets if `setParticles()` computes the particle colors or not.
  67446. * Default value : true. The SPS is faster when it's set to false.
  67447. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67448. */
  67449. get: function () {
  67450. return this._computeParticleColor;
  67451. },
  67452. /**
  67453. * Tells to `setParticles()` to compute the particle colors or not.
  67454. * Default value : true. The SPS is faster when it's set to false.
  67455. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67456. */
  67457. set: function (val) {
  67458. this._computeParticleColor = val;
  67459. },
  67460. enumerable: true,
  67461. configurable: true
  67462. });
  67463. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67464. /**
  67465. * Gets if `setParticles()` computes the particle textures or not.
  67466. * Default value : true. The SPS is faster when it's set to false.
  67467. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67468. */
  67469. get: function () {
  67470. return this._computeParticleTexture;
  67471. },
  67472. set: function (val) {
  67473. this._computeParticleTexture = val;
  67474. },
  67475. enumerable: true,
  67476. configurable: true
  67477. });
  67478. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67479. /**
  67480. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67481. * Default value : false. The SPS is faster when it's set to false.
  67482. * Note : the particle custom vertex positions aren't stored values.
  67483. */
  67484. get: function () {
  67485. return this._computeParticleVertex;
  67486. },
  67487. /**
  67488. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67489. * Default value : false. The SPS is faster when it's set to false.
  67490. * Note : the particle custom vertex positions aren't stored values.
  67491. */
  67492. set: function (val) {
  67493. this._computeParticleVertex = val;
  67494. },
  67495. enumerable: true,
  67496. configurable: true
  67497. });
  67498. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67499. /**
  67500. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67501. */
  67502. get: function () {
  67503. return this._computeBoundingBox;
  67504. },
  67505. /**
  67506. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67507. */
  67508. set: function (val) {
  67509. this._computeBoundingBox = val;
  67510. },
  67511. enumerable: true,
  67512. configurable: true
  67513. });
  67514. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67515. /**
  67516. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67517. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67518. * Default : `true`
  67519. */
  67520. get: function () {
  67521. return this._depthSortParticles;
  67522. },
  67523. /**
  67524. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67525. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67526. * Default : `true`
  67527. */
  67528. set: function (val) {
  67529. this._depthSortParticles = val;
  67530. },
  67531. enumerable: true,
  67532. configurable: true
  67533. });
  67534. // =======================================================================
  67535. // Particle behavior logic
  67536. // these following methods may be overwritten by the user to fit his needs
  67537. /**
  67538. * This function does nothing. It may be overwritten to set all the particle first values.
  67539. * The SPS doesn't call this function, you may have to call it by your own.
  67540. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67541. */
  67542. SolidParticleSystem.prototype.initParticles = function () {
  67543. };
  67544. /**
  67545. * This function does nothing. It may be overwritten to recycle a particle.
  67546. * The SPS doesn't call this function, you may have to call it by your own.
  67547. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67548. * @param particle The particle to recycle
  67549. * @returns the recycled particle
  67550. */
  67551. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67552. return particle;
  67553. };
  67554. /**
  67555. * Updates a particle : this function should be overwritten by the user.
  67556. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67557. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67558. * @example : just set a particle position or velocity and recycle conditions
  67559. * @param particle The particle to update
  67560. * @returns the updated particle
  67561. */
  67562. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67563. return particle;
  67564. };
  67565. /**
  67566. * Updates a vertex of a particle : it can be overwritten by the user.
  67567. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67568. * @param particle the current particle
  67569. * @param vertex the current index of the current particle
  67570. * @param pt the index of the current vertex in the particle shape
  67571. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67572. * @example : just set a vertex particle position
  67573. * @returns the updated vertex
  67574. */
  67575. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67576. return vertex;
  67577. };
  67578. /**
  67579. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67580. * This does nothing and may be overwritten by the user.
  67581. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67582. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67583. * @param update the boolean update value actually passed to setParticles()
  67584. */
  67585. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67586. };
  67587. /**
  67588. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67589. * This will be passed three parameters.
  67590. * This does nothing and may be overwritten by the user.
  67591. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67592. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67593. * @param update the boolean update value actually passed to setParticles()
  67594. */
  67595. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67596. };
  67597. return SolidParticleSystem;
  67598. }());
  67599. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67600. })(BABYLON || (BABYLON = {}));
  67601. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67602. var BABYLON;
  67603. (function (BABYLON) {
  67604. /**
  67605. * Class containing static functions to help procedurally build meshes
  67606. */
  67607. var MeshBuilder = /** @class */ (function () {
  67608. function MeshBuilder() {
  67609. }
  67610. MeshBuilder.updateSideOrientation = function (orientation) {
  67611. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67612. return BABYLON.Mesh.DOUBLESIDE;
  67613. }
  67614. if (orientation === undefined || orientation === null) {
  67615. return BABYLON.Mesh.FRONTSIDE;
  67616. }
  67617. return orientation;
  67618. };
  67619. /**
  67620. * Creates a box mesh
  67621. * * The parameter `size` sets the size (float) of each box side (default 1)
  67622. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67623. * * 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)
  67624. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67625. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67626. * * 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
  67627. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67628. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67629. * @param name defines the name of the mesh
  67630. * @param options defines the options used to create the mesh
  67631. * @param scene defines the hosting scene
  67632. * @returns the box mesh
  67633. */
  67634. MeshBuilder.CreateBox = function (name, options, scene) {
  67635. if (scene === void 0) { scene = null; }
  67636. var box = new BABYLON.Mesh(name, scene);
  67637. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67638. box._originalBuilderSideOrientation = options.sideOrientation;
  67639. var vertexData = BABYLON.VertexData.CreateBox(options);
  67640. vertexData.applyToMesh(box, options.updatable);
  67641. return box;
  67642. };
  67643. /**
  67644. * Creates a sphere mesh
  67645. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67646. * * 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`)
  67647. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67648. * * 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
  67649. * * 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)
  67650. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67651. * * 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
  67652. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67653. * @param name defines the name of the mesh
  67654. * @param options defines the options used to create the mesh
  67655. * @param scene defines the hosting scene
  67656. * @returns the sphere mesh
  67657. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67658. */
  67659. MeshBuilder.CreateSphere = function (name, options, scene) {
  67660. var sphere = new BABYLON.Mesh(name, scene);
  67661. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67662. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67663. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67664. vertexData.applyToMesh(sphere, options.updatable);
  67665. return sphere;
  67666. };
  67667. /**
  67668. * Creates a plane polygonal mesh. By default, this is a disc
  67669. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67670. * * 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
  67671. * * 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
  67672. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67673. * * 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
  67674. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67675. * @param name defines the name of the mesh
  67676. * @param options defines the options used to create the mesh
  67677. * @param scene defines the hosting scene
  67678. * @returns the plane polygonal mesh
  67679. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67680. */
  67681. MeshBuilder.CreateDisc = function (name, options, scene) {
  67682. if (scene === void 0) { scene = null; }
  67683. var disc = new BABYLON.Mesh(name, scene);
  67684. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67685. disc._originalBuilderSideOrientation = options.sideOrientation;
  67686. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67687. vertexData.applyToMesh(disc, options.updatable);
  67688. return disc;
  67689. };
  67690. /**
  67691. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67692. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67693. * * 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`)
  67694. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67695. * * 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
  67696. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67697. * * 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
  67698. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67699. * @param name defines the name of the mesh
  67700. * @param options defines the options used to create the mesh
  67701. * @param scene defines the hosting scene
  67702. * @returns the icosahedron mesh
  67703. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67704. */
  67705. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67706. var sphere = new BABYLON.Mesh(name, scene);
  67707. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67708. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67709. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67710. vertexData.applyToMesh(sphere, options.updatable);
  67711. return sphere;
  67712. };
  67713. ;
  67714. /**
  67715. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67716. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67717. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67718. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67719. * * 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
  67720. * * 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
  67721. * * 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
  67722. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67723. * * 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
  67724. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67725. * * 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
  67726. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67727. * * 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
  67728. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67729. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67730. * @param name defines the name of the mesh
  67731. * @param options defines the options used to create the mesh
  67732. * @param scene defines the hosting scene
  67733. * @returns the ribbon mesh
  67734. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67735. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67736. */
  67737. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67738. if (scene === void 0) { scene = null; }
  67739. var pathArray = options.pathArray;
  67740. var closeArray = options.closeArray;
  67741. var closePath = options.closePath;
  67742. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67743. var instance = options.instance;
  67744. var updatable = options.updatable;
  67745. if (instance) { // existing ribbon instance update
  67746. // positionFunction : ribbon case
  67747. // only pathArray and sideOrientation parameters are taken into account for positions update
  67748. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67749. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  67750. var positionFunction = function (positions) {
  67751. var minlg = pathArray[0].length;
  67752. var mesh = instance;
  67753. var i = 0;
  67754. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  67755. for (var si = 1; si <= ns; si++) {
  67756. for (var p = 0; p < pathArray.length; p++) {
  67757. var path = pathArray[p];
  67758. var l = path.length;
  67759. minlg = (minlg < l) ? minlg : l;
  67760. var j = 0;
  67761. while (j < minlg) {
  67762. positions[i] = path[j].x;
  67763. positions[i + 1] = path[j].y;
  67764. positions[i + 2] = path[j].z;
  67765. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67766. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67767. }
  67768. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67769. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67770. }
  67771. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67772. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67773. }
  67774. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67775. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67776. }
  67777. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67778. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67779. }
  67780. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67781. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67782. }
  67783. j++;
  67784. i += 3;
  67785. }
  67786. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67787. positions[i] = path[0].x;
  67788. positions[i + 1] = path[0].y;
  67789. positions[i + 2] = path[0].z;
  67790. i += 3;
  67791. }
  67792. }
  67793. }
  67794. };
  67795. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67796. positionFunction(positions);
  67797. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  67798. instance._boundingInfo.update(instance._worldMatrix);
  67799. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67800. if (options.colors) {
  67801. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67802. for (var c = 0; c < options.colors.length; c++) {
  67803. colors[c * 4] = options.colors[c].r;
  67804. colors[c * 4 + 1] = options.colors[c].g;
  67805. colors[c * 4 + 2] = options.colors[c].b;
  67806. colors[c * 4 + 3] = options.colors[c].a;
  67807. }
  67808. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67809. }
  67810. if (options.uvs) {
  67811. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67812. for (var i = 0; i < options.uvs.length; i++) {
  67813. uvs[i * 2] = options.uvs[i].x;
  67814. uvs[i * 2 + 1] = options.uvs[i].y;
  67815. }
  67816. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67817. }
  67818. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67819. var indices = instance.getIndices();
  67820. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67821. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67822. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67823. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67824. var indexFirst = 0;
  67825. var indexLast = 0;
  67826. for (var p = 0; p < pathArray.length; p++) {
  67827. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67828. if (p + 1 < pathArray.length) {
  67829. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67830. }
  67831. else {
  67832. indexLast = normals.length - 3;
  67833. }
  67834. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67835. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67836. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67837. normals[indexLast] = normals[indexFirst];
  67838. normals[indexLast + 1] = normals[indexFirst + 1];
  67839. normals[indexLast + 2] = normals[indexFirst + 2];
  67840. }
  67841. }
  67842. if (!(instance.areNormalsFrozen)) {
  67843. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67844. }
  67845. }
  67846. return instance;
  67847. }
  67848. else { // new ribbon creation
  67849. var ribbon = new BABYLON.Mesh(name, scene);
  67850. ribbon._originalBuilderSideOrientation = sideOrientation;
  67851. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67852. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67853. if (closePath) {
  67854. ribbon._creationDataStorage.idx = vertexData._idx;
  67855. }
  67856. ribbon._creationDataStorage.closePath = closePath;
  67857. ribbon._creationDataStorage.closeArray = closeArray;
  67858. vertexData.applyToMesh(ribbon, updatable);
  67859. return ribbon;
  67860. }
  67861. };
  67862. /**
  67863. * Creates a cylinder or a cone mesh
  67864. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67865. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67866. * * 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.
  67867. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67868. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67869. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67870. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67871. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67872. * * 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).
  67873. * * 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
  67874. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67875. * * 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
  67876. * * 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.
  67877. * * If `enclose` is false, a ring surface is one element.
  67878. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67879. * * 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
  67880. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67881. * * 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
  67882. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67883. * @param name defines the name of the mesh
  67884. * @param options defines the options used to create the mesh
  67885. * @param scene defines the hosting scene
  67886. * @returns the cylinder mesh
  67887. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67888. */
  67889. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67890. var cylinder = new BABYLON.Mesh(name, scene);
  67891. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67892. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67893. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67894. vertexData.applyToMesh(cylinder, options.updatable);
  67895. return cylinder;
  67896. };
  67897. /**
  67898. * Creates a torus mesh
  67899. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67900. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67901. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67902. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67903. * * 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
  67904. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67905. * @param name defines the name of the mesh
  67906. * @param options defines the options used to create the mesh
  67907. * @param scene defines the hosting scene
  67908. * @returns the torus mesh
  67909. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67910. */
  67911. MeshBuilder.CreateTorus = function (name, options, scene) {
  67912. var torus = new BABYLON.Mesh(name, scene);
  67913. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67914. torus._originalBuilderSideOrientation = options.sideOrientation;
  67915. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67916. vertexData.applyToMesh(torus, options.updatable);
  67917. return torus;
  67918. };
  67919. /**
  67920. * Creates a torus knot mesh
  67921. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67922. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67923. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67924. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67925. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67926. * * 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
  67927. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67928. * @param name defines the name of the mesh
  67929. * @param options defines the options used to create the mesh
  67930. * @param scene defines the hosting scene
  67931. * @returns the torus knot mesh
  67932. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67933. */
  67934. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67935. var torusKnot = new BABYLON.Mesh(name, scene);
  67936. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67937. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67938. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67939. vertexData.applyToMesh(torusKnot, options.updatable);
  67940. return torusKnot;
  67941. };
  67942. /**
  67943. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67944. * * 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
  67945. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67946. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67947. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67948. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67949. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67950. * * 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
  67951. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67952. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67953. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67954. * @param name defines the name of the new line system
  67955. * @param options defines the options used to create the line system
  67956. * @param scene defines the hosting scene
  67957. * @returns a new line system mesh
  67958. */
  67959. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67960. var instance = options.instance;
  67961. var lines = options.lines;
  67962. var colors = options.colors;
  67963. if (instance) { // lines update
  67964. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67965. var vertexColor;
  67966. var lineColors;
  67967. if (colors) {
  67968. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67969. }
  67970. var i = 0;
  67971. var c = 0;
  67972. for (var l = 0; l < lines.length; l++) {
  67973. var points = lines[l];
  67974. for (var p = 0; p < points.length; p++) {
  67975. positions[i] = points[p].x;
  67976. positions[i + 1] = points[p].y;
  67977. positions[i + 2] = points[p].z;
  67978. if (colors && vertexColor) {
  67979. lineColors = colors[l];
  67980. vertexColor[c] = lineColors[p].r;
  67981. vertexColor[c + 1] = lineColors[p].g;
  67982. vertexColor[c + 2] = lineColors[p].b;
  67983. vertexColor[c + 3] = lineColors[p].a;
  67984. c += 4;
  67985. }
  67986. i += 3;
  67987. }
  67988. }
  67989. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67990. if (colors && vertexColor) {
  67991. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  67992. }
  67993. return instance;
  67994. }
  67995. // line system creation
  67996. var useVertexColor = (colors) ? true : false;
  67997. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  67998. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  67999. vertexData.applyToMesh(lineSystem, options.updatable);
  68000. return lineSystem;
  68001. };
  68002. /**
  68003. * Creates a line mesh
  68004. * 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
  68005. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68006. * * The parameter `points` is an array successive Vector3
  68007. * * 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
  68008. * * The optional parameter `colors` is an array of successive Color4, one per line point
  68009. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  68010. * * When updating an instance, remember that only point positions can change, not the number of points
  68011. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68012. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  68013. * @param name defines the name of the new line system
  68014. * @param options defines the options used to create the line system
  68015. * @param scene defines the hosting scene
  68016. * @returns a new line mesh
  68017. */
  68018. MeshBuilder.CreateLines = function (name, options, scene) {
  68019. if (scene === void 0) { scene = null; }
  68020. var colors = (options.colors) ? [options.colors] : null;
  68021. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  68022. return lines;
  68023. };
  68024. /**
  68025. * Creates a dashed line mesh
  68026. * * 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
  68027. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68028. * * The parameter `points` is an array successive Vector3
  68029. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  68030. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  68031. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68032. * * 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
  68033. * * When updating an instance, remember that only point positions can change, not the number of points
  68034. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68035. * @param name defines the name of the mesh
  68036. * @param options defines the options used to create the mesh
  68037. * @param scene defines the hosting scene
  68038. * @returns the dashed line mesh
  68039. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68040. */
  68041. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68042. if (scene === void 0) { scene = null; }
  68043. var points = options.points;
  68044. var instance = options.instance;
  68045. var gapSize = options.gapSize || 1;
  68046. var dashSize = options.dashSize || 3;
  68047. if (instance) { // dashed lines update
  68048. var positionFunction = function (positions) {
  68049. var curvect = BABYLON.Vector3.Zero();
  68050. var nbSeg = positions.length / 6;
  68051. var lg = 0;
  68052. var nb = 0;
  68053. var shft = 0;
  68054. var dashshft = 0;
  68055. var curshft = 0;
  68056. var p = 0;
  68057. var i = 0;
  68058. var j = 0;
  68059. for (i = 0; i < points.length - 1; i++) {
  68060. points[i + 1].subtractToRef(points[i], curvect);
  68061. lg += curvect.length();
  68062. }
  68063. shft = lg / nbSeg;
  68064. var dashSize = instance._creationDataStorage.dashSize;
  68065. var gapSize = instance._creationDataStorage.gapSize;
  68066. dashshft = dashSize * shft / (dashSize + gapSize);
  68067. for (i = 0; i < points.length - 1; i++) {
  68068. points[i + 1].subtractToRef(points[i], curvect);
  68069. nb = Math.floor(curvect.length() / shft);
  68070. curvect.normalize();
  68071. j = 0;
  68072. while (j < nb && p < positions.length) {
  68073. curshft = shft * j;
  68074. positions[p] = points[i].x + curshft * curvect.x;
  68075. positions[p + 1] = points[i].y + curshft * curvect.y;
  68076. positions[p + 2] = points[i].z + curshft * curvect.z;
  68077. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68078. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68079. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68080. p += 6;
  68081. j++;
  68082. }
  68083. }
  68084. while (p < positions.length) {
  68085. positions[p] = points[i].x;
  68086. positions[p + 1] = points[i].y;
  68087. positions[p + 2] = points[i].z;
  68088. p += 3;
  68089. }
  68090. };
  68091. instance.updateMeshPositions(positionFunction, false);
  68092. return instance;
  68093. }
  68094. // dashed lines creation
  68095. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68096. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68097. vertexData.applyToMesh(dashedLines, options.updatable);
  68098. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68099. dashedLines._creationDataStorage.dashSize = dashSize;
  68100. dashedLines._creationDataStorage.gapSize = gapSize;
  68101. return dashedLines;
  68102. };
  68103. /**
  68104. * 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.
  68105. * * 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.
  68106. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68107. * * 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.
  68108. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68109. * * 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
  68110. * * 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
  68111. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68112. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68113. * * 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
  68114. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68115. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68116. * @param name defines the name of the mesh
  68117. * @param options defines the options used to create the mesh
  68118. * @param scene defines the hosting scene
  68119. * @returns the extruded shape mesh
  68120. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68121. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68122. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68123. */
  68124. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68125. if (scene === void 0) { scene = null; }
  68126. var path = options.path;
  68127. var shape = options.shape;
  68128. var scale = options.scale || 1;
  68129. var rotation = options.rotation || 0;
  68130. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68131. var updatable = options.updatable;
  68132. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68133. var instance = options.instance || null;
  68134. var invertUV = options.invertUV || false;
  68135. 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);
  68136. };
  68137. /**
  68138. * Creates an custom extruded shape mesh.
  68139. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68140. * * 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.
  68141. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68142. * * 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
  68143. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68144. * * 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
  68145. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68146. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68147. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68148. * * 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
  68149. * * 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
  68150. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68151. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68152. * * 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
  68153. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68154. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68155. * @param name defines the name of the mesh
  68156. * @param options defines the options used to create the mesh
  68157. * @param scene defines the hosting scene
  68158. * @returns the custom extruded shape mesh
  68159. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68160. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68161. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68162. */
  68163. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68164. var path = options.path;
  68165. var shape = options.shape;
  68166. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68167. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68168. var ribbonCloseArray = options.ribbonCloseArray || false;
  68169. var ribbonClosePath = options.ribbonClosePath || false;
  68170. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68171. var updatable = options.updatable;
  68172. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68173. var instance = options.instance;
  68174. var invertUV = options.invertUV || false;
  68175. 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);
  68176. };
  68177. /**
  68178. * Creates lathe mesh.
  68179. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68180. * * 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
  68181. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68182. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68183. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68184. * * 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
  68185. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68186. * * 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
  68187. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68188. * * 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
  68189. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68190. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68191. * @param name defines the name of the mesh
  68192. * @param options defines the options used to create the mesh
  68193. * @param scene defines the hosting scene
  68194. * @returns the lathe mesh
  68195. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68196. */
  68197. MeshBuilder.CreateLathe = function (name, options, scene) {
  68198. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68199. var closed = (options.closed === undefined) ? true : options.closed;
  68200. var shape = options.shape;
  68201. var radius = options.radius || 1;
  68202. var tessellation = options.tessellation || 64;
  68203. var clip = options.clip || 0;
  68204. var updatable = options.updatable;
  68205. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68206. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68207. var pi2 = Math.PI * 2;
  68208. var paths = new Array();
  68209. var invertUV = options.invertUV || false;
  68210. var i = 0;
  68211. var p = 0;
  68212. var step = pi2 / tessellation * arc;
  68213. var rotated;
  68214. var path = new Array();
  68215. for (i = 0; i <= tessellation - clip; i++) {
  68216. var path = [];
  68217. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68218. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68219. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68220. }
  68221. for (p = 0; p < shape.length; p++) {
  68222. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68223. path.push(rotated);
  68224. }
  68225. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68226. 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));
  68227. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68228. }
  68229. paths.push(path);
  68230. }
  68231. // lathe ribbon
  68232. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68233. return lathe;
  68234. };
  68235. /**
  68236. * Creates a plane mesh
  68237. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68238. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68239. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68240. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68241. * * 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
  68242. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68243. * @param name defines the name of the mesh
  68244. * @param options defines the options used to create the mesh
  68245. * @param scene defines the hosting scene
  68246. * @returns the plane mesh
  68247. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68248. */
  68249. MeshBuilder.CreatePlane = function (name, options, scene) {
  68250. var plane = new BABYLON.Mesh(name, scene);
  68251. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68252. plane._originalBuilderSideOrientation = options.sideOrientation;
  68253. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68254. vertexData.applyToMesh(plane, options.updatable);
  68255. if (options.sourcePlane) {
  68256. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68257. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68258. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68259. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68260. plane.rotate(vectorProduct, product);
  68261. }
  68262. }
  68263. return plane;
  68264. };
  68265. /**
  68266. * Creates a ground mesh
  68267. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68268. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68270. * @param name defines the name of the mesh
  68271. * @param options defines the options used to create the mesh
  68272. * @param scene defines the hosting scene
  68273. * @returns the ground mesh
  68274. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68275. */
  68276. MeshBuilder.CreateGround = function (name, options, scene) {
  68277. var ground = new BABYLON.GroundMesh(name, scene);
  68278. ground._setReady(false);
  68279. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68280. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68281. ground._width = options.width || 1;
  68282. ground._height = options.height || 1;
  68283. ground._maxX = ground._width / 2;
  68284. ground._maxZ = ground._height / 2;
  68285. ground._minX = -ground._maxX;
  68286. ground._minZ = -ground._maxZ;
  68287. var vertexData = BABYLON.VertexData.CreateGround(options);
  68288. vertexData.applyToMesh(ground, options.updatable);
  68289. ground._setReady(true);
  68290. return ground;
  68291. };
  68292. /**
  68293. * Creates a tiled ground mesh
  68294. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68295. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68296. * * 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
  68297. * * 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
  68298. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68299. * @param name defines the name of the mesh
  68300. * @param options defines the options used to create the mesh
  68301. * @param scene defines the hosting scene
  68302. * @returns the tiled ground mesh
  68303. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68304. */
  68305. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68306. var tiledGround = new BABYLON.Mesh(name, scene);
  68307. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68308. vertexData.applyToMesh(tiledGround, options.updatable);
  68309. return tiledGround;
  68310. };
  68311. /**
  68312. * Creates a ground mesh from a height map
  68313. * * The parameter `url` sets the URL of the height map image resource.
  68314. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68315. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68316. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68317. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68318. * * 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.
  68319. * * 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).
  68320. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68321. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68322. * @param name defines the name of the mesh
  68323. * @param url defines the url to the height map
  68324. * @param options defines the options used to create the mesh
  68325. * @param scene defines the hosting scene
  68326. * @returns the ground mesh
  68327. * @see http://doc.babylonjs.com/babylon101/height_map
  68328. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68329. */
  68330. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68331. var width = options.width || 10.0;
  68332. var height = options.height || 10.0;
  68333. var subdivisions = options.subdivisions || 1 | 0;
  68334. var minHeight = options.minHeight || 0.0;
  68335. var maxHeight = options.maxHeight || 1.0;
  68336. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68337. var alphaFilter = options.alphaFilter || 0.0;
  68338. var updatable = options.updatable;
  68339. var onReady = options.onReady;
  68340. var ground = new BABYLON.GroundMesh(name, scene);
  68341. ground._subdivisionsX = subdivisions;
  68342. ground._subdivisionsY = subdivisions;
  68343. ground._width = width;
  68344. ground._height = height;
  68345. ground._maxX = ground._width / 2.0;
  68346. ground._maxZ = ground._height / 2.0;
  68347. ground._minX = -ground._maxX;
  68348. ground._minZ = -ground._maxZ;
  68349. ground._setReady(false);
  68350. var onload = function (img) {
  68351. // Getting height map data
  68352. var canvas = document.createElement("canvas");
  68353. var context = canvas.getContext("2d");
  68354. if (!context) {
  68355. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68356. }
  68357. if (scene.isDisposed) {
  68358. return;
  68359. }
  68360. var bufferWidth = img.width;
  68361. var bufferHeight = img.height;
  68362. canvas.width = bufferWidth;
  68363. canvas.height = bufferHeight;
  68364. context.drawImage(img, 0, 0);
  68365. // Create VertexData from map data
  68366. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68367. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68368. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68369. width: width, height: height,
  68370. subdivisions: subdivisions,
  68371. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68372. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68373. alphaFilter: alphaFilter
  68374. });
  68375. vertexData.applyToMesh(ground, updatable);
  68376. //execute ready callback, if set
  68377. if (onReady) {
  68378. onReady(ground);
  68379. }
  68380. ground._setReady(true);
  68381. };
  68382. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68383. return ground;
  68384. };
  68385. /**
  68386. * Creates a polygon mesh
  68387. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68388. * * 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
  68389. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68390. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68391. * * 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)
  68392. * * Remember you can only change the shape positions, not their number when updating a polygon
  68393. * @param name defines the name of the mesh
  68394. * @param options defines the options used to create the mesh
  68395. * @param scene defines the hosting scene
  68396. * @returns the polygon mesh
  68397. */
  68398. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68399. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68400. var shape = options.shape;
  68401. var holes = options.holes || [];
  68402. var depth = options.depth || 0;
  68403. var contours = [];
  68404. var hole = [];
  68405. for (var i = 0; i < shape.length; i++) {
  68406. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68407. }
  68408. var epsilon = 0.00000001;
  68409. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68410. contours.pop();
  68411. }
  68412. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68413. for (var hNb = 0; hNb < holes.length; hNb++) {
  68414. hole = [];
  68415. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68416. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68417. }
  68418. polygonTriangulation.addHole(hole);
  68419. }
  68420. var polygon = polygonTriangulation.build(options.updatable, depth);
  68421. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68422. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68423. vertexData.applyToMesh(polygon, options.updatable);
  68424. return polygon;
  68425. };
  68426. ;
  68427. /**
  68428. * Creates an extruded polygon mesh, with depth in the Y direction.
  68429. * * 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)
  68430. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68431. * @param name defines the name of the mesh
  68432. * @param options defines the options used to create the mesh
  68433. * @param scene defines the hosting scene
  68434. * @returns the polygon mesh
  68435. */
  68436. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68437. return MeshBuilder.CreatePolygon(name, options, scene);
  68438. };
  68439. ;
  68440. /**
  68441. * Creates a tube mesh.
  68442. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68443. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68444. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68445. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68446. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68447. * * 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)
  68448. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68449. * * 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
  68450. * * 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
  68451. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68452. * * 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
  68453. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68454. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68455. * @param name defines the name of the mesh
  68456. * @param options defines the options used to create the mesh
  68457. * @param scene defines the hosting scene
  68458. * @returns the tube mesh
  68459. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68460. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68461. */
  68462. MeshBuilder.CreateTube = function (name, options, scene) {
  68463. var path = options.path;
  68464. var instance = options.instance;
  68465. var radius = 1.0;
  68466. if (options.radius !== undefined) {
  68467. radius = options.radius;
  68468. }
  68469. else if (instance) {
  68470. radius = instance._creationDataStorage.radius;
  68471. }
  68472. var tessellation = options.tessellation || 64 | 0;
  68473. var radiusFunction = options.radiusFunction || null;
  68474. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68475. var invertUV = options.invertUV || false;
  68476. var updatable = options.updatable;
  68477. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68478. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68479. // tube geometry
  68480. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68481. var tangents = path3D.getTangents();
  68482. var normals = path3D.getNormals();
  68483. var distances = path3D.getDistances();
  68484. var pi2 = Math.PI * 2;
  68485. var step = pi2 / tessellation * arc;
  68486. var returnRadius = function () { return radius; };
  68487. var radiusFunctionFinal = radiusFunction || returnRadius;
  68488. var circlePath;
  68489. var rad;
  68490. var normal;
  68491. var rotated;
  68492. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68493. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68494. for (var i = 0; i < path.length; i++) {
  68495. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68496. circlePath = Array(); // current circle array
  68497. normal = normals[i]; // current normal
  68498. for (var t = 0; t < tessellation; t++) {
  68499. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68500. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68501. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68502. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68503. circlePath[t] = rotated;
  68504. }
  68505. circlePaths[index] = circlePath;
  68506. index++;
  68507. }
  68508. // cap
  68509. var capPath = function (nbPoints, pathIndex) {
  68510. var pointCap = Array();
  68511. for (var i = 0; i < nbPoints; i++) {
  68512. pointCap.push(path[pathIndex]);
  68513. }
  68514. return pointCap;
  68515. };
  68516. switch (cap) {
  68517. case BABYLON.Mesh.NO_CAP:
  68518. break;
  68519. case BABYLON.Mesh.CAP_START:
  68520. circlePaths[0] = capPath(tessellation, 0);
  68521. circlePaths[1] = circlePaths[2].slice(0);
  68522. break;
  68523. case BABYLON.Mesh.CAP_END:
  68524. circlePaths[index] = circlePaths[index - 1].slice(0);
  68525. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68526. break;
  68527. case BABYLON.Mesh.CAP_ALL:
  68528. circlePaths[0] = capPath(tessellation, 0);
  68529. circlePaths[1] = circlePaths[2].slice(0);
  68530. circlePaths[index] = circlePaths[index - 1].slice(0);
  68531. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68532. break;
  68533. default:
  68534. break;
  68535. }
  68536. return circlePaths;
  68537. };
  68538. var path3D;
  68539. var pathArray;
  68540. if (instance) { // tube update
  68541. var storage = instance._creationDataStorage;
  68542. var arc = options.arc || storage.arc;
  68543. path3D = storage.path3D.update(path);
  68544. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68545. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68546. // Update mode, no need to recreate the storage.
  68547. storage.path3D = path3D;
  68548. storage.pathArray = pathArray;
  68549. storage.arc = arc;
  68550. storage.radius = radius;
  68551. return instance;
  68552. }
  68553. // tube creation
  68554. path3D = new BABYLON.Path3D(path);
  68555. var newPathArray = new Array();
  68556. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68557. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68558. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68559. tube._creationDataStorage.pathArray = pathArray;
  68560. tube._creationDataStorage.path3D = path3D;
  68561. tube._creationDataStorage.tessellation = tessellation;
  68562. tube._creationDataStorage.cap = cap;
  68563. tube._creationDataStorage.arc = options.arc;
  68564. tube._creationDataStorage.radius = radius;
  68565. return tube;
  68566. };
  68567. /**
  68568. * Creates a polyhedron mesh
  68569. * * 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
  68570. * * The parameter `size` (positive float, default 1) sets the polygon size
  68571. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68572. * * 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`
  68573. * * 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
  68574. * * 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)`)
  68575. * * 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
  68576. * * 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
  68577. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68578. * * 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
  68579. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68580. * @param name defines the name of the mesh
  68581. * @param options defines the options used to create the mesh
  68582. * @param scene defines the hosting scene
  68583. * @returns the polyhedron mesh
  68584. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68585. */
  68586. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68587. var polyhedron = new BABYLON.Mesh(name, scene);
  68588. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68589. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68590. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68591. vertexData.applyToMesh(polyhedron, options.updatable);
  68592. return polyhedron;
  68593. };
  68594. /**
  68595. * Creates a decal mesh.
  68596. * 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
  68597. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68598. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68599. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68600. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68601. * @param name defines the name of the mesh
  68602. * @param sourceMesh defines the mesh where the decal must be applied
  68603. * @param options defines the options used to create the mesh
  68604. * @param scene defines the hosting scene
  68605. * @returns the decal mesh
  68606. * @see http://doc.babylonjs.com/how_to/decals
  68607. */
  68608. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68609. var indices = sourceMesh.getIndices();
  68610. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68611. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68612. var position = options.position || BABYLON.Vector3.Zero();
  68613. var normal = options.normal || BABYLON.Vector3.Up();
  68614. var size = options.size || BABYLON.Vector3.One();
  68615. var angle = options.angle || 0;
  68616. // Getting correct rotation
  68617. if (!normal) {
  68618. var target = new BABYLON.Vector3(0, 0, 1);
  68619. var camera = sourceMesh.getScene().activeCamera;
  68620. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68621. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68622. }
  68623. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68624. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68625. var pitch = Math.atan2(normal.y, len);
  68626. // Matrix
  68627. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68628. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68629. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68630. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68631. var vertexData = new BABYLON.VertexData();
  68632. vertexData.indices = [];
  68633. vertexData.positions = [];
  68634. vertexData.normals = [];
  68635. vertexData.uvs = [];
  68636. var currentVertexDataIndex = 0;
  68637. var extractDecalVector3 = function (indexId) {
  68638. var result = new BABYLON.PositionNormalVertex();
  68639. if (!indices || !positions || !normals) {
  68640. return result;
  68641. }
  68642. var vertexId = indices[indexId];
  68643. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68644. // Send vector to decal local world
  68645. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68646. // Get normal
  68647. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68648. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68649. return result;
  68650. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68651. var clip = function (vertices, axis) {
  68652. if (vertices.length === 0) {
  68653. return vertices;
  68654. }
  68655. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68656. var clipVertices = function (v0, v1) {
  68657. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68658. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68659. };
  68660. var result = new Array();
  68661. for (var index = 0; index < vertices.length; index += 3) {
  68662. var v1Out;
  68663. var v2Out;
  68664. var v3Out;
  68665. var total = 0;
  68666. var nV1 = null;
  68667. var nV2 = null;
  68668. var nV3 = null;
  68669. var nV4 = null;
  68670. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68671. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68672. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68673. v1Out = d1 > 0;
  68674. v2Out = d2 > 0;
  68675. v3Out = d3 > 0;
  68676. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68677. switch (total) {
  68678. case 0:
  68679. result.push(vertices[index]);
  68680. result.push(vertices[index + 1]);
  68681. result.push(vertices[index + 2]);
  68682. break;
  68683. case 1:
  68684. if (v1Out) {
  68685. nV1 = vertices[index + 1];
  68686. nV2 = vertices[index + 2];
  68687. nV3 = clipVertices(vertices[index], nV1);
  68688. nV4 = clipVertices(vertices[index], nV2);
  68689. }
  68690. if (v2Out) {
  68691. nV1 = vertices[index];
  68692. nV2 = vertices[index + 2];
  68693. nV3 = clipVertices(vertices[index + 1], nV1);
  68694. nV4 = clipVertices(vertices[index + 1], nV2);
  68695. result.push(nV3);
  68696. result.push(nV2.clone());
  68697. result.push(nV1.clone());
  68698. result.push(nV2.clone());
  68699. result.push(nV3.clone());
  68700. result.push(nV4);
  68701. break;
  68702. }
  68703. if (v3Out) {
  68704. nV1 = vertices[index];
  68705. nV2 = vertices[index + 1];
  68706. nV3 = clipVertices(vertices[index + 2], nV1);
  68707. nV4 = clipVertices(vertices[index + 2], nV2);
  68708. }
  68709. if (nV1 && nV2 && nV3 && nV4) {
  68710. result.push(nV1.clone());
  68711. result.push(nV2.clone());
  68712. result.push(nV3);
  68713. result.push(nV4);
  68714. result.push(nV3.clone());
  68715. result.push(nV2.clone());
  68716. }
  68717. break;
  68718. case 2:
  68719. if (!v1Out) {
  68720. nV1 = vertices[index].clone();
  68721. nV2 = clipVertices(nV1, vertices[index + 1]);
  68722. nV3 = clipVertices(nV1, vertices[index + 2]);
  68723. result.push(nV1);
  68724. result.push(nV2);
  68725. result.push(nV3);
  68726. }
  68727. if (!v2Out) {
  68728. nV1 = vertices[index + 1].clone();
  68729. nV2 = clipVertices(nV1, vertices[index + 2]);
  68730. nV3 = clipVertices(nV1, vertices[index]);
  68731. result.push(nV1);
  68732. result.push(nV2);
  68733. result.push(nV3);
  68734. }
  68735. if (!v3Out) {
  68736. nV1 = vertices[index + 2].clone();
  68737. nV2 = clipVertices(nV1, vertices[index]);
  68738. nV3 = clipVertices(nV1, vertices[index + 1]);
  68739. result.push(nV1);
  68740. result.push(nV2);
  68741. result.push(nV3);
  68742. }
  68743. break;
  68744. case 3:
  68745. break;
  68746. }
  68747. }
  68748. return result;
  68749. };
  68750. for (var index = 0; index < indices.length; index += 3) {
  68751. var faceVertices = new Array();
  68752. faceVertices.push(extractDecalVector3(index));
  68753. faceVertices.push(extractDecalVector3(index + 1));
  68754. faceVertices.push(extractDecalVector3(index + 2));
  68755. // Clip
  68756. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68757. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68758. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68759. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68760. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68761. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68762. if (faceVertices.length === 0) {
  68763. continue;
  68764. }
  68765. // Add UVs and get back to world
  68766. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68767. var vertex = faceVertices[vIndex];
  68768. //TODO check for Int32Array | Uint32Array | Uint16Array
  68769. vertexData.indices.push(currentVertexDataIndex);
  68770. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68771. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68772. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68773. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68774. currentVertexDataIndex++;
  68775. }
  68776. }
  68777. // Return mesh
  68778. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68779. vertexData.applyToMesh(decal);
  68780. decal.position = position.clone();
  68781. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68782. return decal;
  68783. };
  68784. // Privates
  68785. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68786. // extrusion geometry
  68787. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68788. var tangents = path3D.getTangents();
  68789. var normals = path3D.getNormals();
  68790. var binormals = path3D.getBinormals();
  68791. var distances = path3D.getDistances();
  68792. var angle = 0;
  68793. var returnScale = function () { return scale !== null ? scale : 1; };
  68794. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68795. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68796. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68797. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68798. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68799. for (var i = 0; i < curve.length; i++) {
  68800. var shapePath = new Array();
  68801. var angleStep = rotate(i, distances[i]);
  68802. var scaleRatio = scl(i, distances[i]);
  68803. for (var p = 0; p < shape.length; p++) {
  68804. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68805. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68806. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68807. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68808. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68809. shapePath[p] = rotated;
  68810. }
  68811. shapePaths[index] = shapePath;
  68812. angle += angleStep;
  68813. index++;
  68814. }
  68815. // cap
  68816. var capPath = function (shapePath) {
  68817. var pointCap = Array();
  68818. var barycenter = BABYLON.Vector3.Zero();
  68819. var i;
  68820. for (i = 0; i < shapePath.length; i++) {
  68821. barycenter.addInPlace(shapePath[i]);
  68822. }
  68823. barycenter.scaleInPlace(1.0 / shapePath.length);
  68824. for (i = 0; i < shapePath.length; i++) {
  68825. pointCap.push(barycenter);
  68826. }
  68827. return pointCap;
  68828. };
  68829. switch (cap) {
  68830. case BABYLON.Mesh.NO_CAP:
  68831. break;
  68832. case BABYLON.Mesh.CAP_START:
  68833. shapePaths[0] = capPath(shapePaths[2]);
  68834. shapePaths[1] = shapePaths[2];
  68835. break;
  68836. case BABYLON.Mesh.CAP_END:
  68837. shapePaths[index] = shapePaths[index - 1];
  68838. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68839. break;
  68840. case BABYLON.Mesh.CAP_ALL:
  68841. shapePaths[0] = capPath(shapePaths[2]);
  68842. shapePaths[1] = shapePaths[2];
  68843. shapePaths[index] = shapePaths[index - 1];
  68844. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68845. break;
  68846. default:
  68847. break;
  68848. }
  68849. return shapePaths;
  68850. };
  68851. var path3D;
  68852. var pathArray;
  68853. if (instance) { // instance update
  68854. var storage = instance._creationDataStorage;
  68855. path3D = storage.path3D.update(curve);
  68856. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68857. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68858. return instance;
  68859. }
  68860. // extruded shape creation
  68861. path3D = new BABYLON.Path3D(curve);
  68862. var newShapePaths = new Array();
  68863. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68864. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68865. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68866. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68867. extrudedGeneric._creationDataStorage.path3D = path3D;
  68868. extrudedGeneric._creationDataStorage.cap = cap;
  68869. return extrudedGeneric;
  68870. };
  68871. return MeshBuilder;
  68872. }());
  68873. BABYLON.MeshBuilder = MeshBuilder;
  68874. })(BABYLON || (BABYLON = {}));
  68875. //# sourceMappingURL=babylon.meshBuilder.js.map
  68876. var BABYLON;
  68877. (function (BABYLON) {
  68878. /**
  68879. * Draco compression (https://google.github.io/draco/)
  68880. *
  68881. * This class wraps the Draco module.
  68882. *
  68883. * **Encoder**
  68884. *
  68885. * The encoder is not currently implemented.
  68886. *
  68887. * **Decoder**
  68888. *
  68889. * 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.
  68890. *
  68891. * To update the configuration, use the following code:
  68892. * ```javascript
  68893. * BABYLON.DracoCompression.Configuration = {
  68894. * decoder: {
  68895. * wasmUrl: "<url to the WebAssembly library>",
  68896. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68897. * fallbackUrl: "<url to the fallback JavaScript library>",
  68898. * }
  68899. * };
  68900. * ```
  68901. *
  68902. * 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.
  68903. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68904. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68905. *
  68906. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68907. * ```javascript
  68908. * var dracoCompression = new BABYLON.DracoCompression();
  68909. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68910. * [BABYLON.VertexBuffer.PositionKind]: 0
  68911. * });
  68912. * ```
  68913. *
  68914. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68915. */
  68916. var DracoCompression = /** @class */ (function () {
  68917. /**
  68918. * Constructor
  68919. */
  68920. function DracoCompression() {
  68921. }
  68922. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68923. /**
  68924. * Returns true if the decoder is available.
  68925. */
  68926. get: function () {
  68927. if (typeof DracoDecoderModule !== "undefined") {
  68928. return true;
  68929. }
  68930. var decoder = DracoCompression.Configuration.decoder;
  68931. if (decoder) {
  68932. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68933. return true;
  68934. }
  68935. if (decoder.fallbackUrl) {
  68936. return true;
  68937. }
  68938. }
  68939. return false;
  68940. },
  68941. enumerable: true,
  68942. configurable: true
  68943. });
  68944. /**
  68945. * Stop all async operations and release resources.
  68946. */
  68947. DracoCompression.prototype.dispose = function () {
  68948. };
  68949. /**
  68950. * Decode Draco compressed mesh data to vertex data.
  68951. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68952. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68953. * @returns A promise that resolves with the decoded vertex data
  68954. */
  68955. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68956. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68957. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68958. var module = wrappedModule.module;
  68959. var vertexData = new BABYLON.VertexData();
  68960. var buffer = new module.DecoderBuffer();
  68961. buffer.Init(dataView, dataView.byteLength);
  68962. var decoder = new module.Decoder();
  68963. var geometry;
  68964. var status;
  68965. try {
  68966. var type = decoder.GetEncodedGeometryType(buffer);
  68967. switch (type) {
  68968. case module.TRIANGULAR_MESH:
  68969. geometry = new module.Mesh();
  68970. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68971. break;
  68972. case module.POINT_CLOUD:
  68973. geometry = new module.PointCloud();
  68974. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  68975. break;
  68976. default:
  68977. throw new Error("Invalid geometry type " + type);
  68978. }
  68979. if (!status.ok() || !geometry.ptr) {
  68980. throw new Error(status.error_msg());
  68981. }
  68982. var numPoints = geometry.num_points();
  68983. if (type === module.TRIANGULAR_MESH) {
  68984. var numFaces = geometry.num_faces();
  68985. var faceIndices = new module.DracoInt32Array();
  68986. try {
  68987. var indices = new Uint32Array(numFaces * 3);
  68988. for (var i = 0; i < numFaces; i++) {
  68989. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  68990. var offset = i * 3;
  68991. indices[offset + 0] = faceIndices.GetValue(0);
  68992. indices[offset + 1] = faceIndices.GetValue(1);
  68993. indices[offset + 2] = faceIndices.GetValue(2);
  68994. }
  68995. vertexData.indices = indices;
  68996. }
  68997. finally {
  68998. module.destroy(faceIndices);
  68999. }
  69000. }
  69001. for (var kind in attributes) {
  69002. var uniqueId = attributes[kind];
  69003. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  69004. var dracoData = new module.DracoFloat32Array();
  69005. try {
  69006. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  69007. var babylonData = new Float32Array(numPoints * attribute.num_components());
  69008. for (var i = 0; i < babylonData.length; i++) {
  69009. babylonData[i] = dracoData.GetValue(i);
  69010. }
  69011. vertexData.set(babylonData, kind);
  69012. }
  69013. finally {
  69014. module.destroy(dracoData);
  69015. }
  69016. }
  69017. }
  69018. finally {
  69019. if (geometry) {
  69020. module.destroy(geometry);
  69021. }
  69022. module.destroy(decoder);
  69023. module.destroy(buffer);
  69024. }
  69025. return vertexData;
  69026. });
  69027. };
  69028. DracoCompression._GetDecoderModule = function () {
  69029. if (!DracoCompression._DecoderModulePromise) {
  69030. var promise = null;
  69031. var config_1 = {};
  69032. if (typeof DracoDecoderModule !== "undefined") {
  69033. promise = Promise.resolve();
  69034. }
  69035. else {
  69036. var decoder = DracoCompression.Configuration.decoder;
  69037. if (decoder) {
  69038. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69039. promise = Promise.all([
  69040. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69041. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69042. config_1.wasmBinary = data;
  69043. })
  69044. ]);
  69045. }
  69046. else if (decoder.fallbackUrl) {
  69047. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69048. }
  69049. }
  69050. }
  69051. if (!promise) {
  69052. throw new Error("Draco decoder module is not available");
  69053. }
  69054. DracoCompression._DecoderModulePromise = promise.then(function () {
  69055. return new Promise(function (resolve) {
  69056. config_1.onModuleLoaded = function (decoderModule) {
  69057. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69058. resolve({ module: decoderModule });
  69059. };
  69060. DracoDecoderModule(config_1);
  69061. });
  69062. });
  69063. }
  69064. return DracoCompression._DecoderModulePromise;
  69065. };
  69066. DracoCompression._LoadScriptAsync = function (url) {
  69067. return new Promise(function (resolve, reject) {
  69068. BABYLON.Tools.LoadScript(url, function () {
  69069. resolve();
  69070. }, function (message) {
  69071. reject(new Error(message));
  69072. });
  69073. });
  69074. };
  69075. DracoCompression._LoadFileAsync = function (url) {
  69076. return new Promise(function (resolve, reject) {
  69077. BABYLON.Tools.LoadFile(url, function (data) {
  69078. resolve(data);
  69079. }, undefined, undefined, true, function (request, exception) {
  69080. reject(exception);
  69081. });
  69082. });
  69083. };
  69084. /**
  69085. * The configuration. Defaults to the following urls:
  69086. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69087. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69088. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69089. */
  69090. DracoCompression.Configuration = {
  69091. decoder: {
  69092. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69093. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69094. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69095. }
  69096. };
  69097. return DracoCompression;
  69098. }());
  69099. BABYLON.DracoCompression = DracoCompression;
  69100. })(BABYLON || (BABYLON = {}));
  69101. //# sourceMappingURL=babylon.dracoCompression.js.map
  69102. var BABYLON;
  69103. (function (BABYLON) {
  69104. // Sets the default audio engine to Babylon JS.
  69105. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  69106. /**
  69107. * This represents the default audio engine used in babylon.
  69108. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69109. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69110. */
  69111. var AudioEngine = /** @class */ (function () {
  69112. /**
  69113. * Instantiates a new audio engine.
  69114. *
  69115. * There should be only one per page as some browsers restrict the number
  69116. * of audio contexts you can create.
  69117. * @param hostElement defines the host element where to display the mute icon if necessary
  69118. */
  69119. function AudioEngine(hostElement) {
  69120. if (hostElement === void 0) { hostElement = null; }
  69121. var _this = this;
  69122. this._audioContext = null;
  69123. this._audioContextInitialized = false;
  69124. this._muteButton = null;
  69125. /**
  69126. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69127. */
  69128. this.canUseWebAudio = false;
  69129. /**
  69130. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69131. * @ignoreNaming
  69132. */
  69133. this.WarnedWebAudioUnsupported = false;
  69134. /**
  69135. * Gets whether or not mp3 are supported by your browser.
  69136. */
  69137. this.isMP3supported = false;
  69138. /**
  69139. * Gets whether or not ogg are supported by your browser.
  69140. */
  69141. this.isOGGsupported = false;
  69142. /**
  69143. * Gets whether audio has been unlocked on the device.
  69144. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69145. * a user interaction has happened.
  69146. */
  69147. this.unlocked = true;
  69148. /**
  69149. * Defines if the audio engine relies on a custom unlocked button.
  69150. * In this case, the embedded button will not be displayed.
  69151. */
  69152. this.useCustomUnlockedButton = false;
  69153. /**
  69154. * Event raised when audio has been unlocked on the browser.
  69155. */
  69156. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69157. /**
  69158. * Event raised when audio has been locked on the browser.
  69159. */
  69160. this.onAudioLockedObservable = new BABYLON.Observable();
  69161. this._tryToRun = false;
  69162. this._onResize = function () {
  69163. _this._moveButtonToTopLeft();
  69164. };
  69165. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69166. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69167. this.canUseWebAudio = true;
  69168. }
  69169. var audioElem = document.createElement('audio');
  69170. this._hostElement = hostElement;
  69171. try {
  69172. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69173. this.isMP3supported = true;
  69174. }
  69175. }
  69176. catch (e) {
  69177. // protect error during capability check.
  69178. }
  69179. try {
  69180. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69181. this.isOGGsupported = true;
  69182. }
  69183. }
  69184. catch (e) {
  69185. // protect error during capability check.
  69186. }
  69187. }
  69188. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69189. /**
  69190. * Gets the current AudioContext if available.
  69191. */
  69192. get: function () {
  69193. if (!this._audioContextInitialized) {
  69194. this._initializeAudioContext();
  69195. }
  69196. else {
  69197. if (!this.unlocked && !this._muteButton) {
  69198. this._displayMuteButton();
  69199. }
  69200. }
  69201. return this._audioContext;
  69202. },
  69203. enumerable: true,
  69204. configurable: true
  69205. });
  69206. /**
  69207. * Flags the audio engine in Locked state.
  69208. * This happens due to new browser policies preventing audio to autoplay.
  69209. */
  69210. AudioEngine.prototype.lock = function () {
  69211. this._triggerSuspendedState();
  69212. };
  69213. /**
  69214. * Unlocks the audio engine once a user action has been done on the dom.
  69215. * This is helpful to resume play once browser policies have been satisfied.
  69216. */
  69217. AudioEngine.prototype.unlock = function () {
  69218. this._triggerRunningState();
  69219. };
  69220. AudioEngine.prototype._resumeAudioContext = function () {
  69221. var result;
  69222. if (this._audioContext.resume) {
  69223. result = this._audioContext.resume();
  69224. }
  69225. return result || Promise.resolve();
  69226. };
  69227. AudioEngine.prototype._initializeAudioContext = function () {
  69228. try {
  69229. if (this.canUseWebAudio) {
  69230. this._audioContext = new AudioContext();
  69231. // create a global volume gain node
  69232. this.masterGain = this._audioContext.createGain();
  69233. this.masterGain.gain.value = 1;
  69234. this.masterGain.connect(this._audioContext.destination);
  69235. this._audioContextInitialized = true;
  69236. if (this._audioContext.state === "running") {
  69237. // Do not wait for the promise to unlock.
  69238. this._triggerRunningState();
  69239. }
  69240. }
  69241. }
  69242. catch (e) {
  69243. this.canUseWebAudio = false;
  69244. BABYLON.Tools.Error("Web Audio: " + e.message);
  69245. }
  69246. };
  69247. AudioEngine.prototype._triggerRunningState = function () {
  69248. var _this = this;
  69249. if (this._tryToRun) {
  69250. return;
  69251. }
  69252. this._tryToRun = true;
  69253. this._resumeAudioContext()
  69254. .then(function () {
  69255. _this._tryToRun = false;
  69256. if (_this._muteButton) {
  69257. _this._hideMuteButton();
  69258. }
  69259. }).catch(function () {
  69260. _this._tryToRun = false;
  69261. _this.unlocked = false;
  69262. });
  69263. // Notify users that the audio stack is unlocked/unmuted
  69264. this.unlocked = true;
  69265. this.onAudioUnlockedObservable.notifyObservers(this);
  69266. };
  69267. AudioEngine.prototype._triggerSuspendedState = function () {
  69268. this.unlocked = false;
  69269. this.onAudioLockedObservable.notifyObservers(this);
  69270. this._displayMuteButton();
  69271. };
  69272. AudioEngine.prototype._displayMuteButton = function () {
  69273. var _this = this;
  69274. if (this.useCustomUnlockedButton) {
  69275. return;
  69276. }
  69277. this._muteButton = document.createElement("BUTTON");
  69278. this._muteButton.className = "babylonUnmuteIcon";
  69279. this._muteButton.id = "babylonUnmuteIconBtn";
  69280. this._muteButton.title = "Unmute";
  69281. 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) }";
  69282. var style = document.createElement('style');
  69283. style.appendChild(document.createTextNode(css));
  69284. document.getElementsByTagName('head')[0].appendChild(style);
  69285. document.body.appendChild(this._muteButton);
  69286. this._moveButtonToTopLeft();
  69287. this._muteButton.addEventListener('touchend', function () {
  69288. _this._triggerRunningState();
  69289. }, true);
  69290. this._muteButton.addEventListener('click', function () {
  69291. _this._triggerRunningState();
  69292. }, true);
  69293. window.addEventListener("resize", this._onResize);
  69294. };
  69295. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69296. if (this._hostElement && this._muteButton) {
  69297. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  69298. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  69299. }
  69300. };
  69301. AudioEngine.prototype._hideMuteButton = function () {
  69302. if (this._muteButton) {
  69303. document.body.removeChild(this._muteButton);
  69304. this._muteButton = null;
  69305. }
  69306. };
  69307. /**
  69308. * Destroy and release the resources associated with the audio ccontext.
  69309. */
  69310. AudioEngine.prototype.dispose = function () {
  69311. if (this.canUseWebAudio && this._audioContextInitialized) {
  69312. if (this._connectedAnalyser && this._audioContext) {
  69313. this._connectedAnalyser.stopDebugCanvas();
  69314. this._connectedAnalyser.dispose();
  69315. this.masterGain.disconnect();
  69316. this.masterGain.connect(this._audioContext.destination);
  69317. this._connectedAnalyser = null;
  69318. }
  69319. this.masterGain.gain.value = 1;
  69320. }
  69321. this.WarnedWebAudioUnsupported = false;
  69322. this._hideMuteButton();
  69323. window.removeEventListener("resize", this._onResize);
  69324. this.onAudioUnlockedObservable.clear();
  69325. this.onAudioLockedObservable.clear();
  69326. };
  69327. /**
  69328. * Gets the global volume sets on the master gain.
  69329. * @returns the global volume if set or -1 otherwise
  69330. */
  69331. AudioEngine.prototype.getGlobalVolume = function () {
  69332. if (this.canUseWebAudio && this._audioContextInitialized) {
  69333. return this.masterGain.gain.value;
  69334. }
  69335. else {
  69336. return -1;
  69337. }
  69338. };
  69339. /**
  69340. * Sets the global volume of your experience (sets on the master gain).
  69341. * @param newVolume Defines the new global volume of the application
  69342. */
  69343. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69344. if (this.canUseWebAudio && this._audioContextInitialized) {
  69345. this.masterGain.gain.value = newVolume;
  69346. }
  69347. };
  69348. /**
  69349. * Connect the audio engine to an audio analyser allowing some amazing
  69350. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69351. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69352. * @param analyser The analyser to connect to the engine
  69353. */
  69354. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69355. if (this._connectedAnalyser) {
  69356. this._connectedAnalyser.stopDebugCanvas();
  69357. }
  69358. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69359. this._connectedAnalyser = analyser;
  69360. this.masterGain.disconnect();
  69361. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69362. }
  69363. };
  69364. return AudioEngine;
  69365. }());
  69366. BABYLON.AudioEngine = AudioEngine;
  69367. })(BABYLON || (BABYLON = {}));
  69368. //# sourceMappingURL=babylon.audioEngine.js.map
  69369. var BABYLON;
  69370. (function (BABYLON) {
  69371. /**
  69372. * Defines a sound that can be played in the application.
  69373. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69374. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69375. */
  69376. var Sound = /** @class */ (function () {
  69377. /**
  69378. * Create a sound and attach it to a scene
  69379. * @param name Name of your sound
  69380. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69381. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69382. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69383. */
  69384. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69385. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69386. var _this = this;
  69387. /**
  69388. * Does the sound autoplay once loaded.
  69389. */
  69390. this.autoplay = false;
  69391. /**
  69392. * Does the sound loop after it finishes playing once.
  69393. */
  69394. this.loop = false;
  69395. /**
  69396. * Does the sound use a custom attenuation curve to simulate the falloff
  69397. * happening when the source gets further away from the camera.
  69398. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69399. */
  69400. this.useCustomAttenuation = false;
  69401. /**
  69402. * Is this sound currently played.
  69403. */
  69404. this.isPlaying = false;
  69405. /**
  69406. * Is this sound currently paused.
  69407. */
  69408. this.isPaused = false;
  69409. /**
  69410. * Does this sound enables spatial sound.
  69411. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69412. */
  69413. this.spatialSound = false;
  69414. /**
  69415. * Define the reference distance the sound should be heard perfectly.
  69416. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69417. */
  69418. this.refDistance = 1;
  69419. /**
  69420. * Define the roll off factor of spatial sounds.
  69421. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69422. */
  69423. this.rolloffFactor = 1;
  69424. /**
  69425. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69426. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69427. */
  69428. this.maxDistance = 100;
  69429. /**
  69430. * Define the distance attenuation model the sound will follow.
  69431. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69432. */
  69433. this.distanceModel = "linear";
  69434. /**
  69435. * Observable event when the current playing sound finishes.
  69436. */
  69437. this.onEndedObservable = new BABYLON.Observable();
  69438. this._panningModel = "equalpower";
  69439. this._playbackRate = 1;
  69440. this._streaming = false;
  69441. this._startTime = 0;
  69442. this._startOffset = 0;
  69443. this._position = BABYLON.Vector3.Zero();
  69444. /** @hidden */
  69445. this._positionInEmitterSpace = false;
  69446. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69447. this._volume = 1;
  69448. this._isReadyToPlay = false;
  69449. this._isDirectional = false;
  69450. // Used if you'd like to create a directional sound.
  69451. // If not set, the sound will be omnidirectional
  69452. this._coneInnerAngle = 360;
  69453. this._coneOuterAngle = 360;
  69454. this._coneOuterGain = 0;
  69455. this._isOutputConnected = false;
  69456. this._urlType = "Unknown";
  69457. this.name = name;
  69458. this._scene = scene;
  69459. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69460. if (!compo) {
  69461. compo = new BABYLON.AudioSceneComponent(scene);
  69462. scene._addComponent(compo);
  69463. }
  69464. this._readyToPlayCallback = readyToPlayCallback;
  69465. // Default custom attenuation function is a linear attenuation
  69466. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69467. if (currentDistance < maxDistance) {
  69468. return currentVolume * (1 - currentDistance / maxDistance);
  69469. }
  69470. else {
  69471. return 0;
  69472. }
  69473. };
  69474. if (options) {
  69475. this.autoplay = options.autoplay || false;
  69476. this.loop = options.loop || false;
  69477. // if volume === 0, we need another way to check this option
  69478. if (options.volume !== undefined) {
  69479. this._volume = options.volume;
  69480. }
  69481. this.spatialSound = options.spatialSound || false;
  69482. this.maxDistance = options.maxDistance || 100;
  69483. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69484. this.rolloffFactor = options.rolloffFactor || 1;
  69485. this.refDistance = options.refDistance || 1;
  69486. this.distanceModel = options.distanceModel || "linear";
  69487. this._playbackRate = options.playbackRate || 1;
  69488. this._streaming = options.streaming || false;
  69489. }
  69490. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69491. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69492. this._soundGain.gain.value = this._volume;
  69493. this._inputAudioNode = this._soundGain;
  69494. this._outputAudioNode = this._soundGain;
  69495. if (this.spatialSound) {
  69496. this._createSpatialParameters();
  69497. }
  69498. this._scene.mainSoundTrack.AddSound(this);
  69499. var validParameter = true;
  69500. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69501. if (urlOrArrayBuffer) {
  69502. try {
  69503. if (typeof (urlOrArrayBuffer) === "string") {
  69504. this._urlType = "String";
  69505. }
  69506. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69507. this._urlType = "ArrayBuffer";
  69508. }
  69509. else if (urlOrArrayBuffer instanceof MediaStream) {
  69510. this._urlType = "MediaStream";
  69511. }
  69512. else if (Array.isArray(urlOrArrayBuffer)) {
  69513. this._urlType = "Array";
  69514. }
  69515. var urls = [];
  69516. var codecSupportedFound = false;
  69517. switch (this._urlType) {
  69518. case "MediaStream":
  69519. this._streaming = true;
  69520. this._isReadyToPlay = true;
  69521. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69522. if (this.autoplay) {
  69523. this.play();
  69524. }
  69525. if (this._readyToPlayCallback) {
  69526. this._readyToPlayCallback();
  69527. }
  69528. break;
  69529. case "ArrayBuffer":
  69530. if (urlOrArrayBuffer.byteLength > 0) {
  69531. codecSupportedFound = true;
  69532. this._soundLoaded(urlOrArrayBuffer);
  69533. }
  69534. break;
  69535. case "String":
  69536. urls.push(urlOrArrayBuffer);
  69537. case "Array":
  69538. if (urls.length === 0)
  69539. urls = urlOrArrayBuffer;
  69540. // If we found a supported format, we load it immediately and stop the loop
  69541. for (var i = 0; i < urls.length; i++) {
  69542. var url = urls[i];
  69543. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69544. codecSupportedFound = true;
  69545. }
  69546. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69547. codecSupportedFound = true;
  69548. }
  69549. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69550. codecSupportedFound = true;
  69551. }
  69552. if (url.indexOf("blob:") !== -1) {
  69553. codecSupportedFound = true;
  69554. }
  69555. if (codecSupportedFound) {
  69556. // Loading sound using XHR2
  69557. if (!this._streaming) {
  69558. this._scene._loadFile(url, function (data) {
  69559. _this._soundLoaded(data);
  69560. }, undefined, true, true, function (exception) {
  69561. if (exception) {
  69562. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69563. }
  69564. BABYLON.Tools.Error("Sound creation aborted.");
  69565. _this._scene.mainSoundTrack.RemoveSound(_this);
  69566. });
  69567. }
  69568. // Streaming sound using HTML5 Audio tag
  69569. else {
  69570. this._htmlAudioElement = new Audio(url);
  69571. this._htmlAudioElement.controls = false;
  69572. this._htmlAudioElement.loop = this.loop;
  69573. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69574. this._htmlAudioElement.preload = "auto";
  69575. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69576. _this._isReadyToPlay = true;
  69577. if (_this.autoplay) {
  69578. _this.play();
  69579. }
  69580. if (_this._readyToPlayCallback) {
  69581. _this._readyToPlayCallback();
  69582. }
  69583. });
  69584. document.body.appendChild(this._htmlAudioElement);
  69585. this._htmlAudioElement.load();
  69586. }
  69587. break;
  69588. }
  69589. }
  69590. break;
  69591. default:
  69592. validParameter = false;
  69593. break;
  69594. }
  69595. if (!validParameter) {
  69596. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69597. }
  69598. else {
  69599. if (!codecSupportedFound) {
  69600. this._isReadyToPlay = true;
  69601. // Simulating a ready to play event to avoid breaking code path
  69602. if (this._readyToPlayCallback) {
  69603. window.setTimeout(function () {
  69604. if (_this._readyToPlayCallback) {
  69605. _this._readyToPlayCallback();
  69606. }
  69607. }, 1000);
  69608. }
  69609. }
  69610. }
  69611. }
  69612. catch (ex) {
  69613. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69614. this._scene.mainSoundTrack.RemoveSound(this);
  69615. }
  69616. }
  69617. }
  69618. else {
  69619. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69620. this._scene.mainSoundTrack.AddSound(this);
  69621. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69622. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69623. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69624. }
  69625. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69626. if (this._readyToPlayCallback) {
  69627. window.setTimeout(function () {
  69628. if (_this._readyToPlayCallback) {
  69629. _this._readyToPlayCallback();
  69630. }
  69631. }, 1000);
  69632. }
  69633. }
  69634. }
  69635. /**
  69636. * Release the sound and its associated resources
  69637. */
  69638. Sound.prototype.dispose = function () {
  69639. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69640. if (this.isPlaying) {
  69641. this.stop();
  69642. }
  69643. this._isReadyToPlay = false;
  69644. if (this.soundTrackId === -1) {
  69645. this._scene.mainSoundTrack.RemoveSound(this);
  69646. }
  69647. else if (this._scene.soundTracks) {
  69648. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69649. }
  69650. if (this._soundGain) {
  69651. this._soundGain.disconnect();
  69652. this._soundGain = null;
  69653. }
  69654. if (this._soundPanner) {
  69655. this._soundPanner.disconnect();
  69656. this._soundPanner = null;
  69657. }
  69658. if (this._soundSource) {
  69659. this._soundSource.disconnect();
  69660. this._soundSource = null;
  69661. }
  69662. this._audioBuffer = null;
  69663. if (this._htmlAudioElement) {
  69664. this._htmlAudioElement.pause();
  69665. this._htmlAudioElement.src = "";
  69666. document.body.removeChild(this._htmlAudioElement);
  69667. }
  69668. if (this._streamingSource) {
  69669. this._streamingSource.disconnect();
  69670. }
  69671. if (this._connectedMesh && this._registerFunc) {
  69672. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69673. this._connectedMesh = null;
  69674. }
  69675. }
  69676. };
  69677. /**
  69678. * Gets if the sounds is ready to be played or not.
  69679. * @returns true if ready, otherwise false
  69680. */
  69681. Sound.prototype.isReady = function () {
  69682. return this._isReadyToPlay;
  69683. };
  69684. Sound.prototype._soundLoaded = function (audioData) {
  69685. var _this = this;
  69686. if (!BABYLON.Engine.audioEngine.audioContext) {
  69687. return;
  69688. }
  69689. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69690. _this._audioBuffer = buffer;
  69691. _this._isReadyToPlay = true;
  69692. if (_this.autoplay) {
  69693. _this.play();
  69694. }
  69695. if (_this._readyToPlayCallback) {
  69696. _this._readyToPlayCallback();
  69697. }
  69698. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69699. };
  69700. /**
  69701. * Sets the data of the sound from an audiobuffer
  69702. * @param audioBuffer The audioBuffer containing the data
  69703. */
  69704. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69706. this._audioBuffer = audioBuffer;
  69707. this._isReadyToPlay = true;
  69708. }
  69709. };
  69710. /**
  69711. * Updates the current sounds options such as maxdistance, loop...
  69712. * @param options A JSON object containing values named as the object properties
  69713. */
  69714. Sound.prototype.updateOptions = function (options) {
  69715. if (options) {
  69716. this.loop = options.loop || this.loop;
  69717. this.maxDistance = options.maxDistance || this.maxDistance;
  69718. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69719. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69720. this.refDistance = options.refDistance || this.refDistance;
  69721. this.distanceModel = options.distanceModel || this.distanceModel;
  69722. this._playbackRate = options.playbackRate || this._playbackRate;
  69723. this._updateSpatialParameters();
  69724. if (this.isPlaying) {
  69725. if (this._streaming && this._htmlAudioElement) {
  69726. this._htmlAudioElement.playbackRate = this._playbackRate;
  69727. }
  69728. else {
  69729. if (this._soundSource) {
  69730. this._soundSource.playbackRate.value = this._playbackRate;
  69731. }
  69732. }
  69733. }
  69734. }
  69735. };
  69736. Sound.prototype._createSpatialParameters = function () {
  69737. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69738. if (this._scene.headphone) {
  69739. this._panningModel = "HRTF";
  69740. }
  69741. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69742. this._updateSpatialParameters();
  69743. this._soundPanner.connect(this._outputAudioNode);
  69744. this._inputAudioNode = this._soundPanner;
  69745. }
  69746. };
  69747. Sound.prototype._updateSpatialParameters = function () {
  69748. if (this.spatialSound && this._soundPanner) {
  69749. if (this.useCustomAttenuation) {
  69750. // Tricks to disable in a way embedded Web Audio attenuation
  69751. this._soundPanner.distanceModel = "linear";
  69752. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69753. this._soundPanner.refDistance = 1;
  69754. this._soundPanner.rolloffFactor = 1;
  69755. this._soundPanner.panningModel = this._panningModel;
  69756. }
  69757. else {
  69758. this._soundPanner.distanceModel = this.distanceModel;
  69759. this._soundPanner.maxDistance = this.maxDistance;
  69760. this._soundPanner.refDistance = this.refDistance;
  69761. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69762. this._soundPanner.panningModel = this._panningModel;
  69763. }
  69764. }
  69765. };
  69766. /**
  69767. * Switch the panning model to HRTF:
  69768. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69769. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69770. */
  69771. Sound.prototype.switchPanningModelToHRTF = function () {
  69772. this._panningModel = "HRTF";
  69773. this._switchPanningModel();
  69774. };
  69775. /**
  69776. * Switch the panning model to Equal Power:
  69777. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69778. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69779. */
  69780. Sound.prototype.switchPanningModelToEqualPower = function () {
  69781. this._panningModel = "equalpower";
  69782. this._switchPanningModel();
  69783. };
  69784. Sound.prototype._switchPanningModel = function () {
  69785. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69786. this._soundPanner.panningModel = this._panningModel;
  69787. }
  69788. };
  69789. /**
  69790. * Connect this sound to a sound track audio node like gain...
  69791. * @param soundTrackAudioNode the sound track audio node to connect to
  69792. */
  69793. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69794. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69795. if (this._isOutputConnected) {
  69796. this._outputAudioNode.disconnect();
  69797. }
  69798. this._outputAudioNode.connect(soundTrackAudioNode);
  69799. this._isOutputConnected = true;
  69800. }
  69801. };
  69802. /**
  69803. * Transform this sound into a directional source
  69804. * @param coneInnerAngle Size of the inner cone in degree
  69805. * @param coneOuterAngle Size of the outer cone in degree
  69806. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69807. */
  69808. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69809. if (coneOuterAngle < coneInnerAngle) {
  69810. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69811. return;
  69812. }
  69813. this._coneInnerAngle = coneInnerAngle;
  69814. this._coneOuterAngle = coneOuterAngle;
  69815. this._coneOuterGain = coneOuterGain;
  69816. this._isDirectional = true;
  69817. if (this.isPlaying && this.loop) {
  69818. this.stop();
  69819. this.play();
  69820. }
  69821. };
  69822. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69823. /**
  69824. * Gets or sets the inner angle for the directional cone.
  69825. */
  69826. get: function () {
  69827. return this._coneInnerAngle;
  69828. },
  69829. /**
  69830. * Gets or sets the inner angle for the directional cone.
  69831. */
  69832. set: function (value) {
  69833. if (value != this._coneInnerAngle) {
  69834. if (this._coneOuterAngle < value) {
  69835. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69836. return;
  69837. }
  69838. this._coneInnerAngle = value;
  69839. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69840. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69841. }
  69842. }
  69843. },
  69844. enumerable: true,
  69845. configurable: true
  69846. });
  69847. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69848. /**
  69849. * Gets or sets the outer angle for the directional cone.
  69850. */
  69851. get: function () {
  69852. return this._coneOuterAngle;
  69853. },
  69854. /**
  69855. * Gets or sets the outer angle for the directional cone.
  69856. */
  69857. set: function (value) {
  69858. if (value != this._coneOuterAngle) {
  69859. if (value < this._coneInnerAngle) {
  69860. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69861. return;
  69862. }
  69863. this._coneOuterAngle = value;
  69864. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69865. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69866. }
  69867. }
  69868. },
  69869. enumerable: true,
  69870. configurable: true
  69871. });
  69872. /**
  69873. * Sets the position of the emitter if spatial sound is enabled
  69874. * @param newPosition Defines the new posisiton
  69875. */
  69876. Sound.prototype.setPosition = function (newPosition) {
  69877. this._position = newPosition;
  69878. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69879. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69880. }
  69881. };
  69882. /**
  69883. * Sets the local direction of the emitter if spatial sound is enabled
  69884. * @param newLocalDirection Defines the new local direction
  69885. */
  69886. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69887. this._localDirection = newLocalDirection;
  69888. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69889. this._updateDirection();
  69890. }
  69891. };
  69892. Sound.prototype._updateDirection = function () {
  69893. if (!this._connectedMesh || !this._soundPanner) {
  69894. return;
  69895. }
  69896. var mat = this._connectedMesh.getWorldMatrix();
  69897. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69898. direction.normalize();
  69899. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69900. };
  69901. /** @hidden */
  69902. Sound.prototype.updateDistanceFromListener = function () {
  69903. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69904. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69905. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69906. }
  69907. };
  69908. /**
  69909. * Sets a new custom attenuation function for the sound.
  69910. * @param callback Defines the function used for the attenuation
  69911. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69912. */
  69913. Sound.prototype.setAttenuationFunction = function (callback) {
  69914. this._customAttenuationFunction = callback;
  69915. };
  69916. /**
  69917. * Play the sound
  69918. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69919. * @param offset (optional) Start the sound setting it at a specific time
  69920. */
  69921. Sound.prototype.play = function (time, offset) {
  69922. var _this = this;
  69923. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69924. try {
  69925. if (this._startOffset < 0) {
  69926. time = -this._startOffset;
  69927. this._startOffset = 0;
  69928. }
  69929. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69930. if (!this._soundSource || !this._streamingSource) {
  69931. if (this.spatialSound && this._soundPanner) {
  69932. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69933. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69934. }
  69935. if (this._isDirectional) {
  69936. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69937. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69938. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69939. if (this._connectedMesh) {
  69940. this._updateDirection();
  69941. }
  69942. else {
  69943. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69944. }
  69945. }
  69946. }
  69947. }
  69948. if (this._streaming) {
  69949. if (!this._streamingSource) {
  69950. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69951. this._htmlAudioElement.onended = function () { _this._onended(); };
  69952. this._htmlAudioElement.playbackRate = this._playbackRate;
  69953. }
  69954. this._streamingSource.disconnect();
  69955. this._streamingSource.connect(this._inputAudioNode);
  69956. if (this._htmlAudioElement) {
  69957. // required to manage properly the new suspended default state of Chrome
  69958. // When the option 'streaming: true' is used, we need first to wait for
  69959. // the audio engine to be unlocked by a user gesture before trying to play
  69960. // an HTML Audio elememt
  69961. var tryToPlay = function () {
  69962. if (BABYLON.Engine.audioEngine.unlocked) {
  69963. var playPromise = _this._htmlAudioElement.play();
  69964. // In browsers that don’t yet support this functionality,
  69965. // playPromise won’t be defined.
  69966. if (playPromise !== undefined) {
  69967. playPromise.catch(function (error) {
  69968. // Automatic playback failed.
  69969. // Waiting for the audio engine to be unlocked by user click on unmute
  69970. BABYLON.Engine.audioEngine.lock();
  69971. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69972. });
  69973. }
  69974. }
  69975. else {
  69976. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69977. }
  69978. };
  69979. tryToPlay();
  69980. }
  69981. }
  69982. else {
  69983. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  69984. this._soundSource.buffer = this._audioBuffer;
  69985. this._soundSource.connect(this._inputAudioNode);
  69986. this._soundSource.loop = this.loop;
  69987. this._soundSource.playbackRate.value = this._playbackRate;
  69988. this._soundSource.onended = function () { _this._onended(); };
  69989. if (this._soundSource.buffer) {
  69990. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  69991. }
  69992. }
  69993. this._startTime = startTime;
  69994. this.isPlaying = true;
  69995. this.isPaused = false;
  69996. }
  69997. catch (ex) {
  69998. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  69999. }
  70000. }
  70001. };
  70002. Sound.prototype._onended = function () {
  70003. this.isPlaying = false;
  70004. if (this.onended) {
  70005. this.onended();
  70006. }
  70007. this.onEndedObservable.notifyObservers(this);
  70008. };
  70009. /**
  70010. * Stop the sound
  70011. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  70012. */
  70013. Sound.prototype.stop = function (time) {
  70014. if (this.isPlaying) {
  70015. if (this._streaming) {
  70016. if (this._htmlAudioElement) {
  70017. this._htmlAudioElement.pause();
  70018. // Test needed for Firefox or it will generate an Invalid State Error
  70019. if (this._htmlAudioElement.currentTime > 0) {
  70020. this._htmlAudioElement.currentTime = 0;
  70021. }
  70022. }
  70023. else {
  70024. this._streamingSource.disconnect();
  70025. }
  70026. }
  70027. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70028. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70029. this._soundSource.stop(stopTime);
  70030. this._soundSource.onended = function () { };
  70031. if (!this.isPaused) {
  70032. this._startOffset = 0;
  70033. }
  70034. }
  70035. this.isPlaying = false;
  70036. }
  70037. };
  70038. /**
  70039. * Put the sound in pause
  70040. */
  70041. Sound.prototype.pause = function () {
  70042. if (this.isPlaying) {
  70043. this.isPaused = true;
  70044. if (this._streaming) {
  70045. if (this._htmlAudioElement) {
  70046. this._htmlAudioElement.pause();
  70047. }
  70048. else {
  70049. this._streamingSource.disconnect();
  70050. }
  70051. }
  70052. else if (BABYLON.Engine.audioEngine.audioContext) {
  70053. this.stop(0);
  70054. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70055. }
  70056. }
  70057. };
  70058. /**
  70059. * Sets a dedicated volume for this sounds
  70060. * @param newVolume Define the new volume of the sound
  70061. * @param time Define in how long the sound should be at this value
  70062. */
  70063. Sound.prototype.setVolume = function (newVolume, time) {
  70064. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70065. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70066. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70067. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70068. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70069. }
  70070. else {
  70071. this._soundGain.gain.value = newVolume;
  70072. }
  70073. }
  70074. this._volume = newVolume;
  70075. };
  70076. /**
  70077. * Set the sound play back rate
  70078. * @param newPlaybackRate Define the playback rate the sound should be played at
  70079. */
  70080. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70081. this._playbackRate = newPlaybackRate;
  70082. if (this.isPlaying) {
  70083. if (this._streaming && this._htmlAudioElement) {
  70084. this._htmlAudioElement.playbackRate = this._playbackRate;
  70085. }
  70086. else if (this._soundSource) {
  70087. this._soundSource.playbackRate.value = this._playbackRate;
  70088. }
  70089. }
  70090. };
  70091. /**
  70092. * Gets the volume of the sound.
  70093. * @returns the volume of the sound
  70094. */
  70095. Sound.prototype.getVolume = function () {
  70096. return this._volume;
  70097. };
  70098. /**
  70099. * Attach the sound to a dedicated mesh
  70100. * @param meshToConnectTo The mesh to connect the sound with
  70101. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70102. */
  70103. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70104. var _this = this;
  70105. if (this._connectedMesh && this._registerFunc) {
  70106. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70107. this._registerFunc = null;
  70108. }
  70109. this._connectedMesh = meshToConnectTo;
  70110. if (!this.spatialSound) {
  70111. this.spatialSound = true;
  70112. this._createSpatialParameters();
  70113. if (this.isPlaying && this.loop) {
  70114. this.stop();
  70115. this.play();
  70116. }
  70117. }
  70118. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70119. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70120. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70121. };
  70122. /**
  70123. * Detach the sound from the previously attached mesh
  70124. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70125. */
  70126. Sound.prototype.detachFromMesh = function () {
  70127. if (this._connectedMesh && this._registerFunc) {
  70128. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70129. this._registerFunc = null;
  70130. this._connectedMesh = null;
  70131. }
  70132. };
  70133. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70134. if (!node.getBoundingInfo) {
  70135. return;
  70136. }
  70137. var mesh = node;
  70138. if (this._positionInEmitterSpace) {
  70139. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70140. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70141. }
  70142. else {
  70143. var boundingInfo = mesh.getBoundingInfo();
  70144. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70145. }
  70146. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70147. this._updateDirection();
  70148. }
  70149. };
  70150. /**
  70151. * Clone the current sound in the scene.
  70152. * @returns the new sound clone
  70153. */
  70154. Sound.prototype.clone = function () {
  70155. var _this = this;
  70156. if (!this._streaming) {
  70157. var setBufferAndRun = function () {
  70158. if (_this._isReadyToPlay) {
  70159. clonedSound._audioBuffer = _this.getAudioBuffer();
  70160. clonedSound._isReadyToPlay = true;
  70161. if (clonedSound.autoplay) {
  70162. clonedSound.play();
  70163. }
  70164. }
  70165. else {
  70166. window.setTimeout(setBufferAndRun, 300);
  70167. }
  70168. };
  70169. var currentOptions = {
  70170. autoplay: this.autoplay, loop: this.loop,
  70171. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70172. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70173. refDistance: this.refDistance, distanceModel: this.distanceModel
  70174. };
  70175. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70176. if (this.useCustomAttenuation) {
  70177. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70178. }
  70179. clonedSound.setPosition(this._position);
  70180. clonedSound.setPlaybackRate(this._playbackRate);
  70181. setBufferAndRun();
  70182. return clonedSound;
  70183. }
  70184. // Can't clone a streaming sound
  70185. else {
  70186. return null;
  70187. }
  70188. };
  70189. /**
  70190. * Gets the current underlying audio buffer containing the data
  70191. * @returns the audio buffer
  70192. */
  70193. Sound.prototype.getAudioBuffer = function () {
  70194. return this._audioBuffer;
  70195. };
  70196. /**
  70197. * Serializes the Sound in a JSON representation
  70198. * @returns the JSON representation of the sound
  70199. */
  70200. Sound.prototype.serialize = function () {
  70201. var serializationObject = {
  70202. name: this.name,
  70203. url: this.name,
  70204. autoplay: this.autoplay,
  70205. loop: this.loop,
  70206. volume: this._volume,
  70207. spatialSound: this.spatialSound,
  70208. maxDistance: this.maxDistance,
  70209. rolloffFactor: this.rolloffFactor,
  70210. refDistance: this.refDistance,
  70211. distanceModel: this.distanceModel,
  70212. playbackRate: this._playbackRate,
  70213. panningModel: this._panningModel,
  70214. soundTrackId: this.soundTrackId
  70215. };
  70216. if (this.spatialSound) {
  70217. if (this._connectedMesh)
  70218. serializationObject.connectedMeshId = this._connectedMesh.id;
  70219. serializationObject.position = this._position.asArray();
  70220. serializationObject.refDistance = this.refDistance;
  70221. serializationObject.distanceModel = this.distanceModel;
  70222. serializationObject.isDirectional = this._isDirectional;
  70223. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70224. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70225. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70226. serializationObject.coneOuterGain = this._coneOuterGain;
  70227. }
  70228. return serializationObject;
  70229. };
  70230. /**
  70231. * Parse a JSON representation of a sound to innstantiate in a given scene
  70232. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70233. * @param scene Define the scene the new parsed sound should be created in
  70234. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70235. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70236. * @returns the newly parsed sound
  70237. */
  70238. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70239. var soundName = parsedSound.name;
  70240. var soundUrl;
  70241. if (parsedSound.url) {
  70242. soundUrl = rootUrl + parsedSound.url;
  70243. }
  70244. else {
  70245. soundUrl = rootUrl + soundName;
  70246. }
  70247. var options = {
  70248. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70249. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70250. rolloffFactor: parsedSound.rolloffFactor,
  70251. refDistance: parsedSound.refDistance,
  70252. distanceModel: parsedSound.distanceModel,
  70253. playbackRate: parsedSound.playbackRate
  70254. };
  70255. var newSound;
  70256. if (!sourceSound) {
  70257. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70258. scene._addPendingData(newSound);
  70259. }
  70260. else {
  70261. var setBufferAndRun = function () {
  70262. if (sourceSound._isReadyToPlay) {
  70263. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70264. newSound._isReadyToPlay = true;
  70265. if (newSound.autoplay) {
  70266. newSound.play();
  70267. }
  70268. }
  70269. else {
  70270. window.setTimeout(setBufferAndRun, 300);
  70271. }
  70272. };
  70273. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70274. setBufferAndRun();
  70275. }
  70276. if (parsedSound.position) {
  70277. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70278. newSound.setPosition(soundPosition);
  70279. }
  70280. if (parsedSound.isDirectional) {
  70281. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70282. if (parsedSound.localDirectionToMesh) {
  70283. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70284. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70285. }
  70286. }
  70287. if (parsedSound.connectedMeshId) {
  70288. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70289. if (connectedMesh) {
  70290. newSound.attachToMesh(connectedMesh);
  70291. }
  70292. }
  70293. return newSound;
  70294. };
  70295. return Sound;
  70296. }());
  70297. BABYLON.Sound = Sound;
  70298. })(BABYLON || (BABYLON = {}));
  70299. //# sourceMappingURL=babylon.sound.js.map
  70300. var BABYLON;
  70301. (function (BABYLON) {
  70302. /**
  70303. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70304. * It will be also used in a future release to apply effects on a specific track.
  70305. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70306. */
  70307. var SoundTrack = /** @class */ (function () {
  70308. /**
  70309. * Creates a new sound track.
  70310. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70311. * @param scene Define the scene the sound track belongs to
  70312. * @param options
  70313. */
  70314. function SoundTrack(scene, options) {
  70315. if (options === void 0) { options = {}; }
  70316. /**
  70317. * The unique identifier of the sound track in the scene.
  70318. */
  70319. this.id = -1;
  70320. this._isMainTrack = false;
  70321. this._isInitialized = false;
  70322. this._scene = scene;
  70323. this.soundCollection = new Array();
  70324. this._options = options;
  70325. if (!this._isMainTrack && this._scene.soundTracks) {
  70326. this._scene.soundTracks.push(this);
  70327. this.id = this._scene.soundTracks.length - 1;
  70328. }
  70329. }
  70330. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70331. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70332. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70333. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70334. if (this._options) {
  70335. if (this._options.volume) {
  70336. this._outputAudioNode.gain.value = this._options.volume;
  70337. }
  70338. if (this._options.mainTrack) {
  70339. this._isMainTrack = this._options.mainTrack;
  70340. }
  70341. }
  70342. this._isInitialized = true;
  70343. }
  70344. };
  70345. /**
  70346. * Release the sound track and its associated resources
  70347. */
  70348. SoundTrack.prototype.dispose = function () {
  70349. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70350. if (this._connectedAnalyser) {
  70351. this._connectedAnalyser.stopDebugCanvas();
  70352. }
  70353. while (this.soundCollection.length) {
  70354. this.soundCollection[0].dispose();
  70355. }
  70356. if (this._outputAudioNode) {
  70357. this._outputAudioNode.disconnect();
  70358. }
  70359. this._outputAudioNode = null;
  70360. }
  70361. };
  70362. /**
  70363. * Adds a sound to this sound track
  70364. * @param sound define the cound to add
  70365. * @ignoreNaming
  70366. */
  70367. SoundTrack.prototype.AddSound = function (sound) {
  70368. if (!this._isInitialized) {
  70369. this._initializeSoundTrackAudioGraph();
  70370. }
  70371. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70372. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70373. }
  70374. if (sound.soundTrackId) {
  70375. if (sound.soundTrackId === -1) {
  70376. this._scene.mainSoundTrack.RemoveSound(sound);
  70377. }
  70378. else if (this._scene.soundTracks) {
  70379. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70380. }
  70381. }
  70382. this.soundCollection.push(sound);
  70383. sound.soundTrackId = this.id;
  70384. };
  70385. /**
  70386. * Removes a sound to this sound track
  70387. * @param sound define the cound to remove
  70388. * @ignoreNaming
  70389. */
  70390. SoundTrack.prototype.RemoveSound = function (sound) {
  70391. var index = this.soundCollection.indexOf(sound);
  70392. if (index !== -1) {
  70393. this.soundCollection.splice(index, 1);
  70394. }
  70395. };
  70396. /**
  70397. * Set a global volume for the full sound track.
  70398. * @param newVolume Define the new volume of the sound track
  70399. */
  70400. SoundTrack.prototype.setVolume = function (newVolume) {
  70401. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70402. this._outputAudioNode.gain.value = newVolume;
  70403. }
  70404. };
  70405. /**
  70406. * Switch the panning model to HRTF:
  70407. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70408. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70409. */
  70410. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70411. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70412. for (var i = 0; i < this.soundCollection.length; i++) {
  70413. this.soundCollection[i].switchPanningModelToHRTF();
  70414. }
  70415. }
  70416. };
  70417. /**
  70418. * Switch the panning model to Equal Power:
  70419. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70420. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70421. */
  70422. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70423. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70424. for (var i = 0; i < this.soundCollection.length; i++) {
  70425. this.soundCollection[i].switchPanningModelToEqualPower();
  70426. }
  70427. }
  70428. };
  70429. /**
  70430. * Connect the sound track to an audio analyser allowing some amazing
  70431. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70432. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70433. * @param analyser The analyser to connect to the engine
  70434. */
  70435. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70436. if (this._connectedAnalyser) {
  70437. this._connectedAnalyser.stopDebugCanvas();
  70438. }
  70439. this._connectedAnalyser = analyser;
  70440. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70441. this._outputAudioNode.disconnect();
  70442. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70443. }
  70444. };
  70445. return SoundTrack;
  70446. }());
  70447. BABYLON.SoundTrack = SoundTrack;
  70448. })(BABYLON || (BABYLON = {}));
  70449. //# sourceMappingURL=babylon.soundtrack.js.map
  70450. var BABYLON;
  70451. (function (BABYLON) {
  70452. /**
  70453. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70454. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70455. */
  70456. var Analyser = /** @class */ (function () {
  70457. /**
  70458. * Creates a new analyser
  70459. * @param scene defines hosting scene
  70460. */
  70461. function Analyser(scene) {
  70462. /**
  70463. * Gets or sets the smoothing
  70464. * @ignorenaming
  70465. */
  70466. this.SMOOTHING = 0.75;
  70467. /**
  70468. * Gets or sets the FFT table size
  70469. * @ignorenaming
  70470. */
  70471. this.FFT_SIZE = 512;
  70472. /**
  70473. * Gets or sets the bar graph amplitude
  70474. * @ignorenaming
  70475. */
  70476. this.BARGRAPHAMPLITUDE = 256;
  70477. /**
  70478. * Gets or sets the position of the debug canvas
  70479. * @ignorenaming
  70480. */
  70481. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70482. /**
  70483. * Gets or sets the debug canvas size
  70484. * @ignorenaming
  70485. */
  70486. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70487. this._scene = scene;
  70488. this._audioEngine = BABYLON.Engine.audioEngine;
  70489. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70490. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70491. this._webAudioAnalyser.minDecibels = -140;
  70492. this._webAudioAnalyser.maxDecibels = 0;
  70493. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70494. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70495. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70496. }
  70497. }
  70498. /**
  70499. * Get the number of data values you will have to play with for the visualization
  70500. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70501. * @returns a number
  70502. */
  70503. Analyser.prototype.getFrequencyBinCount = function () {
  70504. if (this._audioEngine.canUseWebAudio) {
  70505. return this._webAudioAnalyser.frequencyBinCount;
  70506. }
  70507. else {
  70508. return 0;
  70509. }
  70510. };
  70511. /**
  70512. * Gets the current frequency data as a byte array
  70513. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70514. * @returns a Uint8Array
  70515. */
  70516. Analyser.prototype.getByteFrequencyData = function () {
  70517. if (this._audioEngine.canUseWebAudio) {
  70518. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70519. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70520. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70521. }
  70522. return this._byteFreqs;
  70523. };
  70524. /**
  70525. * Gets the current waveform as a byte array
  70526. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70527. * @returns a Uint8Array
  70528. */
  70529. Analyser.prototype.getByteTimeDomainData = function () {
  70530. if (this._audioEngine.canUseWebAudio) {
  70531. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70532. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70533. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70534. }
  70535. return this._byteTime;
  70536. };
  70537. /**
  70538. * Gets the current frequency data as a float array
  70539. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70540. * @returns a Float32Array
  70541. */
  70542. Analyser.prototype.getFloatFrequencyData = function () {
  70543. if (this._audioEngine.canUseWebAudio) {
  70544. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70545. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70546. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70547. }
  70548. return this._floatFreqs;
  70549. };
  70550. /**
  70551. * Renders the debug canvas
  70552. */
  70553. Analyser.prototype.drawDebugCanvas = function () {
  70554. var _this = this;
  70555. if (this._audioEngine.canUseWebAudio) {
  70556. if (!this._debugCanvas) {
  70557. this._debugCanvas = document.createElement("canvas");
  70558. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70559. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70560. this._debugCanvas.style.position = "absolute";
  70561. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70562. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70563. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70564. document.body.appendChild(this._debugCanvas);
  70565. this._registerFunc = function () {
  70566. _this.drawDebugCanvas();
  70567. };
  70568. this._scene.registerBeforeRender(this._registerFunc);
  70569. }
  70570. if (this._registerFunc && this._debugCanvasContext) {
  70571. var workingArray = this.getByteFrequencyData();
  70572. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70573. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70574. // Draw the frequency domain chart.
  70575. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70576. var value = workingArray[i];
  70577. var percent = value / this.BARGRAPHAMPLITUDE;
  70578. var height = this.DEBUGCANVASSIZE.height * percent;
  70579. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70580. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70581. var hue = i / this.getFrequencyBinCount() * 360;
  70582. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70583. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70584. }
  70585. }
  70586. }
  70587. };
  70588. /**
  70589. * Stops rendering the debug canvas and removes it
  70590. */
  70591. Analyser.prototype.stopDebugCanvas = function () {
  70592. if (this._debugCanvas) {
  70593. if (this._registerFunc) {
  70594. this._scene.unregisterBeforeRender(this._registerFunc);
  70595. this._registerFunc = null;
  70596. }
  70597. document.body.removeChild(this._debugCanvas);
  70598. this._debugCanvas = null;
  70599. this._debugCanvasContext = null;
  70600. }
  70601. };
  70602. /**
  70603. * Connects two audio nodes
  70604. * @param inputAudioNode defines first node to connect
  70605. * @param outputAudioNode defines second node to connect
  70606. */
  70607. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70608. if (this._audioEngine.canUseWebAudio) {
  70609. inputAudioNode.connect(this._webAudioAnalyser);
  70610. this._webAudioAnalyser.connect(outputAudioNode);
  70611. }
  70612. };
  70613. /**
  70614. * Releases all associated resources
  70615. */
  70616. Analyser.prototype.dispose = function () {
  70617. if (this._audioEngine.canUseWebAudio) {
  70618. this._webAudioAnalyser.disconnect();
  70619. }
  70620. };
  70621. return Analyser;
  70622. }());
  70623. BABYLON.Analyser = Analyser;
  70624. })(BABYLON || (BABYLON = {}));
  70625. //# sourceMappingURL=babylon.analyser.js.map
  70626. var BABYLON;
  70627. (function (BABYLON) {
  70628. /**
  70629. * Wraps one or more Sound objects and selects one with random weight for playback.
  70630. */
  70631. var WeightedSound = /** @class */ (function () {
  70632. /**
  70633. * Creates a new WeightedSound from the list of sounds given.
  70634. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70635. * @param sounds Array of Sounds that will be selected from.
  70636. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70637. */
  70638. function WeightedSound(loop, sounds, weights) {
  70639. var _this = this;
  70640. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70641. this.loop = false;
  70642. this._coneInnerAngle = 360;
  70643. this._coneOuterAngle = 360;
  70644. this._volume = 1;
  70645. /** A Sound is currently playing. */
  70646. this.isPlaying = false;
  70647. /** A Sound is currently paused. */
  70648. this.isPaused = false;
  70649. this._sounds = [];
  70650. this._weights = [];
  70651. if (sounds.length !== weights.length) {
  70652. throw new Error('Sounds length does not equal weights length');
  70653. }
  70654. this.loop = loop;
  70655. this._weights = weights;
  70656. // Normalize the weights
  70657. var weightSum = 0;
  70658. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70659. var weight = weights_1[_i];
  70660. weightSum += weight;
  70661. }
  70662. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70663. for (var i = 0; i < this._weights.length; i++) {
  70664. this._weights[i] *= invWeightSum;
  70665. }
  70666. this._sounds = sounds;
  70667. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70668. var sound = _b[_a];
  70669. sound.onEndedObservable.add(function () { _this._onended(); });
  70670. }
  70671. }
  70672. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70673. /**
  70674. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70675. */
  70676. get: function () {
  70677. return this._coneInnerAngle;
  70678. },
  70679. /**
  70680. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70681. */
  70682. set: function (value) {
  70683. if (value !== this._coneInnerAngle) {
  70684. if (this._coneOuterAngle < value) {
  70685. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70686. return;
  70687. }
  70688. this._coneInnerAngle = value;
  70689. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70690. var sound = _a[_i];
  70691. sound.directionalConeInnerAngle = value;
  70692. }
  70693. }
  70694. },
  70695. enumerable: true,
  70696. configurable: true
  70697. });
  70698. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70699. /**
  70700. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70701. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70702. */
  70703. get: function () {
  70704. return this._coneOuterAngle;
  70705. },
  70706. /**
  70707. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70708. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70709. */
  70710. set: function (value) {
  70711. if (value !== this._coneOuterAngle) {
  70712. if (value < this._coneInnerAngle) {
  70713. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70714. return;
  70715. }
  70716. this._coneOuterAngle = value;
  70717. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70718. var sound = _a[_i];
  70719. sound.directionalConeOuterAngle = value;
  70720. }
  70721. }
  70722. },
  70723. enumerable: true,
  70724. configurable: true
  70725. });
  70726. Object.defineProperty(WeightedSound.prototype, "volume", {
  70727. /**
  70728. * Playback volume.
  70729. */
  70730. get: function () {
  70731. return this._volume;
  70732. },
  70733. /**
  70734. * Playback volume.
  70735. */
  70736. set: function (value) {
  70737. if (value !== this._volume) {
  70738. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70739. var sound = _a[_i];
  70740. sound.setVolume(value);
  70741. }
  70742. }
  70743. },
  70744. enumerable: true,
  70745. configurable: true
  70746. });
  70747. WeightedSound.prototype._onended = function () {
  70748. if (this._currentIndex !== undefined) {
  70749. this._sounds[this._currentIndex].autoplay = false;
  70750. }
  70751. if (this.loop && this.isPlaying) {
  70752. this.play();
  70753. }
  70754. else {
  70755. this.isPlaying = false;
  70756. }
  70757. };
  70758. /**
  70759. * Suspend playback
  70760. */
  70761. WeightedSound.prototype.pause = function () {
  70762. this.isPaused = true;
  70763. if (this._currentIndex !== undefined) {
  70764. this._sounds[this._currentIndex].pause();
  70765. }
  70766. };
  70767. /**
  70768. * Stop playback
  70769. */
  70770. WeightedSound.prototype.stop = function () {
  70771. this.isPlaying = false;
  70772. if (this._currentIndex !== undefined) {
  70773. this._sounds[this._currentIndex].stop();
  70774. }
  70775. };
  70776. /**
  70777. * Start playback.
  70778. * @param startOffset Position the clip head at a specific time in seconds.
  70779. */
  70780. WeightedSound.prototype.play = function (startOffset) {
  70781. if (!this.isPaused) {
  70782. this.stop();
  70783. var randomValue = Math.random();
  70784. var total = 0;
  70785. for (var i = 0; i < this._weights.length; i++) {
  70786. total += this._weights[i];
  70787. if (randomValue <= total) {
  70788. this._currentIndex = i;
  70789. break;
  70790. }
  70791. }
  70792. }
  70793. var sound = this._sounds[this._currentIndex];
  70794. if (sound.isReady()) {
  70795. sound.play(0, this.isPaused ? undefined : startOffset);
  70796. }
  70797. else {
  70798. sound.autoplay = true;
  70799. }
  70800. this.isPlaying = true;
  70801. this.isPaused = false;
  70802. };
  70803. return WeightedSound;
  70804. }());
  70805. BABYLON.WeightedSound = WeightedSound;
  70806. })(BABYLON || (BABYLON = {}));
  70807. //# sourceMappingURL=babylon.weightedsound.js.map
  70808. var BABYLON;
  70809. (function (BABYLON) {
  70810. // Adds the parser to the scene parsers.
  70811. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70812. // TODO: add sound
  70813. var loadedSounds = [];
  70814. var loadedSound;
  70815. container.sounds = container.sounds || [];
  70816. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70817. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70818. var parsedSound = parsedData.sounds[index];
  70819. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70820. if (!parsedSound.url)
  70821. parsedSound.url = parsedSound.name;
  70822. if (!loadedSounds[parsedSound.url]) {
  70823. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70824. loadedSounds[parsedSound.url] = loadedSound;
  70825. container.sounds.push(loadedSound);
  70826. }
  70827. else {
  70828. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70829. }
  70830. }
  70831. else {
  70832. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70833. }
  70834. }
  70835. }
  70836. loadedSounds = [];
  70837. });
  70838. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70839. get: function () {
  70840. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70841. if (!compo) {
  70842. compo = new AudioSceneComponent(this);
  70843. this._addComponent(compo);
  70844. }
  70845. if (!this._mainSoundTrack) {
  70846. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70847. }
  70848. return this._mainSoundTrack;
  70849. },
  70850. enumerable: true,
  70851. configurable: true
  70852. });
  70853. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70854. var index;
  70855. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70856. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70857. return this.mainSoundTrack.soundCollection[index];
  70858. }
  70859. }
  70860. if (this.soundTracks) {
  70861. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70862. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70863. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70864. return this.soundTracks[sdIndex].soundCollection[index];
  70865. }
  70866. }
  70867. }
  70868. }
  70869. return null;
  70870. };
  70871. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70872. get: function () {
  70873. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70874. if (!compo) {
  70875. compo = new AudioSceneComponent(this);
  70876. this._addComponent(compo);
  70877. }
  70878. return compo.audioEnabled;
  70879. },
  70880. set: function (value) {
  70881. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70882. if (!compo) {
  70883. compo = new AudioSceneComponent(this);
  70884. this._addComponent(compo);
  70885. }
  70886. if (value) {
  70887. compo.enableAudio();
  70888. }
  70889. else {
  70890. compo.disableAudio();
  70891. }
  70892. },
  70893. enumerable: true,
  70894. configurable: true
  70895. });
  70896. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70897. get: function () {
  70898. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70899. if (!compo) {
  70900. compo = new AudioSceneComponent(this);
  70901. this._addComponent(compo);
  70902. }
  70903. return compo.headphone;
  70904. },
  70905. set: function (value) {
  70906. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70907. if (!compo) {
  70908. compo = new AudioSceneComponent(this);
  70909. this._addComponent(compo);
  70910. }
  70911. if (value) {
  70912. compo.switchAudioModeForHeadphones();
  70913. }
  70914. else {
  70915. compo.switchAudioModeForNormalSpeakers();
  70916. }
  70917. },
  70918. enumerable: true,
  70919. configurable: true
  70920. });
  70921. /**
  70922. * Defines the sound scene component responsible to manage any sounds
  70923. * in a given scene.
  70924. */
  70925. var AudioSceneComponent = /** @class */ (function () {
  70926. /**
  70927. * Creates a new instance of the component for the given scene
  70928. * @param scene Defines the scene to register the component in
  70929. */
  70930. function AudioSceneComponent(scene) {
  70931. /**
  70932. * The component name helpfull to identify the component in the list of scene components.
  70933. */
  70934. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70935. this._audioEnabled = true;
  70936. this._headphone = false;
  70937. this.scene = scene;
  70938. scene.soundTracks = new Array();
  70939. scene.sounds = new Array();
  70940. }
  70941. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70942. /**
  70943. * Gets whether audio is enabled or not.
  70944. * Please use related enable/disable method to switch state.
  70945. */
  70946. get: function () {
  70947. return this._audioEnabled;
  70948. },
  70949. enumerable: true,
  70950. configurable: true
  70951. });
  70952. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70953. /**
  70954. * Gets whether audio is outputing to headphone or not.
  70955. * Please use the according Switch methods to change output.
  70956. */
  70957. get: function () {
  70958. return this._headphone;
  70959. },
  70960. enumerable: true,
  70961. configurable: true
  70962. });
  70963. /**
  70964. * Registers the component in a given scene
  70965. */
  70966. AudioSceneComponent.prototype.register = function () {
  70967. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70968. };
  70969. /**
  70970. * Rebuilds the elements related to this component in case of
  70971. * context lost for instance.
  70972. */
  70973. AudioSceneComponent.prototype.rebuild = function () {
  70974. // Nothing to do here. (Not rendering related)
  70975. };
  70976. /**
  70977. * Serializes the component data to the specified json object
  70978. * @param serializationObject The object to serialize to
  70979. */
  70980. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  70981. serializationObject.sounds = [];
  70982. if (this.scene.soundTracks) {
  70983. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  70984. var soundtrack = this.scene.soundTracks[index];
  70985. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  70986. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  70987. }
  70988. }
  70989. }
  70990. };
  70991. /**
  70992. * Adds all the element from the container to the scene
  70993. * @param container the container holding the elements
  70994. */
  70995. AudioSceneComponent.prototype.addFromContainer = function (container) {
  70996. var _this = this;
  70997. if (!container.sounds) {
  70998. return;
  70999. }
  71000. container.sounds.forEach(function (sound) {
  71001. sound.play();
  71002. sound.autoplay = true;
  71003. _this.scene.mainSoundTrack.AddSound(sound);
  71004. });
  71005. };
  71006. /**
  71007. * Removes all the elements in the container from the scene
  71008. * @param container contains the elements to remove
  71009. */
  71010. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  71011. var _this = this;
  71012. if (!container.sounds) {
  71013. return;
  71014. }
  71015. container.sounds.forEach(function (sound) {
  71016. sound.stop();
  71017. sound.autoplay = false;
  71018. _this.scene.mainSoundTrack.RemoveSound(sound);
  71019. });
  71020. };
  71021. /**
  71022. * Disposes the component and the associated ressources.
  71023. */
  71024. AudioSceneComponent.prototype.dispose = function () {
  71025. var scene = this.scene;
  71026. if (scene._mainSoundTrack) {
  71027. scene.mainSoundTrack.dispose();
  71028. }
  71029. if (scene.soundTracks) {
  71030. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71031. scene.soundTracks[scIndex].dispose();
  71032. }
  71033. }
  71034. };
  71035. /**
  71036. * Disables audio in the associated scene.
  71037. */
  71038. AudioSceneComponent.prototype.disableAudio = function () {
  71039. var scene = this.scene;
  71040. this._audioEnabled = false;
  71041. var i;
  71042. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71043. scene.mainSoundTrack.soundCollection[i].pause();
  71044. }
  71045. if (scene.soundTracks) {
  71046. for (i = 0; i < scene.soundTracks.length; i++) {
  71047. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71048. scene.soundTracks[i].soundCollection[j].pause();
  71049. }
  71050. }
  71051. }
  71052. };
  71053. /**
  71054. * Enables audio in the associated scene.
  71055. */
  71056. AudioSceneComponent.prototype.enableAudio = function () {
  71057. var scene = this.scene;
  71058. this._audioEnabled = true;
  71059. var i;
  71060. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71061. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71062. scene.mainSoundTrack.soundCollection[i].play();
  71063. }
  71064. }
  71065. if (scene.soundTracks) {
  71066. for (i = 0; i < scene.soundTracks.length; i++) {
  71067. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71068. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71069. scene.soundTracks[i].soundCollection[j].play();
  71070. }
  71071. }
  71072. }
  71073. }
  71074. };
  71075. /**
  71076. * Switch audio to headphone output.
  71077. */
  71078. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71079. var scene = this.scene;
  71080. this._headphone = true;
  71081. scene.mainSoundTrack.switchPanningModelToHRTF();
  71082. if (scene.soundTracks) {
  71083. for (var i = 0; i < scene.soundTracks.length; i++) {
  71084. scene.soundTracks[i].switchPanningModelToHRTF();
  71085. }
  71086. }
  71087. };
  71088. /**
  71089. * Switch audio to normal speakers.
  71090. */
  71091. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71092. var scene = this.scene;
  71093. this._headphone = false;
  71094. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71095. if (scene.soundTracks) {
  71096. for (var i = 0; i < scene.soundTracks.length; i++) {
  71097. scene.soundTracks[i].switchPanningModelToEqualPower();
  71098. }
  71099. }
  71100. };
  71101. AudioSceneComponent.prototype._afterRender = function () {
  71102. var scene = this.scene;
  71103. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71104. return;
  71105. }
  71106. var listeningCamera;
  71107. var audioEngine = BABYLON.Engine.audioEngine;
  71108. if (scene.activeCameras.length > 0) {
  71109. listeningCamera = scene.activeCameras[0];
  71110. }
  71111. else {
  71112. listeningCamera = scene.activeCamera;
  71113. }
  71114. if (listeningCamera && audioEngine.audioContext) {
  71115. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71116. // for VR cameras
  71117. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71118. listeningCamera = listeningCamera.rigCameras[0];
  71119. }
  71120. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71121. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71122. cameraDirection.normalize();
  71123. // To avoid some errors on GearVR
  71124. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71125. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71126. }
  71127. var i;
  71128. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71129. var sound = scene.mainSoundTrack.soundCollection[i];
  71130. if (sound.useCustomAttenuation) {
  71131. sound.updateDistanceFromListener();
  71132. }
  71133. }
  71134. if (scene.soundTracks) {
  71135. for (i = 0; i < scene.soundTracks.length; i++) {
  71136. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71137. sound = scene.soundTracks[i].soundCollection[j];
  71138. if (sound.useCustomAttenuation) {
  71139. sound.updateDistanceFromListener();
  71140. }
  71141. }
  71142. }
  71143. }
  71144. }
  71145. };
  71146. return AudioSceneComponent;
  71147. }());
  71148. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71149. })(BABYLON || (BABYLON = {}));
  71150. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71151. var BABYLON;
  71152. (function (BABYLON) {
  71153. /**
  71154. * This defines an action helpful to play a defined sound on a triggered action.
  71155. */
  71156. var PlaySoundAction = /** @class */ (function (_super) {
  71157. __extends(PlaySoundAction, _super);
  71158. /**
  71159. * Instantiate the action
  71160. * @param triggerOptions defines the trigger options
  71161. * @param sound defines the sound to play
  71162. * @param condition defines the trigger related conditions
  71163. */
  71164. function PlaySoundAction(triggerOptions, sound, condition) {
  71165. var _this = _super.call(this, triggerOptions, condition) || this;
  71166. _this._sound = sound;
  71167. return _this;
  71168. }
  71169. /** @hidden */
  71170. PlaySoundAction.prototype._prepare = function () {
  71171. };
  71172. /**
  71173. * Execute the action and play the sound.
  71174. */
  71175. PlaySoundAction.prototype.execute = function () {
  71176. if (this._sound !== undefined)
  71177. this._sound.play();
  71178. };
  71179. /**
  71180. * Serializes the actions and its related information.
  71181. * @param parent defines the object to serialize in
  71182. * @returns the serialized object
  71183. */
  71184. PlaySoundAction.prototype.serialize = function (parent) {
  71185. return _super.prototype._serialize.call(this, {
  71186. name: "PlaySoundAction",
  71187. properties: [{ name: "sound", value: this._sound.name }]
  71188. }, parent);
  71189. };
  71190. return PlaySoundAction;
  71191. }(BABYLON.Action));
  71192. BABYLON.PlaySoundAction = PlaySoundAction;
  71193. /**
  71194. * This defines an action helpful to stop a defined sound on a triggered action.
  71195. */
  71196. var StopSoundAction = /** @class */ (function (_super) {
  71197. __extends(StopSoundAction, _super);
  71198. /**
  71199. * Instantiate the action
  71200. * @param triggerOptions defines the trigger options
  71201. * @param sound defines the sound to stop
  71202. * @param condition defines the trigger related conditions
  71203. */
  71204. function StopSoundAction(triggerOptions, sound, condition) {
  71205. var _this = _super.call(this, triggerOptions, condition) || this;
  71206. _this._sound = sound;
  71207. return _this;
  71208. }
  71209. /** @hidden */
  71210. StopSoundAction.prototype._prepare = function () {
  71211. };
  71212. /**
  71213. * Execute the action and stop the sound.
  71214. */
  71215. StopSoundAction.prototype.execute = function () {
  71216. if (this._sound !== undefined)
  71217. this._sound.stop();
  71218. };
  71219. /**
  71220. * Serializes the actions and its related information.
  71221. * @param parent defines the object to serialize in
  71222. * @returns the serialized object
  71223. */
  71224. StopSoundAction.prototype.serialize = function (parent) {
  71225. return _super.prototype._serialize.call(this, {
  71226. name: "StopSoundAction",
  71227. properties: [{ name: "sound", value: this._sound.name }]
  71228. }, parent);
  71229. };
  71230. return StopSoundAction;
  71231. }(BABYLON.Action));
  71232. BABYLON.StopSoundAction = StopSoundAction;
  71233. })(BABYLON || (BABYLON = {}));
  71234. //# sourceMappingURL=babylon.directAudioActions.js.map
  71235. var BABYLON;
  71236. (function (BABYLON) {
  71237. /**
  71238. * Class for creating a cube texture
  71239. */
  71240. var CubeTexture = /** @class */ (function (_super) {
  71241. __extends(CubeTexture, _super);
  71242. /**
  71243. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71244. * as prefiltered data.
  71245. * @param rootUrl defines the url of the texture or the root name of the six images
  71246. * @param scene defines the scene the texture is attached to
  71247. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71248. * @param noMipmap defines if mipmaps should be created or not
  71249. * @param files defines the six files to load for the different faces
  71250. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71251. * @param onError defines a callback triggered in case of error during load
  71252. * @param format defines the internal format to use for the texture once loaded
  71253. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71254. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71255. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71256. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71257. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71258. * @return the cube texture
  71259. */
  71260. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71261. if (extensions === void 0) { extensions = null; }
  71262. if (noMipmap === void 0) { noMipmap = false; }
  71263. if (files === void 0) { files = null; }
  71264. if (onLoad === void 0) { onLoad = null; }
  71265. if (onError === void 0) { onError = null; }
  71266. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71267. if (prefiltered === void 0) { prefiltered = false; }
  71268. if (forcedExtension === void 0) { forcedExtension = null; }
  71269. if (createPolynomials === void 0) { createPolynomials = false; }
  71270. if (lodScale === void 0) { lodScale = 0.8; }
  71271. if (lodOffset === void 0) { lodOffset = 0; }
  71272. var _this = _super.call(this, scene) || this;
  71273. /**
  71274. * Gets or sets the center of the bounding box associated with the cube texture.
  71275. * It must define where the camera used to render the texture was set
  71276. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71277. */
  71278. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71279. _this._rotationY = 0;
  71280. /** @hidden */
  71281. _this._prefiltered = false;
  71282. _this.name = rootUrl;
  71283. _this.url = rootUrl;
  71284. _this._noMipmap = noMipmap;
  71285. _this.hasAlpha = false;
  71286. _this._format = format;
  71287. _this.isCube = true;
  71288. _this._textureMatrix = BABYLON.Matrix.Identity();
  71289. _this._createPolynomials = createPolynomials;
  71290. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71291. if (!rootUrl && !files) {
  71292. return _this;
  71293. }
  71294. var lastDot = rootUrl.lastIndexOf(".");
  71295. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71296. var isDDS = (extension === ".dds");
  71297. var isEnv = (extension === ".env");
  71298. if (isEnv) {
  71299. _this.gammaSpace = false;
  71300. _this._prefiltered = false;
  71301. }
  71302. else {
  71303. _this._prefiltered = prefiltered;
  71304. if (prefiltered) {
  71305. _this.gammaSpace = false;
  71306. }
  71307. }
  71308. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71309. if (!files) {
  71310. if (!isEnv && !isDDS && !extensions) {
  71311. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71312. }
  71313. files = [];
  71314. if (extensions) {
  71315. for (var index = 0; index < extensions.length; index++) {
  71316. files.push(rootUrl + extensions[index]);
  71317. }
  71318. }
  71319. }
  71320. _this._files = files;
  71321. if (!_this._texture) {
  71322. if (!scene.useDelayedTextureLoading) {
  71323. if (prefiltered) {
  71324. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71325. }
  71326. else {
  71327. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71328. }
  71329. }
  71330. else {
  71331. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71332. }
  71333. }
  71334. else if (onLoad) {
  71335. if (_this._texture.isReady) {
  71336. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71337. }
  71338. else {
  71339. _this._texture.onLoadedObservable.add(onLoad);
  71340. }
  71341. }
  71342. return _this;
  71343. }
  71344. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71345. /**
  71346. * Returns the bounding box size
  71347. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71348. */
  71349. get: function () {
  71350. return this._boundingBoxSize;
  71351. },
  71352. /**
  71353. * Gets or sets the size of the bounding box associated with the cube texture
  71354. * When defined, the cubemap will switch to local mode
  71355. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71356. * @example https://www.babylonjs-playground.com/#RNASML
  71357. */
  71358. set: function (value) {
  71359. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71360. return;
  71361. }
  71362. this._boundingBoxSize = value;
  71363. var scene = this.getScene();
  71364. if (scene) {
  71365. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71366. }
  71367. },
  71368. enumerable: true,
  71369. configurable: true
  71370. });
  71371. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71372. /**
  71373. * Gets texture matrix rotation angle around Y axis radians.
  71374. */
  71375. get: function () {
  71376. return this._rotationY;
  71377. },
  71378. /**
  71379. * Sets texture matrix rotation angle around Y axis in radians.
  71380. */
  71381. set: function (value) {
  71382. this._rotationY = value;
  71383. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71384. },
  71385. enumerable: true,
  71386. configurable: true
  71387. });
  71388. /**
  71389. * Creates a cube texture from an array of image urls
  71390. * @param files defines an array of image urls
  71391. * @param scene defines the hosting scene
  71392. * @param noMipmap specifies if mip maps are not used
  71393. * @returns a cube texture
  71394. */
  71395. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71396. var rootUrlKey = "";
  71397. files.forEach(function (url) { return rootUrlKey += url; });
  71398. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71399. };
  71400. /**
  71401. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71402. * @param url defines the url of the prefiltered texture
  71403. * @param scene defines the scene the texture is attached to
  71404. * @param forcedExtension defines the extension of the file if different from the url
  71405. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71406. * @return the prefiltered texture
  71407. */
  71408. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71409. if (forcedExtension === void 0) { forcedExtension = null; }
  71410. if (createPolynomials === void 0) { createPolynomials = true; }
  71411. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71412. };
  71413. /**
  71414. * Delays loading of the cube texture
  71415. */
  71416. CubeTexture.prototype.delayLoad = function () {
  71417. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71418. return;
  71419. }
  71420. var scene = this.getScene();
  71421. if (!scene) {
  71422. return;
  71423. }
  71424. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71425. this._texture = this._getFromCache(this.url, this._noMipmap);
  71426. if (!this._texture) {
  71427. if (this._prefiltered) {
  71428. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71429. }
  71430. else {
  71431. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71432. }
  71433. }
  71434. };
  71435. /**
  71436. * Returns the reflection texture matrix
  71437. * @returns the reflection texture matrix
  71438. */
  71439. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71440. return this._textureMatrix;
  71441. };
  71442. /**
  71443. * Sets the reflection texture matrix
  71444. * @param value Reflection texture matrix
  71445. */
  71446. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71447. this._textureMatrix = value;
  71448. };
  71449. /**
  71450. * Parses text to create a cube texture
  71451. * @param parsedTexture define the serialized text to read from
  71452. * @param scene defines the hosting scene
  71453. * @param rootUrl defines the root url of the cube texture
  71454. * @returns a cube texture
  71455. */
  71456. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71457. var texture = BABYLON.SerializationHelper.Parse(function () {
  71458. var prefiltered = false;
  71459. if (parsedTexture.prefiltered) {
  71460. prefiltered = parsedTexture.prefiltered;
  71461. }
  71462. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71463. }, parsedTexture, scene);
  71464. // Local Cubemaps
  71465. if (parsedTexture.boundingBoxPosition) {
  71466. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71467. }
  71468. if (parsedTexture.boundingBoxSize) {
  71469. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71470. }
  71471. // Animations
  71472. if (parsedTexture.animations) {
  71473. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71474. var parsedAnimation = parsedTexture.animations[animationIndex];
  71475. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71476. }
  71477. }
  71478. return texture;
  71479. };
  71480. /**
  71481. * Makes a clone, or deep copy, of the cube texture
  71482. * @returns a new cube texture
  71483. */
  71484. CubeTexture.prototype.clone = function () {
  71485. var _this = this;
  71486. return BABYLON.SerializationHelper.Clone(function () {
  71487. var scene = _this.getScene();
  71488. if (!scene) {
  71489. return _this;
  71490. }
  71491. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71492. }, this);
  71493. };
  71494. __decorate([
  71495. BABYLON.serialize("rotationY")
  71496. ], CubeTexture.prototype, "rotationY", null);
  71497. return CubeTexture;
  71498. }(BABYLON.BaseTexture));
  71499. BABYLON.CubeTexture = CubeTexture;
  71500. })(BABYLON || (BABYLON = {}));
  71501. //# sourceMappingURL=babylon.cubeTexture.js.map
  71502. var BABYLON;
  71503. (function (BABYLON) {
  71504. /**
  71505. * Raw cube texture where the raw buffers are passed in
  71506. */
  71507. var RawCubeTexture = /** @class */ (function (_super) {
  71508. __extends(RawCubeTexture, _super);
  71509. /**
  71510. * Creates a cube texture where the raw buffers are passed in.
  71511. * @param scene defines the scene the texture is attached to
  71512. * @param data defines the array of data to use to create each face
  71513. * @param size defines the size of the textures
  71514. * @param format defines the format of the data
  71515. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71516. * @param generateMipMaps defines if the engine should generate the mip levels
  71517. * @param invertY defines if data must be stored with Y axis inverted
  71518. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71519. * @param compression defines the compression used (null by default)
  71520. */
  71521. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71522. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71523. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71524. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71525. if (invertY === void 0) { invertY = false; }
  71526. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71527. if (compression === void 0) { compression = null; }
  71528. var _this = _super.call(this, "", scene) || this;
  71529. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71530. return _this;
  71531. }
  71532. /**
  71533. * Updates the raw cube texture.
  71534. * @param data defines the data to store
  71535. * @param format defines the data format
  71536. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71537. * @param invertY defines if data must be stored with Y axis inverted
  71538. * @param compression defines the compression used (null by default)
  71539. * @param level defines which level of the texture to update
  71540. */
  71541. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71542. if (compression === void 0) { compression = null; }
  71543. if (level === void 0) { level = 0; }
  71544. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71545. };
  71546. /**
  71547. * Updates a raw cube texture with RGBD encoded data.
  71548. * @param data defines the array of data [mipmap][face] to use to create each face
  71549. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71550. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71551. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71552. * @returns a promsie that resolves when the operation is complete
  71553. */
  71554. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71555. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71556. if (lodScale === void 0) { lodScale = 0.8; }
  71557. if (lodOffset === void 0) { lodOffset = 0; }
  71558. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71559. };
  71560. /**
  71561. * Clones the raw cube texture.
  71562. * @return a new cube texture
  71563. */
  71564. RawCubeTexture.prototype.clone = function () {
  71565. var _this = this;
  71566. return BABYLON.SerializationHelper.Clone(function () {
  71567. var scene = _this.getScene();
  71568. var internalTexture = _this._texture;
  71569. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71570. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71571. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71572. }
  71573. return texture;
  71574. }, this);
  71575. };
  71576. /** @hidden */
  71577. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71578. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71579. internalTexture._bufferViewArrayArray = data;
  71580. internalTexture._lodGenerationScale = lodScale;
  71581. internalTexture._lodGenerationOffset = lodOffset;
  71582. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71583. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71584. internalTexture.isReady = true;
  71585. });
  71586. };
  71587. return RawCubeTexture;
  71588. }(BABYLON.CubeTexture));
  71589. BABYLON.RawCubeTexture = RawCubeTexture;
  71590. })(BABYLON || (BABYLON = {}));
  71591. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71592. var BABYLON;
  71593. (function (BABYLON) {
  71594. /**
  71595. * This Helps creating a texture that will be created from a camera in your scene.
  71596. * It is basically a dynamic texture that could be used to create special effects for instance.
  71597. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71598. */
  71599. var RenderTargetTexture = /** @class */ (function (_super) {
  71600. __extends(RenderTargetTexture, _super);
  71601. /**
  71602. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71603. * or used a shadow, depth texture...
  71604. * @param name The friendly name of the texture
  71605. * @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)
  71606. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71607. * @param generateMipMaps True if mip maps need to be generated after render.
  71608. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71609. * @param type The type of the buffer in the RTT (int, half float, float...)
  71610. * @param isCube True if a cube texture needs to be created
  71611. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71612. * @param generateDepthBuffer True to generate a depth buffer
  71613. * @param generateStencilBuffer True to generate a stencil buffer
  71614. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71615. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71616. */
  71617. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71618. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71619. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71620. if (isCube === void 0) { isCube = false; }
  71621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71622. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71623. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71624. if (isMulti === void 0) { isMulti = false; }
  71625. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71626. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71627. _this.isCube = isCube;
  71628. /**
  71629. * Define if particles should be rendered in your texture.
  71630. */
  71631. _this.renderParticles = true;
  71632. /**
  71633. * Define if sprites should be rendered in your texture.
  71634. */
  71635. _this.renderSprites = false;
  71636. /**
  71637. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71638. */
  71639. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71640. /**
  71641. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71642. */
  71643. _this.ignoreCameraViewport = false;
  71644. /**
  71645. * An event triggered when the texture is unbind.
  71646. */
  71647. _this.onBeforeBindObservable = new BABYLON.Observable();
  71648. /**
  71649. * An event triggered when the texture is unbind.
  71650. */
  71651. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71652. /**
  71653. * An event triggered before rendering the texture
  71654. */
  71655. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71656. /**
  71657. * An event triggered after rendering the texture
  71658. */
  71659. _this.onAfterRenderObservable = new BABYLON.Observable();
  71660. /**
  71661. * An event triggered after the texture clear
  71662. */
  71663. _this.onClearObservable = new BABYLON.Observable();
  71664. _this._currentRefreshId = -1;
  71665. _this._refreshRate = 1;
  71666. _this._samples = 1;
  71667. /**
  71668. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71669. * It must define where the camera used to render the texture is set
  71670. */
  71671. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71672. scene = _this.getScene();
  71673. if (!scene) {
  71674. return _this;
  71675. }
  71676. _this.renderList = new Array();
  71677. _this._engine = scene.getEngine();
  71678. _this.name = name;
  71679. _this.isRenderTarget = true;
  71680. _this._initialSizeParameter = size;
  71681. _this._processSizeParameter(size);
  71682. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71683. });
  71684. _this._generateMipMaps = generateMipMaps ? true : false;
  71685. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71686. // Rendering groups
  71687. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71688. _this._renderingManager._useSceneAutoClearSetup = true;
  71689. if (isMulti) {
  71690. return _this;
  71691. }
  71692. _this._renderTargetOptions = {
  71693. generateMipMaps: generateMipMaps,
  71694. type: type,
  71695. format: format,
  71696. samplingMode: samplingMode,
  71697. generateDepthBuffer: generateDepthBuffer,
  71698. generateStencilBuffer: generateStencilBuffer
  71699. };
  71700. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71701. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71702. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71703. }
  71704. if (isCube) {
  71705. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71706. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71707. _this._textureMatrix = BABYLON.Matrix.Identity();
  71708. }
  71709. else {
  71710. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71711. }
  71712. return _this;
  71713. }
  71714. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71715. /**
  71716. * Use this list to define the list of mesh you want to render.
  71717. */
  71718. get: function () {
  71719. return this._renderList;
  71720. },
  71721. set: function (value) {
  71722. this._renderList = value;
  71723. if (this._renderList) {
  71724. this._hookArray(this._renderList);
  71725. }
  71726. },
  71727. enumerable: true,
  71728. configurable: true
  71729. });
  71730. RenderTargetTexture.prototype._hookArray = function (array) {
  71731. var _this = this;
  71732. var oldPush = array.push;
  71733. array.push = function () {
  71734. var items = [];
  71735. for (var _i = 0; _i < arguments.length; _i++) {
  71736. items[_i] = arguments[_i];
  71737. }
  71738. var wasEmpty = array.length === 0;
  71739. var result = oldPush.apply(array, items);
  71740. if (wasEmpty) {
  71741. _this.getScene().meshes.forEach(function (mesh) {
  71742. mesh._markSubMeshesAsLightDirty();
  71743. });
  71744. }
  71745. return result;
  71746. };
  71747. var oldSplice = array.splice;
  71748. array.splice = function (index, deleteCount) {
  71749. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71750. if (array.length === 0) {
  71751. _this.getScene().meshes.forEach(function (mesh) {
  71752. mesh._markSubMeshesAsLightDirty();
  71753. });
  71754. }
  71755. return deleted;
  71756. };
  71757. };
  71758. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71759. /**
  71760. * Set a after unbind callback in the texture.
  71761. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  71762. */
  71763. set: function (callback) {
  71764. if (this._onAfterUnbindObserver) {
  71765. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71766. }
  71767. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71768. },
  71769. enumerable: true,
  71770. configurable: true
  71771. });
  71772. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71773. /**
  71774. * Set a before render callback in the texture.
  71775. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  71776. */
  71777. set: function (callback) {
  71778. if (this._onBeforeRenderObserver) {
  71779. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71780. }
  71781. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71782. },
  71783. enumerable: true,
  71784. configurable: true
  71785. });
  71786. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71787. /**
  71788. * Set a after render callback in the texture.
  71789. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  71790. */
  71791. set: function (callback) {
  71792. if (this._onAfterRenderObserver) {
  71793. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71794. }
  71795. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71796. },
  71797. enumerable: true,
  71798. configurable: true
  71799. });
  71800. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71801. /**
  71802. * Set a clear callback in the texture.
  71803. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  71804. */
  71805. set: function (callback) {
  71806. if (this._onClearObserver) {
  71807. this.onClearObservable.remove(this._onClearObserver);
  71808. }
  71809. this._onClearObserver = this.onClearObservable.add(callback);
  71810. },
  71811. enumerable: true,
  71812. configurable: true
  71813. });
  71814. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71815. /**
  71816. * Gets render target creation options that were used.
  71817. */
  71818. get: function () {
  71819. return this._renderTargetOptions;
  71820. },
  71821. enumerable: true,
  71822. configurable: true
  71823. });
  71824. RenderTargetTexture.prototype._onRatioRescale = function () {
  71825. if (this._sizeRatio) {
  71826. this.resize(this._initialSizeParameter);
  71827. }
  71828. };
  71829. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71830. get: function () {
  71831. return this._boundingBoxSize;
  71832. },
  71833. /**
  71834. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71835. * When defined, the cubemap will switch to local mode
  71836. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71837. * @example https://www.babylonjs-playground.com/#RNASML
  71838. */
  71839. set: function (value) {
  71840. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71841. return;
  71842. }
  71843. this._boundingBoxSize = value;
  71844. var scene = this.getScene();
  71845. if (scene) {
  71846. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71847. }
  71848. },
  71849. enumerable: true,
  71850. configurable: true
  71851. });
  71852. /**
  71853. * Creates a depth stencil texture.
  71854. * This is only available in WebGL 2 or with the depth texture extension available.
  71855. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71856. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71857. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71858. */
  71859. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71860. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71861. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71862. if (generateStencil === void 0) { generateStencil = false; }
  71863. if (!this.getScene()) {
  71864. return;
  71865. }
  71866. var engine = this.getScene().getEngine();
  71867. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71868. bilinearFiltering: bilinearFiltering,
  71869. comparisonFunction: comparisonFunction,
  71870. generateStencil: generateStencil,
  71871. isCube: this.isCube
  71872. });
  71873. engine.setFrameBufferDepthStencilTexture(this);
  71874. };
  71875. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71876. if (size.ratio) {
  71877. this._sizeRatio = size.ratio;
  71878. this._size = {
  71879. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71880. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71881. };
  71882. }
  71883. else {
  71884. this._size = size;
  71885. }
  71886. };
  71887. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71888. /**
  71889. * Define the number of samples to use in case of MSAA.
  71890. * It defaults to one meaning no MSAA has been enabled.
  71891. */
  71892. get: function () {
  71893. return this._samples;
  71894. },
  71895. set: function (value) {
  71896. if (this._samples === value) {
  71897. return;
  71898. }
  71899. var scene = this.getScene();
  71900. if (!scene) {
  71901. return;
  71902. }
  71903. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71904. },
  71905. enumerable: true,
  71906. configurable: true
  71907. });
  71908. /**
  71909. * Resets the refresh counter of the texture and start bak from scratch.
  71910. * Could be usefull to regenerate the texture if it is setup to render only once.
  71911. */
  71912. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71913. this._currentRefreshId = -1;
  71914. };
  71915. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71916. /**
  71917. * Define the refresh rate of the texture or the rendering frequency.
  71918. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71919. */
  71920. get: function () {
  71921. return this._refreshRate;
  71922. },
  71923. set: function (value) {
  71924. this._refreshRate = value;
  71925. this.resetRefreshCounter();
  71926. },
  71927. enumerable: true,
  71928. configurable: true
  71929. });
  71930. /**
  71931. * Adds a post process to the render target rendering passes.
  71932. * @param postProcess define the post process to add
  71933. */
  71934. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71935. if (!this._postProcessManager) {
  71936. var scene = this.getScene();
  71937. if (!scene) {
  71938. return;
  71939. }
  71940. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71941. this._postProcesses = new Array();
  71942. }
  71943. this._postProcesses.push(postProcess);
  71944. this._postProcesses[0].autoClear = false;
  71945. };
  71946. /**
  71947. * Clear all the post processes attached to the render target
  71948. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  71949. */
  71950. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71951. if (dispose === void 0) { dispose = false; }
  71952. if (!this._postProcesses) {
  71953. return;
  71954. }
  71955. if (dispose) {
  71956. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71957. var postProcess = _a[_i];
  71958. postProcess.dispose();
  71959. }
  71960. }
  71961. this._postProcesses = [];
  71962. };
  71963. /**
  71964. * Remove one of the post process from the list of attached post processes to the texture
  71965. * @param postProcess define the post process to remove from the list
  71966. */
  71967. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71968. if (!this._postProcesses) {
  71969. return;
  71970. }
  71971. var index = this._postProcesses.indexOf(postProcess);
  71972. if (index === -1) {
  71973. return;
  71974. }
  71975. this._postProcesses.splice(index, 1);
  71976. if (this._postProcesses.length > 0) {
  71977. this._postProcesses[0].autoClear = false;
  71978. }
  71979. };
  71980. /** @hidden */
  71981. RenderTargetTexture.prototype._shouldRender = function () {
  71982. if (this._currentRefreshId === -1) { // At least render once
  71983. this._currentRefreshId = 1;
  71984. return true;
  71985. }
  71986. if (this.refreshRate === this._currentRefreshId) {
  71987. this._currentRefreshId = 1;
  71988. return true;
  71989. }
  71990. this._currentRefreshId++;
  71991. return false;
  71992. };
  71993. /**
  71994. * Gets the actual render size of the texture.
  71995. * @returns the width of the render size
  71996. */
  71997. RenderTargetTexture.prototype.getRenderSize = function () {
  71998. return this.getRenderWidth();
  71999. };
  72000. /**
  72001. * Gets the actual render width of the texture.
  72002. * @returns the width of the render size
  72003. */
  72004. RenderTargetTexture.prototype.getRenderWidth = function () {
  72005. if (this._size.width) {
  72006. return this._size.width;
  72007. }
  72008. return this._size;
  72009. };
  72010. /**
  72011. * Gets the actual render height of the texture.
  72012. * @returns the height of the render size
  72013. */
  72014. RenderTargetTexture.prototype.getRenderHeight = function () {
  72015. if (this._size.width) {
  72016. return this._size.height;
  72017. }
  72018. return this._size;
  72019. };
  72020. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72021. /**
  72022. * Get if the texture can be rescaled or not.
  72023. */
  72024. get: function () {
  72025. return true;
  72026. },
  72027. enumerable: true,
  72028. configurable: true
  72029. });
  72030. /**
  72031. * Resize the texture using a ratio.
  72032. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72033. */
  72034. RenderTargetTexture.prototype.scale = function (ratio) {
  72035. var newSize = this.getRenderSize() * ratio;
  72036. this.resize(newSize);
  72037. };
  72038. /**
  72039. * Get the texture reflection matrix used to rotate/transform the reflection.
  72040. * @returns the reflection matrix
  72041. */
  72042. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72043. if (this.isCube) {
  72044. return this._textureMatrix;
  72045. }
  72046. return _super.prototype.getReflectionTextureMatrix.call(this);
  72047. };
  72048. /**
  72049. * Resize the texture to a new desired size.
  72050. * Be carrefull as it will recreate all the data in the new texture.
  72051. * @param size Define the new size. It can be:
  72052. * - a number for squared texture,
  72053. * - an object containing { width: number, height: number }
  72054. * - or an object containing a ratio { ratio: number }
  72055. */
  72056. RenderTargetTexture.prototype.resize = function (size) {
  72057. this.releaseInternalTexture();
  72058. var scene = this.getScene();
  72059. if (!scene) {
  72060. return;
  72061. }
  72062. this._processSizeParameter(size);
  72063. if (this.isCube) {
  72064. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72065. }
  72066. else {
  72067. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72068. }
  72069. };
  72070. /**
  72071. * Renders all the objects from the render list into the texture.
  72072. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72073. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72074. */
  72075. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72076. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72077. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72078. var scene = this.getScene();
  72079. if (!scene) {
  72080. return;
  72081. }
  72082. var engine = scene.getEngine();
  72083. if (this.useCameraPostProcesses !== undefined) {
  72084. useCameraPostProcess = this.useCameraPostProcesses;
  72085. }
  72086. if (this._waitingRenderList) {
  72087. this.renderList = [];
  72088. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72089. var id = this._waitingRenderList[index];
  72090. var mesh_1 = scene.getMeshByID(id);
  72091. if (mesh_1) {
  72092. this.renderList.push(mesh_1);
  72093. }
  72094. }
  72095. delete this._waitingRenderList;
  72096. }
  72097. // Is predicate defined?
  72098. if (this.renderListPredicate) {
  72099. if (this.renderList) {
  72100. this.renderList.splice(0); // Clear previous renderList
  72101. }
  72102. else {
  72103. this.renderList = [];
  72104. }
  72105. var scene = this.getScene();
  72106. if (!scene) {
  72107. return;
  72108. }
  72109. var sceneMeshes = scene.meshes;
  72110. for (var index = 0; index < sceneMeshes.length; index++) {
  72111. var mesh = sceneMeshes[index];
  72112. if (this.renderListPredicate(mesh)) {
  72113. this.renderList.push(mesh);
  72114. }
  72115. }
  72116. }
  72117. this.onBeforeBindObservable.notifyObservers(this);
  72118. // Set custom projection.
  72119. // Needs to be before binding to prevent changing the aspect ratio.
  72120. var camera;
  72121. if (this.activeCamera) {
  72122. camera = this.activeCamera;
  72123. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72124. if (this.activeCamera !== scene.activeCamera) {
  72125. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72126. }
  72127. }
  72128. else {
  72129. camera = scene.activeCamera;
  72130. if (camera) {
  72131. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72132. }
  72133. }
  72134. // Prepare renderingManager
  72135. this._renderingManager.reset();
  72136. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72137. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72138. var sceneRenderId = scene.getRenderId();
  72139. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72140. var mesh = currentRenderList[meshIndex];
  72141. if (mesh) {
  72142. if (!mesh.isReady(this.refreshRate === 0)) {
  72143. this.resetRefreshCounter();
  72144. continue;
  72145. }
  72146. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72147. var isMasked = void 0;
  72148. if (!this.renderList && camera) {
  72149. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72150. }
  72151. else {
  72152. isMasked = false;
  72153. }
  72154. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72155. mesh._activate(sceneRenderId);
  72156. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72157. var subMesh = mesh.subMeshes[subIndex];
  72158. scene._activeIndices.addCount(subMesh.indexCount, false);
  72159. this._renderingManager.dispatch(subMesh, mesh);
  72160. }
  72161. }
  72162. }
  72163. }
  72164. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72165. var particleSystem = scene.particleSystems[particleIndex];
  72166. var emitter = particleSystem.emitter;
  72167. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72168. continue;
  72169. }
  72170. if (currentRenderList.indexOf(emitter) >= 0) {
  72171. this._renderingManager.dispatchParticles(particleSystem);
  72172. }
  72173. }
  72174. if (this.isCube) {
  72175. for (var face = 0; face < 6; face++) {
  72176. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72177. scene.incrementRenderId();
  72178. scene.resetCachedMaterial();
  72179. }
  72180. }
  72181. else {
  72182. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72183. }
  72184. this.onAfterUnbindObservable.notifyObservers(this);
  72185. if (scene.activeCamera) {
  72186. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72187. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72188. }
  72189. engine.setViewport(scene.activeCamera.viewport);
  72190. }
  72191. scene.resetCachedMaterial();
  72192. };
  72193. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72194. var minimum = 128;
  72195. var x = renderDimension * scale;
  72196. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72197. // Ensure we don't exceed the render dimension (while staying POT)
  72198. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72199. };
  72200. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72201. var _this = this;
  72202. if (!this._texture) {
  72203. return;
  72204. }
  72205. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72206. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72207. });
  72208. };
  72209. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72210. var scene = this.getScene();
  72211. if (!scene) {
  72212. return;
  72213. }
  72214. var engine = scene.getEngine();
  72215. if (!this._texture) {
  72216. return;
  72217. }
  72218. // Bind
  72219. if (this._postProcessManager) {
  72220. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72221. }
  72222. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72223. if (this._texture) {
  72224. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72225. }
  72226. }
  72227. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72228. // Clear
  72229. if (this.onClearObservable.hasObservers()) {
  72230. this.onClearObservable.notifyObservers(engine);
  72231. }
  72232. else {
  72233. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72234. }
  72235. if (!this._doNotChangeAspectRatio) {
  72236. scene.updateTransformMatrix(true);
  72237. }
  72238. // Render
  72239. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72240. if (this._postProcessManager) {
  72241. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72242. }
  72243. else if (useCameraPostProcess) {
  72244. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72245. }
  72246. if (!this._doNotChangeAspectRatio) {
  72247. scene.updateTransformMatrix(true);
  72248. }
  72249. // Dump ?
  72250. if (dumpForDebug) {
  72251. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72252. }
  72253. // Unbind
  72254. if (!this.isCube || faceIndex === 5) {
  72255. if (this.isCube) {
  72256. if (faceIndex === 5) {
  72257. engine.generateMipMapsForCubemap(this._texture);
  72258. }
  72259. }
  72260. this.unbindFrameBuffer(engine, faceIndex);
  72261. }
  72262. else {
  72263. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72264. }
  72265. };
  72266. /**
  72267. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72268. * This allowed control for front to back rendering or reversly depending of the special needs.
  72269. *
  72270. * @param renderingGroupId The rendering group id corresponding to its index
  72271. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72272. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72273. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72274. */
  72275. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72276. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72277. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72278. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72279. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72280. };
  72281. /**
  72282. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72283. *
  72284. * @param renderingGroupId The rendering group id corresponding to its index
  72285. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72286. */
  72287. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72288. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72289. this._renderingManager._useSceneAutoClearSetup = false;
  72290. };
  72291. /**
  72292. * Clones the texture.
  72293. * @returns the cloned texture
  72294. */
  72295. RenderTargetTexture.prototype.clone = function () {
  72296. var textureSize = this.getSize();
  72297. 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);
  72298. // Base texture
  72299. newTexture.hasAlpha = this.hasAlpha;
  72300. newTexture.level = this.level;
  72301. // RenderTarget Texture
  72302. newTexture.coordinatesMode = this.coordinatesMode;
  72303. if (this.renderList) {
  72304. newTexture.renderList = this.renderList.slice(0);
  72305. }
  72306. return newTexture;
  72307. };
  72308. /**
  72309. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72310. * @returns The JSON representation of the texture
  72311. */
  72312. RenderTargetTexture.prototype.serialize = function () {
  72313. if (!this.name) {
  72314. return null;
  72315. }
  72316. var serializationObject = _super.prototype.serialize.call(this);
  72317. serializationObject.renderTargetSize = this.getRenderSize();
  72318. serializationObject.renderList = [];
  72319. if (this.renderList) {
  72320. for (var index = 0; index < this.renderList.length; index++) {
  72321. serializationObject.renderList.push(this.renderList[index].id);
  72322. }
  72323. }
  72324. return serializationObject;
  72325. };
  72326. /**
  72327. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72328. */
  72329. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72330. var objBuffer = this.getInternalTexture();
  72331. var scene = this.getScene();
  72332. if (objBuffer && scene) {
  72333. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72334. }
  72335. };
  72336. /**
  72337. * Dispose the texture and release its associated resources.
  72338. */
  72339. RenderTargetTexture.prototype.dispose = function () {
  72340. if (this._postProcessManager) {
  72341. this._postProcessManager.dispose();
  72342. this._postProcessManager = null;
  72343. }
  72344. this.clearPostProcesses(true);
  72345. if (this._resizeObserver) {
  72346. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72347. this._resizeObserver = null;
  72348. }
  72349. this.renderList = null;
  72350. // Remove from custom render targets
  72351. var scene = this.getScene();
  72352. if (!scene) {
  72353. return;
  72354. }
  72355. var index = scene.customRenderTargets.indexOf(this);
  72356. if (index >= 0) {
  72357. scene.customRenderTargets.splice(index, 1);
  72358. }
  72359. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72360. var camera = _a[_i];
  72361. index = camera.customRenderTargets.indexOf(this);
  72362. if (index >= 0) {
  72363. camera.customRenderTargets.splice(index, 1);
  72364. }
  72365. }
  72366. _super.prototype.dispose.call(this);
  72367. };
  72368. /** @hidden */
  72369. RenderTargetTexture.prototype._rebuild = function () {
  72370. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72371. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72372. }
  72373. if (this._postProcessManager) {
  72374. this._postProcessManager._rebuild();
  72375. }
  72376. };
  72377. /**
  72378. * Clear the info related to rendering groups preventing retention point in material dispose.
  72379. */
  72380. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72381. if (this._renderingManager) {
  72382. this._renderingManager.freeRenderingGroups();
  72383. }
  72384. };
  72385. /**
  72386. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72387. */
  72388. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72389. /**
  72390. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72391. */
  72392. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72393. /**
  72394. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72395. * the central point of your effect and can save a lot of performances.
  72396. */
  72397. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72398. return RenderTargetTexture;
  72399. }(BABYLON.Texture));
  72400. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72401. })(BABYLON || (BABYLON = {}));
  72402. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72403. var BABYLON;
  72404. (function (BABYLON) {
  72405. ;
  72406. /**
  72407. * A multi render target, like a render target provides the ability to render to a texture.
  72408. * Unlike the render target, it can render to several draw buffers in one draw.
  72409. * This is specially interesting in deferred rendering or for any effects requiring more than
  72410. * just one color from a single pass.
  72411. */
  72412. var MultiRenderTarget = /** @class */ (function (_super) {
  72413. __extends(MultiRenderTarget, _super);
  72414. /**
  72415. * Instantiate a new multi render target texture.
  72416. * A multi render target, like a render target provides the ability to render to a texture.
  72417. * Unlike the render target, it can render to several draw buffers in one draw.
  72418. * This is specially interesting in deferred rendering or for any effects requiring more than
  72419. * just one color from a single pass.
  72420. * @param name Define the name of the texture
  72421. * @param size Define the size of the buffers to render to
  72422. * @param count Define the number of target we are rendering into
  72423. * @param scene Define the scene the texture belongs to
  72424. * @param options Define the options used to create the multi render target
  72425. */
  72426. function MultiRenderTarget(name, size, count, scene, options) {
  72427. var _this = this;
  72428. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72429. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72430. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72431. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72432. _this._engine = scene.getEngine();
  72433. if (!_this.isSupported) {
  72434. _this.dispose();
  72435. return;
  72436. }
  72437. var types = [];
  72438. var samplingModes = [];
  72439. for (var i = 0; i < count; i++) {
  72440. if (options && options.types && options.types[i] !== undefined) {
  72441. types.push(options.types[i]);
  72442. }
  72443. else {
  72444. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72445. }
  72446. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72447. samplingModes.push(options.samplingModes[i]);
  72448. }
  72449. else {
  72450. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72451. }
  72452. }
  72453. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72454. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72455. _this._size = size;
  72456. _this._multiRenderTargetOptions = {
  72457. samplingModes: samplingModes,
  72458. generateMipMaps: generateMipMaps,
  72459. generateDepthBuffer: generateDepthBuffer,
  72460. generateStencilBuffer: generateStencilBuffer,
  72461. generateDepthTexture: generateDepthTexture,
  72462. types: types,
  72463. textureCount: count
  72464. };
  72465. _this._createInternalTextures();
  72466. _this._createTextures();
  72467. return _this;
  72468. }
  72469. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72470. /**
  72471. * Get if draw buffers are currently supported by the used hardware and browser.
  72472. */
  72473. get: function () {
  72474. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72475. },
  72476. enumerable: true,
  72477. configurable: true
  72478. });
  72479. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72480. /**
  72481. * Get the list of textures generated by the multi render target.
  72482. */
  72483. get: function () {
  72484. return this._textures;
  72485. },
  72486. enumerable: true,
  72487. configurable: true
  72488. });
  72489. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72490. /**
  72491. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72492. */
  72493. get: function () {
  72494. return this._textures[this._textures.length - 1];
  72495. },
  72496. enumerable: true,
  72497. configurable: true
  72498. });
  72499. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72500. /**
  72501. * Set the wrapping mode on U of all the textures we are rendering to.
  72502. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72503. */
  72504. set: function (wrap) {
  72505. if (this._textures) {
  72506. for (var i = 0; i < this._textures.length; i++) {
  72507. this._textures[i].wrapU = wrap;
  72508. }
  72509. }
  72510. },
  72511. enumerable: true,
  72512. configurable: true
  72513. });
  72514. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72515. /**
  72516. * Set the wrapping mode on V of all the textures we are rendering to.
  72517. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72518. */
  72519. set: function (wrap) {
  72520. if (this._textures) {
  72521. for (var i = 0; i < this._textures.length; i++) {
  72522. this._textures[i].wrapV = wrap;
  72523. }
  72524. }
  72525. },
  72526. enumerable: true,
  72527. configurable: true
  72528. });
  72529. /** @hidden */
  72530. MultiRenderTarget.prototype._rebuild = function () {
  72531. this.releaseInternalTextures();
  72532. this._createInternalTextures();
  72533. for (var i = 0; i < this._internalTextures.length; i++) {
  72534. var texture = this._textures[i];
  72535. texture._texture = this._internalTextures[i];
  72536. }
  72537. // Keeps references to frame buffer and stencil/depth buffer
  72538. this._texture = this._internalTextures[0];
  72539. };
  72540. MultiRenderTarget.prototype._createInternalTextures = function () {
  72541. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72542. };
  72543. MultiRenderTarget.prototype._createTextures = function () {
  72544. this._textures = [];
  72545. for (var i = 0; i < this._internalTextures.length; i++) {
  72546. var texture = new BABYLON.Texture(null, this.getScene());
  72547. texture._texture = this._internalTextures[i];
  72548. this._textures.push(texture);
  72549. }
  72550. // Keeps references to frame buffer and stencil/depth buffer
  72551. this._texture = this._internalTextures[0];
  72552. };
  72553. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72554. /**
  72555. * Define the number of samples used if MSAA is enabled.
  72556. */
  72557. get: function () {
  72558. return this._samples;
  72559. },
  72560. set: function (value) {
  72561. if (this._samples === value) {
  72562. return;
  72563. }
  72564. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72565. },
  72566. enumerable: true,
  72567. configurable: true
  72568. });
  72569. /**
  72570. * Resize all the textures in the multi render target.
  72571. * Be carrefull as it will recreate all the data in the new texture.
  72572. * @param size Define the new size
  72573. */
  72574. MultiRenderTarget.prototype.resize = function (size) {
  72575. this.releaseInternalTextures();
  72576. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72577. this._createInternalTextures();
  72578. };
  72579. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72580. var _this = this;
  72581. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72582. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72583. });
  72584. };
  72585. /**
  72586. * Dispose the render targets and their associated resources
  72587. */
  72588. MultiRenderTarget.prototype.dispose = function () {
  72589. this.releaseInternalTextures();
  72590. _super.prototype.dispose.call(this);
  72591. };
  72592. /**
  72593. * Release all the underlying texture used as draw buffers.
  72594. */
  72595. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72596. if (!this._internalTextures) {
  72597. return;
  72598. }
  72599. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72600. if (this._internalTextures[i] !== undefined) {
  72601. this._internalTextures[i].dispose();
  72602. this._internalTextures.splice(i, 1);
  72603. }
  72604. }
  72605. };
  72606. return MultiRenderTarget;
  72607. }(BABYLON.RenderTargetTexture));
  72608. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72609. })(BABYLON || (BABYLON = {}));
  72610. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72611. var BABYLON;
  72612. (function (BABYLON) {
  72613. /**
  72614. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72615. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72616. * You can then easily use it as a reflectionTexture on a flat surface.
  72617. * In case the surface is not a plane, please consider relying on reflection probes.
  72618. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72619. */
  72620. var MirrorTexture = /** @class */ (function (_super) {
  72621. __extends(MirrorTexture, _super);
  72622. /**
  72623. * Instantiates a Mirror Texture.
  72624. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72625. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72626. * You can then easily use it as a reflectionTexture on a flat surface.
  72627. * In case the surface is not a plane, please consider relying on reflection probes.
  72628. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72629. * @param name
  72630. * @param size
  72631. * @param scene
  72632. * @param generateMipMaps
  72633. * @param type
  72634. * @param samplingMode
  72635. * @param generateDepthBuffer
  72636. */
  72637. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72638. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72640. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72641. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72642. _this.scene = scene;
  72643. /**
  72644. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72645. * 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.
  72646. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72647. */
  72648. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72649. _this._transformMatrix = BABYLON.Matrix.Zero();
  72650. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72651. _this._adaptiveBlurKernel = 0;
  72652. _this._blurKernelX = 0;
  72653. _this._blurKernelY = 0;
  72654. _this._blurRatio = 1.0;
  72655. _this.ignoreCameraViewport = true;
  72656. _this._updateGammaSpace();
  72657. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72658. _this._updateGammaSpace;
  72659. });
  72660. _this.onBeforeRenderObservable.add(function () {
  72661. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72662. _this._savedViewMatrix = scene.getViewMatrix();
  72663. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72664. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72665. scene.clipPlane = _this.mirrorPlane;
  72666. scene.getEngine().cullBackFaces = false;
  72667. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72668. });
  72669. _this.onAfterRenderObservable.add(function () {
  72670. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72671. scene.getEngine().cullBackFaces = true;
  72672. scene._mirroredCameraPosition = null;
  72673. delete scene.clipPlane;
  72674. });
  72675. return _this;
  72676. }
  72677. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72678. get: function () {
  72679. return this._blurRatio;
  72680. },
  72681. /**
  72682. * Define the blur ratio used to blur the reflection if needed.
  72683. */
  72684. set: function (value) {
  72685. if (this._blurRatio === value) {
  72686. return;
  72687. }
  72688. this._blurRatio = value;
  72689. this._preparePostProcesses();
  72690. },
  72691. enumerable: true,
  72692. configurable: true
  72693. });
  72694. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72695. /**
  72696. * Define the adaptive blur kernel used to blur the reflection if needed.
  72697. * This will autocompute the closest best match for the `blurKernel`
  72698. */
  72699. set: function (value) {
  72700. this._adaptiveBlurKernel = value;
  72701. this._autoComputeBlurKernel();
  72702. },
  72703. enumerable: true,
  72704. configurable: true
  72705. });
  72706. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  72707. /**
  72708. * Define the blur kernel used to blur the reflection if needed.
  72709. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72710. */
  72711. set: function (value) {
  72712. this.blurKernelX = value;
  72713. this.blurKernelY = value;
  72714. },
  72715. enumerable: true,
  72716. configurable: true
  72717. });
  72718. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  72719. get: function () {
  72720. return this._blurKernelX;
  72721. },
  72722. /**
  72723. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  72724. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72725. */
  72726. set: function (value) {
  72727. if (this._blurKernelX === value) {
  72728. return;
  72729. }
  72730. this._blurKernelX = value;
  72731. this._preparePostProcesses();
  72732. },
  72733. enumerable: true,
  72734. configurable: true
  72735. });
  72736. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  72737. get: function () {
  72738. return this._blurKernelY;
  72739. },
  72740. /**
  72741. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  72742. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72743. */
  72744. set: function (value) {
  72745. if (this._blurKernelY === value) {
  72746. return;
  72747. }
  72748. this._blurKernelY = value;
  72749. this._preparePostProcesses();
  72750. },
  72751. enumerable: true,
  72752. configurable: true
  72753. });
  72754. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  72755. var engine = this.getScene().getEngine();
  72756. var dw = this.getRenderWidth() / engine.getRenderWidth();
  72757. var dh = this.getRenderHeight() / engine.getRenderHeight();
  72758. this.blurKernelX = this._adaptiveBlurKernel * dw;
  72759. this.blurKernelY = this._adaptiveBlurKernel * dh;
  72760. };
  72761. MirrorTexture.prototype._onRatioRescale = function () {
  72762. if (this._sizeRatio) {
  72763. this.resize(this._initialSizeParameter);
  72764. if (!this._adaptiveBlurKernel) {
  72765. this._preparePostProcesses();
  72766. }
  72767. }
  72768. if (this._adaptiveBlurKernel) {
  72769. this._autoComputeBlurKernel();
  72770. }
  72771. };
  72772. MirrorTexture.prototype._updateGammaSpace = function () {
  72773. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  72774. };
  72775. MirrorTexture.prototype._preparePostProcesses = function () {
  72776. this.clearPostProcesses(true);
  72777. if (this._blurKernelX && this._blurKernelY) {
  72778. var engine = this.getScene().getEngine();
  72779. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72780. 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);
  72781. this._blurX.autoClear = false;
  72782. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  72783. this._blurX.inputTexture = this._texture;
  72784. }
  72785. else {
  72786. this._blurX.alwaysForcePOT = true;
  72787. }
  72788. 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);
  72789. this._blurY.autoClear = false;
  72790. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  72791. this.addPostProcess(this._blurX);
  72792. this.addPostProcess(this._blurY);
  72793. }
  72794. else {
  72795. if (this._blurY) {
  72796. this.removePostProcess(this._blurY);
  72797. this._blurY.dispose();
  72798. this._blurY = null;
  72799. }
  72800. if (this._blurX) {
  72801. this.removePostProcess(this._blurX);
  72802. this._blurX.dispose();
  72803. this._blurX = null;
  72804. }
  72805. }
  72806. };
  72807. /**
  72808. * Clone the mirror texture.
  72809. * @returns the cloned texture
  72810. */
  72811. MirrorTexture.prototype.clone = function () {
  72812. var scene = this.getScene();
  72813. if (!scene) {
  72814. return this;
  72815. }
  72816. var textureSize = this.getSize();
  72817. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  72818. // Base texture
  72819. newTexture.hasAlpha = this.hasAlpha;
  72820. newTexture.level = this.level;
  72821. // Mirror Texture
  72822. newTexture.mirrorPlane = this.mirrorPlane.clone();
  72823. if (this.renderList) {
  72824. newTexture.renderList = this.renderList.slice(0);
  72825. }
  72826. return newTexture;
  72827. };
  72828. /**
  72829. * Serialize the texture to a JSON representation you could use in Parse later on
  72830. * @returns the serialized JSON representation
  72831. */
  72832. MirrorTexture.prototype.serialize = function () {
  72833. if (!this.name) {
  72834. return null;
  72835. }
  72836. var serializationObject = _super.prototype.serialize.call(this);
  72837. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72838. return serializationObject;
  72839. };
  72840. /**
  72841. * Dispose the texture and release its associated resources.
  72842. */
  72843. MirrorTexture.prototype.dispose = function () {
  72844. _super.prototype.dispose.call(this);
  72845. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72846. };
  72847. return MirrorTexture;
  72848. }(BABYLON.RenderTargetTexture));
  72849. BABYLON.MirrorTexture = MirrorTexture;
  72850. })(BABYLON || (BABYLON = {}));
  72851. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72852. var BABYLON;
  72853. (function (BABYLON) {
  72854. /**
  72855. * Creates a refraction texture used by refraction channel of the standard material.
  72856. * It is like a mirror but to see through a material.
  72857. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72858. */
  72859. var RefractionTexture = /** @class */ (function (_super) {
  72860. __extends(RefractionTexture, _super);
  72861. /**
  72862. * Creates a refraction texture used by refraction channel of the standard material.
  72863. * It is like a mirror but to see through a material.
  72864. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72865. * @param name Define the texture name
  72866. * @param size Define the size of the underlying texture
  72867. * @param scene Define the scene the refraction belongs to
  72868. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72869. */
  72870. function RefractionTexture(name, size, scene, generateMipMaps) {
  72871. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72872. /**
  72873. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72874. * 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.
  72875. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72876. */
  72877. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72878. /**
  72879. * Define how deep under the surface we should see.
  72880. */
  72881. _this.depth = 2.0;
  72882. _this.onBeforeRenderObservable.add(function () {
  72883. scene.clipPlane = _this.refractionPlane;
  72884. });
  72885. _this.onAfterRenderObservable.add(function () {
  72886. delete scene.clipPlane;
  72887. });
  72888. return _this;
  72889. }
  72890. /**
  72891. * Clone the refraction texture.
  72892. * @returns the cloned texture
  72893. */
  72894. RefractionTexture.prototype.clone = function () {
  72895. var scene = this.getScene();
  72896. if (!scene) {
  72897. return this;
  72898. }
  72899. var textureSize = this.getSize();
  72900. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72901. // Base texture
  72902. newTexture.hasAlpha = this.hasAlpha;
  72903. newTexture.level = this.level;
  72904. // Refraction Texture
  72905. newTexture.refractionPlane = this.refractionPlane.clone();
  72906. if (this.renderList) {
  72907. newTexture.renderList = this.renderList.slice(0);
  72908. }
  72909. newTexture.depth = this.depth;
  72910. return newTexture;
  72911. };
  72912. /**
  72913. * Serialize the texture to a JSON representation you could use in Parse later on
  72914. * @returns the serialized JSON representation
  72915. */
  72916. RefractionTexture.prototype.serialize = function () {
  72917. if (!this.name) {
  72918. return null;
  72919. }
  72920. var serializationObject = _super.prototype.serialize.call(this);
  72921. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72922. serializationObject.depth = this.depth;
  72923. return serializationObject;
  72924. };
  72925. return RefractionTexture;
  72926. }(BABYLON.RenderTargetTexture));
  72927. BABYLON.RefractionTexture = RefractionTexture;
  72928. })(BABYLON || (BABYLON = {}));
  72929. //# sourceMappingURL=babylon.refractionTexture.js.map
  72930. var BABYLON;
  72931. (function (BABYLON) {
  72932. /**
  72933. * A class extending Texture allowing drawing on a texture
  72934. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72935. */
  72936. var DynamicTexture = /** @class */ (function (_super) {
  72937. __extends(DynamicTexture, _super);
  72938. /**
  72939. * Creates a DynamicTexture
  72940. * @param name defines the name of the texture
  72941. * @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
  72942. * @param scene defines the scene where you want the texture
  72943. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72944. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72945. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72946. */
  72947. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72948. if (scene === void 0) { scene = null; }
  72949. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72950. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72951. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72952. _this.name = name;
  72953. _this._engine = _this.getScene().getEngine();
  72954. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72955. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72956. _this._generateMipMaps = generateMipMaps;
  72957. if (options.getContext) {
  72958. _this._canvas = options;
  72959. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72960. }
  72961. else {
  72962. _this._canvas = document.createElement("canvas");
  72963. if (options.width || options.width === 0) {
  72964. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72965. }
  72966. else {
  72967. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72968. }
  72969. }
  72970. var textureSize = _this.getSize();
  72971. _this._canvas.width = textureSize.width;
  72972. _this._canvas.height = textureSize.height;
  72973. _this._context = _this._canvas.getContext("2d");
  72974. return _this;
  72975. }
  72976. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  72977. /**
  72978. * Gets the current state of canRescale
  72979. */
  72980. get: function () {
  72981. return true;
  72982. },
  72983. enumerable: true,
  72984. configurable: true
  72985. });
  72986. DynamicTexture.prototype._recreate = function (textureSize) {
  72987. this._canvas.width = textureSize.width;
  72988. this._canvas.height = textureSize.height;
  72989. this.releaseInternalTexture();
  72990. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  72991. };
  72992. /**
  72993. * Scales the texture
  72994. * @param ratio the scale factor to apply to both width and height
  72995. */
  72996. DynamicTexture.prototype.scale = function (ratio) {
  72997. var textureSize = this.getSize();
  72998. textureSize.width *= ratio;
  72999. textureSize.height *= ratio;
  73000. this._recreate(textureSize);
  73001. };
  73002. /**
  73003. * Resizes the texture
  73004. * @param width the new width
  73005. * @param height the new height
  73006. */
  73007. DynamicTexture.prototype.scaleTo = function (width, height) {
  73008. var textureSize = this.getSize();
  73009. textureSize.width = width;
  73010. textureSize.height = height;
  73011. this._recreate(textureSize);
  73012. };
  73013. /**
  73014. * Gets the context of the canvas used by the texture
  73015. * @returns the canvas context of the dynamic texture
  73016. */
  73017. DynamicTexture.prototype.getContext = function () {
  73018. return this._context;
  73019. };
  73020. /**
  73021. * Clears the texture
  73022. */
  73023. DynamicTexture.prototype.clear = function () {
  73024. var size = this.getSize();
  73025. this._context.fillRect(0, 0, size.width, size.height);
  73026. };
  73027. /**
  73028. * Updates the texture
  73029. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73030. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73031. */
  73032. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73033. if (premulAlpha === void 0) { premulAlpha = false; }
  73034. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73035. };
  73036. /**
  73037. * Draws text onto the texture
  73038. * @param text defines the text to be drawn
  73039. * @param x defines the placement of the text from the left
  73040. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73041. * @param font defines the font to be used with font-style, font-size, font-name
  73042. * @param color defines the color used for the text
  73043. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73044. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73045. * @param update defines whether texture is immediately update (default is true)
  73046. */
  73047. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73048. if (update === void 0) { update = true; }
  73049. var size = this.getSize();
  73050. if (clearColor) {
  73051. this._context.fillStyle = clearColor;
  73052. this._context.fillRect(0, 0, size.width, size.height);
  73053. }
  73054. this._context.font = font;
  73055. if (x === null || x === undefined) {
  73056. var textSize = this._context.measureText(text);
  73057. x = (size.width - textSize.width) / 2;
  73058. }
  73059. if (y === null || y === undefined) {
  73060. var fontSize = parseInt((font.replace(/\D/g, '')));
  73061. y = (size.height / 2) + (fontSize / 3.65);
  73062. }
  73063. this._context.fillStyle = color;
  73064. this._context.fillText(text, x, y);
  73065. if (update) {
  73066. this.update(invertY);
  73067. }
  73068. };
  73069. /**
  73070. * Clones the texture
  73071. * @returns the clone of the texture.
  73072. */
  73073. DynamicTexture.prototype.clone = function () {
  73074. var scene = this.getScene();
  73075. if (!scene) {
  73076. return this;
  73077. }
  73078. var textureSize = this.getSize();
  73079. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73080. // Base texture
  73081. newTexture.hasAlpha = this.hasAlpha;
  73082. newTexture.level = this.level;
  73083. // Dynamic Texture
  73084. newTexture.wrapU = this.wrapU;
  73085. newTexture.wrapV = this.wrapV;
  73086. return newTexture;
  73087. };
  73088. /**
  73089. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73090. * @returns a serialized dynamic texture object
  73091. */
  73092. DynamicTexture.prototype.serialize = function () {
  73093. var scene = this.getScene();
  73094. if (scene && !scene.isReady()) {
  73095. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73096. }
  73097. var serializationObject = _super.prototype.serialize.call(this);
  73098. serializationObject.base64String = this._canvas.toDataURL();
  73099. serializationObject.invertY = this._invertY;
  73100. serializationObject.samplingMode = this.samplingMode;
  73101. return serializationObject;
  73102. };
  73103. /** @hidden */
  73104. DynamicTexture.prototype._rebuild = function () {
  73105. this.update();
  73106. };
  73107. return DynamicTexture;
  73108. }(BABYLON.Texture));
  73109. BABYLON.DynamicTexture = DynamicTexture;
  73110. })(BABYLON || (BABYLON = {}));
  73111. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73112. var BABYLON;
  73113. (function (BABYLON) {
  73114. /**
  73115. * If you want to display a video in your scene, this is the special texture for that.
  73116. * This special texture works similar to other textures, with the exception of a few parameters.
  73117. * @see https://doc.babylonjs.com/how_to/video_texture
  73118. */
  73119. var VideoTexture = /** @class */ (function (_super) {
  73120. __extends(VideoTexture, _super);
  73121. /**
  73122. * Creates a video texture.
  73123. * If you want to display a video in your scene, this is the special texture for that.
  73124. * This special texture works similar to other textures, with the exception of a few parameters.
  73125. * @see https://doc.babylonjs.com/how_to/video_texture
  73126. * @param name optional name, will detect from video source, if not defined
  73127. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  73128. * @param scene is obviously the current scene.
  73129. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73130. * @param invertY is false by default but can be used to invert video on Y axis
  73131. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73132. * @param settings allows finer control over video usage
  73133. */
  73134. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73135. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73136. if (invertY === void 0) { invertY = false; }
  73137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73138. if (settings === void 0) { settings = {
  73139. autoPlay: true,
  73140. loop: true,
  73141. autoUpdateTexture: true,
  73142. }; }
  73143. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73144. _this._onUserActionRequestedObservable = null;
  73145. _this._stillImageCaptured = false;
  73146. _this._poster = false;
  73147. _this._createInternalTexture = function () {
  73148. if (_this._texture != null) {
  73149. if (_this._poster) {
  73150. _this._texture.dispose();
  73151. _this._poster = false;
  73152. }
  73153. else {
  73154. return;
  73155. }
  73156. }
  73157. if (!_this._engine.needPOTTextures ||
  73158. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73159. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73160. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73161. }
  73162. else {
  73163. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73164. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73165. _this._generateMipMaps = false;
  73166. }
  73167. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73168. if (!_this.video.autoplay) {
  73169. var oldHandler_1 = _this.video.onplaying;
  73170. var error_1 = false;
  73171. _this.video.onplaying = function () {
  73172. _this.video.onplaying = oldHandler_1;
  73173. _this._texture.isReady = true;
  73174. _this._updateInternalTexture();
  73175. if (!error_1) {
  73176. _this.video.pause();
  73177. }
  73178. if (_this.onLoadObservable.hasObservers()) {
  73179. _this.onLoadObservable.notifyObservers(_this);
  73180. }
  73181. };
  73182. var playing = _this.video.play();
  73183. if (playing) {
  73184. playing.then(function () {
  73185. // Everything is good.
  73186. })
  73187. .catch(function () {
  73188. error_1 = true;
  73189. // On Chrome for instance, new policies might prevent playing without user interaction.
  73190. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73191. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73192. }
  73193. });
  73194. }
  73195. else {
  73196. _this.video.onplaying = oldHandler_1;
  73197. _this._texture.isReady = true;
  73198. _this._updateInternalTexture();
  73199. if (_this.onLoadObservable.hasObservers()) {
  73200. _this.onLoadObservable.notifyObservers(_this);
  73201. }
  73202. }
  73203. }
  73204. else {
  73205. _this._texture.isReady = true;
  73206. _this._updateInternalTexture();
  73207. if (_this.onLoadObservable.hasObservers()) {
  73208. _this.onLoadObservable.notifyObservers(_this);
  73209. }
  73210. }
  73211. };
  73212. _this.reset = function () {
  73213. if (_this._texture == null) {
  73214. return;
  73215. }
  73216. if (!_this._poster) {
  73217. _this._texture.dispose();
  73218. _this._texture = null;
  73219. }
  73220. };
  73221. _this._updateInternalTexture = function (e) {
  73222. if (_this._texture == null || !_this._texture.isReady) {
  73223. return;
  73224. }
  73225. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73226. return;
  73227. }
  73228. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73229. };
  73230. _this._engine = _this.getScene().getEngine();
  73231. _this._generateMipMaps = generateMipMaps;
  73232. _this._samplingMode = samplingMode;
  73233. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73234. _this.name = name || _this._getName(src);
  73235. _this.video = _this._getVideo(src);
  73236. if (settings.poster) {
  73237. _this.video.poster = settings.poster;
  73238. }
  73239. if (settings.autoPlay !== undefined) {
  73240. _this.video.autoplay = settings.autoPlay;
  73241. }
  73242. if (settings.loop !== undefined) {
  73243. _this.video.loop = settings.loop;
  73244. }
  73245. _this.video.setAttribute("playsinline", "");
  73246. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73247. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73248. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73249. _this.video.addEventListener("emptied", _this.reset);
  73250. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73251. _this._createInternalTexture();
  73252. }
  73253. if (settings.poster) {
  73254. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73255. _this._poster = true;
  73256. }
  73257. return _this;
  73258. }
  73259. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73260. /**
  73261. * Event triggerd when a dom action is required by the user to play the video.
  73262. * This happens due to recent changes in browser policies preventing video to auto start.
  73263. */
  73264. get: function () {
  73265. if (!this._onUserActionRequestedObservable) {
  73266. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73267. }
  73268. return this._onUserActionRequestedObservable;
  73269. },
  73270. enumerable: true,
  73271. configurable: true
  73272. });
  73273. VideoTexture.prototype._getName = function (src) {
  73274. if (src instanceof HTMLVideoElement) {
  73275. return src.currentSrc;
  73276. }
  73277. if (typeof src === "object") {
  73278. return src.toString();
  73279. }
  73280. return src;
  73281. };
  73282. ;
  73283. VideoTexture.prototype._getVideo = function (src) {
  73284. if (src instanceof HTMLVideoElement) {
  73285. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73286. return src;
  73287. }
  73288. var video = document.createElement("video");
  73289. if (typeof src === "string") {
  73290. BABYLON.Tools.SetCorsBehavior(src, video);
  73291. video.src = src;
  73292. }
  73293. else {
  73294. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73295. src.forEach(function (url) {
  73296. var source = document.createElement("source");
  73297. source.src = url;
  73298. video.appendChild(source);
  73299. });
  73300. }
  73301. return video;
  73302. };
  73303. ;
  73304. /**
  73305. * @hidden Internal method to initiate `update`.
  73306. */
  73307. VideoTexture.prototype._rebuild = function () {
  73308. this.update();
  73309. };
  73310. /**
  73311. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73312. */
  73313. VideoTexture.prototype.update = function () {
  73314. if (!this.autoUpdateTexture) {
  73315. // Expecting user to call `updateTexture` manually
  73316. return;
  73317. }
  73318. this.updateTexture(true);
  73319. };
  73320. /**
  73321. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73322. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73323. */
  73324. VideoTexture.prototype.updateTexture = function (isVisible) {
  73325. if (!isVisible) {
  73326. return;
  73327. }
  73328. if (this.video.paused && this._stillImageCaptured) {
  73329. return;
  73330. }
  73331. this._stillImageCaptured = true;
  73332. this._updateInternalTexture();
  73333. };
  73334. /**
  73335. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73336. * @param url New url.
  73337. */
  73338. VideoTexture.prototype.updateURL = function (url) {
  73339. this.video.src = url;
  73340. };
  73341. /**
  73342. * Dispose the texture and release its associated resources.
  73343. */
  73344. VideoTexture.prototype.dispose = function () {
  73345. _super.prototype.dispose.call(this);
  73346. if (this._onUserActionRequestedObservable) {
  73347. this._onUserActionRequestedObservable.clear();
  73348. this._onUserActionRequestedObservable = null;
  73349. }
  73350. this.video.removeEventListener("canplay", this._createInternalTexture);
  73351. this.video.removeEventListener("paused", this._updateInternalTexture);
  73352. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73353. this.video.removeEventListener("emptied", this.reset);
  73354. this.video.pause();
  73355. };
  73356. /**
  73357. * Creates a video texture straight from your WebCam video feed.
  73358. * @param scene Define the scene the texture should be created in
  73359. * @param onReady Define a callback to triggered once the texture will be ready
  73360. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73361. */
  73362. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73363. var video = document.createElement("video");
  73364. video.setAttribute('autoplay', '');
  73365. video.setAttribute('muted', '');
  73366. video.setAttribute('playsinline', '');
  73367. var constraintsDeviceId;
  73368. if (constraints && constraints.deviceId) {
  73369. constraintsDeviceId = {
  73370. exact: constraints.deviceId,
  73371. };
  73372. }
  73373. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73374. if (navigator.mediaDevices) {
  73375. navigator.mediaDevices.getUserMedia({ video: constraints })
  73376. .then(function (stream) {
  73377. if (video.mozSrcObject !== undefined) {
  73378. // hack for Firefox < 19
  73379. video.mozSrcObject = stream;
  73380. }
  73381. else {
  73382. video.srcObject = stream;
  73383. }
  73384. var onPlaying = function () {
  73385. if (onReady) {
  73386. onReady(new VideoTexture("video", video, scene, true, true));
  73387. }
  73388. video.removeEventListener("playing", onPlaying);
  73389. };
  73390. video.addEventListener("playing", onPlaying);
  73391. video.play();
  73392. })
  73393. .catch(function (err) {
  73394. BABYLON.Tools.Error(err.name);
  73395. });
  73396. }
  73397. else {
  73398. navigator.getUserMedia =
  73399. navigator.getUserMedia ||
  73400. navigator.webkitGetUserMedia ||
  73401. navigator.mozGetUserMedia ||
  73402. navigator.msGetUserMedia;
  73403. if (navigator.getUserMedia) {
  73404. navigator.getUserMedia({
  73405. video: {
  73406. deviceId: constraintsDeviceId,
  73407. width: {
  73408. min: (constraints && constraints.minWidth) || 256,
  73409. max: (constraints && constraints.maxWidth) || 640,
  73410. },
  73411. height: {
  73412. min: (constraints && constraints.minHeight) || 256,
  73413. max: (constraints && constraints.maxHeight) || 480,
  73414. },
  73415. },
  73416. }, function (stream) {
  73417. if (video.mozSrcObject !== undefined) {
  73418. // hack for Firefox < 19
  73419. video.mozSrcObject = stream;
  73420. }
  73421. else {
  73422. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73423. }
  73424. video.play();
  73425. if (onReady) {
  73426. onReady(new VideoTexture("video", video, scene, true, true));
  73427. }
  73428. }, function (e) {
  73429. BABYLON.Tools.Error(e.name);
  73430. });
  73431. }
  73432. }
  73433. };
  73434. return VideoTexture;
  73435. }(BABYLON.Texture));
  73436. BABYLON.VideoTexture = VideoTexture;
  73437. })(BABYLON || (BABYLON = {}));
  73438. //# sourceMappingURL=babylon.videoTexture.js.map
  73439. var BABYLON;
  73440. (function (BABYLON) {
  73441. /**
  73442. * Raw texture can help creating a texture directly from an array of data.
  73443. * This can be super useful if you either get the data from an uncompressed source or
  73444. * if you wish to create your texture pixel by pixel.
  73445. */
  73446. var RawTexture = /** @class */ (function (_super) {
  73447. __extends(RawTexture, _super);
  73448. /**
  73449. * Instantiates a new RawTexture.
  73450. * Raw texture can help creating a texture directly from an array of data.
  73451. * This can be super useful if you either get the data from an uncompressed source or
  73452. * if you wish to create your texture pixel by pixel.
  73453. * @param data define the array of data to use to create the texture
  73454. * @param width define the width of the texture
  73455. * @param height define the height of the texture
  73456. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73457. * @param scene define the scene the texture belongs to
  73458. * @param generateMipMaps define whether mip maps should be generated or not
  73459. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73460. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73461. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73462. */
  73463. function RawTexture(data, width, height,
  73464. /**
  73465. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73466. */
  73467. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73469. if (invertY === void 0) { invertY = false; }
  73470. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73471. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73472. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73473. _this.format = format;
  73474. _this._engine = scene.getEngine();
  73475. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73476. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73477. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73478. return _this;
  73479. }
  73480. /**
  73481. * Updates the texture underlying data.
  73482. * @param data Define the new data of the texture
  73483. */
  73484. RawTexture.prototype.update = function (data) {
  73485. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73486. };
  73487. /**
  73488. * Creates a luminance texture from some data.
  73489. * @param data Define the texture data
  73490. * @param width Define the width of the texture
  73491. * @param height Define the height of the texture
  73492. * @param scene Define the scene the texture belongs to
  73493. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73494. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73495. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73496. * @returns the luminance texture
  73497. */
  73498. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73499. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73500. if (invertY === void 0) { invertY = false; }
  73501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73502. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73503. };
  73504. /**
  73505. * Creates a luminance alpha texture from some data.
  73506. * @param data Define the texture data
  73507. * @param width Define the width of the texture
  73508. * @param height Define the height of the texture
  73509. * @param scene Define the scene the texture belongs to
  73510. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73511. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73512. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73513. * @returns the luminance alpha texture
  73514. */
  73515. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73516. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73517. if (invertY === void 0) { invertY = false; }
  73518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73519. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73520. };
  73521. /**
  73522. * Creates an alpha texture from some data.
  73523. * @param data Define the texture data
  73524. * @param width Define the width of the texture
  73525. * @param height Define the height of the texture
  73526. * @param scene Define the scene the texture belongs to
  73527. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73528. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73529. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73530. * @returns the alpha texture
  73531. */
  73532. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73533. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73534. if (invertY === void 0) { invertY = false; }
  73535. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73536. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73537. };
  73538. /**
  73539. * Creates a RGB texture from some data.
  73540. * @param data Define the texture data
  73541. * @param width Define the width of the texture
  73542. * @param height Define the height of the texture
  73543. * @param scene Define the scene the texture belongs to
  73544. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73545. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73546. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73547. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73548. * @returns the RGB alpha texture
  73549. */
  73550. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73551. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73552. if (invertY === void 0) { invertY = false; }
  73553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73554. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73555. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73556. };
  73557. /**
  73558. * Creates a RGBA texture from some data.
  73559. * @param data Define the texture data
  73560. * @param width Define the width of the texture
  73561. * @param height Define the height of the texture
  73562. * @param scene Define the scene the texture belongs to
  73563. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73564. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73565. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73566. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73567. * @returns the RGBA texture
  73568. */
  73569. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73570. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73571. if (invertY === void 0) { invertY = false; }
  73572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73573. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73574. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73575. };
  73576. /**
  73577. * Creates a R texture from some data.
  73578. * @param data Define the texture data
  73579. * @param width Define the width of the texture
  73580. * @param height Define the height of the texture
  73581. * @param scene Define the scene the texture belongs to
  73582. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73583. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73584. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73585. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73586. * @returns the R texture
  73587. */
  73588. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73589. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73590. if (invertY === void 0) { invertY = false; }
  73591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73592. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73593. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73594. };
  73595. return RawTexture;
  73596. }(BABYLON.Texture));
  73597. BABYLON.RawTexture = RawTexture;
  73598. })(BABYLON || (BABYLON = {}));
  73599. //# sourceMappingURL=babylon.rawTexture.js.map
  73600. var BABYLON;
  73601. (function (BABYLON) {
  73602. /**
  73603. * Class used to store 3D textures containing user data
  73604. */
  73605. var RawTexture3D = /** @class */ (function (_super) {
  73606. __extends(RawTexture3D, _super);
  73607. /**
  73608. * Create a new RawTexture3D
  73609. * @param data defines the data of the texture
  73610. * @param width defines the width of the texture
  73611. * @param height defines the height of the texture
  73612. * @param depth defines the depth of the texture
  73613. * @param format defines the texture format to use
  73614. * @param scene defines the hosting scene
  73615. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73616. * @param invertY defines if texture must be stored with Y axis inverted
  73617. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73618. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73619. */
  73620. function RawTexture3D(data, width, height, depth,
  73621. /** Gets or sets the texture format to use */
  73622. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73623. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73624. if (invertY === void 0) { invertY = false; }
  73625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73626. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73627. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73628. _this.format = format;
  73629. _this._engine = scene.getEngine();
  73630. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73631. _this.is3D = true;
  73632. return _this;
  73633. }
  73634. /**
  73635. * Update the texture with new data
  73636. * @param data defines the data to store in the texture
  73637. */
  73638. RawTexture3D.prototype.update = function (data) {
  73639. if (!this._texture) {
  73640. return;
  73641. }
  73642. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73643. };
  73644. return RawTexture3D;
  73645. }(BABYLON.Texture));
  73646. BABYLON.RawTexture3D = RawTexture3D;
  73647. })(BABYLON || (BABYLON = {}));
  73648. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73649. var BABYLON;
  73650. (function (BABYLON) {
  73651. /**
  73652. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73653. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73654. */
  73655. var PostProcessManager = /** @class */ (function () {
  73656. /**
  73657. * Creates a new instance PostProcess
  73658. * @param scene The scene that the post process is associated with.
  73659. */
  73660. function PostProcessManager(scene) {
  73661. this._vertexBuffers = {};
  73662. this._scene = scene;
  73663. }
  73664. PostProcessManager.prototype._prepareBuffers = function () {
  73665. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73666. return;
  73667. }
  73668. // VBO
  73669. var vertices = [];
  73670. vertices.push(1, 1);
  73671. vertices.push(-1, 1);
  73672. vertices.push(-1, -1);
  73673. vertices.push(1, -1);
  73674. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73675. this._buildIndexBuffer();
  73676. };
  73677. PostProcessManager.prototype._buildIndexBuffer = function () {
  73678. // Indices
  73679. var indices = [];
  73680. indices.push(0);
  73681. indices.push(1);
  73682. indices.push(2);
  73683. indices.push(0);
  73684. indices.push(2);
  73685. indices.push(3);
  73686. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73687. };
  73688. /**
  73689. * Rebuilds the vertex buffers of the manager.
  73690. * @hidden
  73691. */
  73692. PostProcessManager.prototype._rebuild = function () {
  73693. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73694. if (!vb) {
  73695. return;
  73696. }
  73697. vb._rebuild();
  73698. this._buildIndexBuffer();
  73699. };
  73700. // Methods
  73701. /**
  73702. * Prepares a frame to be run through a post process.
  73703. * @param sourceTexture The input texture to the post procesess. (default: null)
  73704. * @param postProcesses An array of post processes to be run. (default: null)
  73705. * @returns True if the post processes were able to be run.
  73706. * @hidden
  73707. */
  73708. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  73709. if (sourceTexture === void 0) { sourceTexture = null; }
  73710. if (postProcesses === void 0) { postProcesses = null; }
  73711. var camera = this._scene.activeCamera;
  73712. if (!camera) {
  73713. return false;
  73714. }
  73715. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73716. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73717. return false;
  73718. }
  73719. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  73720. return true;
  73721. };
  73722. /**
  73723. * Manually render a set of post processes to a texture.
  73724. * @param postProcesses An array of post processes to be run.
  73725. * @param targetTexture The target texture to render to.
  73726. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  73727. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  73728. * @param lodLevel defines which lod of the texture to render to
  73729. */
  73730. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  73731. if (targetTexture === void 0) { targetTexture = null; }
  73732. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73733. if (faceIndex === void 0) { faceIndex = 0; }
  73734. if (lodLevel === void 0) { lodLevel = 0; }
  73735. var engine = this._scene.getEngine();
  73736. for (var index = 0; index < postProcesses.length; index++) {
  73737. if (index < postProcesses.length - 1) {
  73738. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  73739. }
  73740. else {
  73741. if (targetTexture) {
  73742. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  73743. }
  73744. else {
  73745. engine.restoreDefaultFramebuffer();
  73746. }
  73747. }
  73748. var pp = postProcesses[index];
  73749. var effect = pp.apply();
  73750. if (effect) {
  73751. pp.onBeforeRenderObservable.notifyObservers(effect);
  73752. // VBOs
  73753. this._prepareBuffers();
  73754. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73755. // Draw order
  73756. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73757. pp.onAfterRenderObservable.notifyObservers(effect);
  73758. }
  73759. }
  73760. // Restore depth buffer
  73761. engine.setDepthBuffer(true);
  73762. engine.setDepthWrite(true);
  73763. };
  73764. /**
  73765. * Finalize the result of the output of the postprocesses.
  73766. * @param doNotPresent If true the result will not be displayed to the screen.
  73767. * @param targetTexture The target texture to render to.
  73768. * @param faceIndex The index of the face to bind the target texture to.
  73769. * @param postProcesses The array of post processes to render.
  73770. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  73771. * @hidden
  73772. */
  73773. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  73774. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73775. var camera = this._scene.activeCamera;
  73776. if (!camera) {
  73777. return;
  73778. }
  73779. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73780. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73781. return;
  73782. }
  73783. var engine = this._scene.getEngine();
  73784. for (var index = 0, len = postProcesses.length; index < len; index++) {
  73785. var pp = postProcesses[index];
  73786. if (index < len - 1) {
  73787. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  73788. }
  73789. else {
  73790. if (targetTexture) {
  73791. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  73792. pp._outputTexture = targetTexture;
  73793. }
  73794. else {
  73795. engine.restoreDefaultFramebuffer();
  73796. pp._outputTexture = null;
  73797. }
  73798. }
  73799. if (doNotPresent) {
  73800. break;
  73801. }
  73802. var effect = pp.apply();
  73803. if (effect) {
  73804. pp.onBeforeRenderObservable.notifyObservers(effect);
  73805. // VBOs
  73806. this._prepareBuffers();
  73807. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73808. // Draw order
  73809. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73810. pp.onAfterRenderObservable.notifyObservers(effect);
  73811. }
  73812. }
  73813. // Restore states
  73814. engine.setDepthBuffer(true);
  73815. engine.setDepthWrite(true);
  73816. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73817. };
  73818. /**
  73819. * Disposes of the post process manager.
  73820. */
  73821. PostProcessManager.prototype.dispose = function () {
  73822. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73823. if (buffer) {
  73824. buffer.dispose();
  73825. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73826. }
  73827. if (this._indexBuffer) {
  73828. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73829. this._indexBuffer = null;
  73830. }
  73831. };
  73832. return PostProcessManager;
  73833. }());
  73834. BABYLON.PostProcessManager = PostProcessManager;
  73835. })(BABYLON || (BABYLON = {}));
  73836. //# sourceMappingURL=babylon.postProcessManager.js.map
  73837. var BABYLON;
  73838. (function (BABYLON) {
  73839. /**
  73840. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73841. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73842. */
  73843. var PostProcess = /** @class */ (function () {
  73844. /**
  73845. * Creates a new instance PostProcess
  73846. * @param name The name of the PostProcess.
  73847. * @param fragmentUrl The url of the fragment shader to be used.
  73848. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73849. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73850. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73851. * @param camera The camera to apply the render pass to.
  73852. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73853. * @param engine The engine which the post process will be applied. (default: current engine)
  73854. * @param reusable If the post process can be reused on the same frame. (default: false)
  73855. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73856. * @param textureType Type of textures used when performing the post process. (default: 0)
  73857. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73858. * @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
  73859. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73860. */
  73861. function PostProcess(
  73862. /** Name of the PostProcess. */
  73863. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73865. if (defines === void 0) { defines = null; }
  73866. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73867. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73868. if (blockCompilation === void 0) { blockCompilation = false; }
  73869. this.name = name;
  73870. /**
  73871. * Width of the texture to apply the post process on
  73872. */
  73873. this.width = -1;
  73874. /**
  73875. * Height of the texture to apply the post process on
  73876. */
  73877. this.height = -1;
  73878. /**
  73879. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73880. * @hidden
  73881. */
  73882. this._outputTexture = null;
  73883. /**
  73884. * If the buffer needs to be cleared before applying the post process. (default: true)
  73885. * Should be set to false if shader will overwrite all previous pixels.
  73886. */
  73887. this.autoClear = true;
  73888. /**
  73889. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73890. */
  73891. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73892. /**
  73893. * Animations to be used for the post processing
  73894. */
  73895. this.animations = new Array();
  73896. /**
  73897. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73898. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73899. */
  73900. this.enablePixelPerfectMode = false;
  73901. /**
  73902. * Force the postprocess to be applied without taking in account viewport
  73903. */
  73904. this.forceFullscreenViewport = true;
  73905. /**
  73906. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73907. *
  73908. * | Value | Type | Description |
  73909. * | ----- | ----------------------------------- | ----------- |
  73910. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73911. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73912. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73913. *
  73914. */
  73915. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73916. /**
  73917. * Force textures to be a power of two (default: false)
  73918. */
  73919. this.alwaysForcePOT = false;
  73920. this._samples = 1;
  73921. /**
  73922. * Modify the scale of the post process to be the same as the viewport (default: false)
  73923. */
  73924. this.adaptScaleToCurrentViewport = false;
  73925. this._reusable = false;
  73926. /**
  73927. * Smart array of input and output textures for the post process.
  73928. * @hidden
  73929. */
  73930. this._textures = new BABYLON.SmartArray(2);
  73931. /**
  73932. * The index in _textures that corresponds to the output texture.
  73933. * @hidden
  73934. */
  73935. this._currentRenderTextureInd = 0;
  73936. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73937. this._texelSize = BABYLON.Vector2.Zero();
  73938. // Events
  73939. /**
  73940. * An event triggered when the postprocess is activated.
  73941. */
  73942. this.onActivateObservable = new BABYLON.Observable();
  73943. /**
  73944. * An event triggered when the postprocess changes its size.
  73945. */
  73946. this.onSizeChangedObservable = new BABYLON.Observable();
  73947. /**
  73948. * An event triggered when the postprocess applies its effect.
  73949. */
  73950. this.onApplyObservable = new BABYLON.Observable();
  73951. /**
  73952. * An event triggered before rendering the postprocess
  73953. */
  73954. this.onBeforeRenderObservable = new BABYLON.Observable();
  73955. /**
  73956. * An event triggered after rendering the postprocess
  73957. */
  73958. this.onAfterRenderObservable = new BABYLON.Observable();
  73959. if (camera != null) {
  73960. this._camera = camera;
  73961. this._scene = camera.getScene();
  73962. camera.attachPostProcess(this);
  73963. this._engine = this._scene.getEngine();
  73964. this._scene.postProcesses.push(this);
  73965. }
  73966. else if (engine) {
  73967. this._engine = engine;
  73968. this._engine.postProcesses.push(this);
  73969. }
  73970. this._options = options;
  73971. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73972. this._reusable = reusable || false;
  73973. this._textureType = textureType;
  73974. this._samplers = samplers || [];
  73975. this._samplers.push("textureSampler");
  73976. this._fragmentUrl = fragmentUrl;
  73977. this._vertexUrl = vertexUrl;
  73978. this._parameters = parameters || [];
  73979. this._parameters.push("scale");
  73980. this._indexParameters = indexParameters;
  73981. if (!blockCompilation) {
  73982. this.updateEffect(defines);
  73983. }
  73984. }
  73985. Object.defineProperty(PostProcess.prototype, "samples", {
  73986. /**
  73987. * Number of sample textures (default: 1)
  73988. */
  73989. get: function () {
  73990. return this._samples;
  73991. },
  73992. set: function (n) {
  73993. var _this = this;
  73994. this._samples = n;
  73995. this._textures.forEach(function (texture) {
  73996. if (texture.samples !== _this._samples) {
  73997. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  73998. }
  73999. });
  74000. },
  74001. enumerable: true,
  74002. configurable: true
  74003. });
  74004. Object.defineProperty(PostProcess.prototype, "onActivate", {
  74005. /**
  74006. * A function that is added to the onActivateObservable
  74007. */
  74008. set: function (callback) {
  74009. if (this._onActivateObserver) {
  74010. this.onActivateObservable.remove(this._onActivateObserver);
  74011. }
  74012. if (callback) {
  74013. this._onActivateObserver = this.onActivateObservable.add(callback);
  74014. }
  74015. },
  74016. enumerable: true,
  74017. configurable: true
  74018. });
  74019. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74020. /**
  74021. * A function that is added to the onSizeChangedObservable
  74022. */
  74023. set: function (callback) {
  74024. if (this._onSizeChangedObserver) {
  74025. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74026. }
  74027. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74028. },
  74029. enumerable: true,
  74030. configurable: true
  74031. });
  74032. Object.defineProperty(PostProcess.prototype, "onApply", {
  74033. /**
  74034. * A function that is added to the onApplyObservable
  74035. */
  74036. set: function (callback) {
  74037. if (this._onApplyObserver) {
  74038. this.onApplyObservable.remove(this._onApplyObserver);
  74039. }
  74040. this._onApplyObserver = this.onApplyObservable.add(callback);
  74041. },
  74042. enumerable: true,
  74043. configurable: true
  74044. });
  74045. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74046. /**
  74047. * A function that is added to the onBeforeRenderObservable
  74048. */
  74049. set: function (callback) {
  74050. if (this._onBeforeRenderObserver) {
  74051. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74052. }
  74053. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74054. },
  74055. enumerable: true,
  74056. configurable: true
  74057. });
  74058. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74059. /**
  74060. * A function that is added to the onAfterRenderObservable
  74061. */
  74062. set: function (callback) {
  74063. if (this._onAfterRenderObserver) {
  74064. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74065. }
  74066. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74067. },
  74068. enumerable: true,
  74069. configurable: true
  74070. });
  74071. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74072. /**
  74073. * 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
  74074. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74075. */
  74076. get: function () {
  74077. return this._textures.data[this._currentRenderTextureInd];
  74078. },
  74079. set: function (value) {
  74080. this._forcedOutputTexture = value;
  74081. },
  74082. enumerable: true,
  74083. configurable: true
  74084. });
  74085. /**
  74086. * Gets the camera which post process is applied to.
  74087. * @returns The camera the post process is applied to.
  74088. */
  74089. PostProcess.prototype.getCamera = function () {
  74090. return this._camera;
  74091. };
  74092. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74093. /**
  74094. * Gets the texel size of the postprocess.
  74095. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74096. */
  74097. get: function () {
  74098. if (this._shareOutputWithPostProcess) {
  74099. return this._shareOutputWithPostProcess.texelSize;
  74100. }
  74101. if (this._forcedOutputTexture) {
  74102. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74103. }
  74104. return this._texelSize;
  74105. },
  74106. enumerable: true,
  74107. configurable: true
  74108. });
  74109. /**
  74110. * Gets the engine which this post process belongs to.
  74111. * @returns The engine the post process was enabled with.
  74112. */
  74113. PostProcess.prototype.getEngine = function () {
  74114. return this._engine;
  74115. };
  74116. /**
  74117. * The effect that is created when initializing the post process.
  74118. * @returns The created effect corrisponding the the postprocess.
  74119. */
  74120. PostProcess.prototype.getEffect = function () {
  74121. return this._effect;
  74122. };
  74123. /**
  74124. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74125. * @param postProcess The post process to share the output with.
  74126. * @returns This post process.
  74127. */
  74128. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74129. this._disposeTextures();
  74130. this._shareOutputWithPostProcess = postProcess;
  74131. return this;
  74132. };
  74133. /**
  74134. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74135. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74136. */
  74137. PostProcess.prototype.useOwnOutput = function () {
  74138. if (this._textures.length == 0) {
  74139. this._textures = new BABYLON.SmartArray(2);
  74140. }
  74141. this._shareOutputWithPostProcess = null;
  74142. };
  74143. /**
  74144. * Updates the effect with the current post process compile time values and recompiles the shader.
  74145. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74146. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74147. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74148. * @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
  74149. * @param onCompiled Called when the shader has been compiled.
  74150. * @param onError Called if there is an error when compiling a shader.
  74151. */
  74152. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74153. if (defines === void 0) { defines = null; }
  74154. if (uniforms === void 0) { uniforms = null; }
  74155. if (samplers === void 0) { samplers = null; }
  74156. 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);
  74157. };
  74158. /**
  74159. * The post process is reusable if it can be used multiple times within one frame.
  74160. * @returns If the post process is reusable
  74161. */
  74162. PostProcess.prototype.isReusable = function () {
  74163. return this._reusable;
  74164. };
  74165. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74166. PostProcess.prototype.markTextureDirty = function () {
  74167. this.width = -1;
  74168. };
  74169. /**
  74170. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74171. * 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.
  74172. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74173. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74174. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74175. * @returns The target texture that was bound to be written to.
  74176. */
  74177. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74178. var _this = this;
  74179. if (sourceTexture === void 0) { sourceTexture = null; }
  74180. camera = camera || this._camera;
  74181. var scene = camera.getScene();
  74182. var engine = scene.getEngine();
  74183. var maxSize = engine.getCaps().maxTextureSize;
  74184. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74185. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74186. // 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
  74187. var webVRCamera = camera.parent;
  74188. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74189. requiredWidth /= 2;
  74190. }
  74191. var desiredWidth = (this._options.width || requiredWidth);
  74192. var desiredHeight = this._options.height || requiredHeight;
  74193. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74194. if (this.adaptScaleToCurrentViewport) {
  74195. var currentViewport = engine.currentViewport;
  74196. if (currentViewport) {
  74197. desiredWidth *= currentViewport.width;
  74198. desiredHeight *= currentViewport.height;
  74199. }
  74200. }
  74201. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74202. if (!this._options.width) {
  74203. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74204. }
  74205. if (!this._options.height) {
  74206. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74207. }
  74208. }
  74209. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74210. if (this._textures.length > 0) {
  74211. for (var i = 0; i < this._textures.length; i++) {
  74212. this._engine._releaseTexture(this._textures.data[i]);
  74213. }
  74214. this._textures.reset();
  74215. }
  74216. this.width = desiredWidth;
  74217. this.height = desiredHeight;
  74218. var textureSize = { width: this.width, height: this.height };
  74219. var textureOptions = {
  74220. generateMipMaps: false,
  74221. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74222. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74223. samplingMode: this.renderTargetSamplingMode,
  74224. type: this._textureType
  74225. };
  74226. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74227. if (this._reusable) {
  74228. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74229. }
  74230. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74231. this.onSizeChangedObservable.notifyObservers(this);
  74232. }
  74233. this._textures.forEach(function (texture) {
  74234. if (texture.samples !== _this.samples) {
  74235. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74236. }
  74237. });
  74238. }
  74239. var target;
  74240. if (this._shareOutputWithPostProcess) {
  74241. target = this._shareOutputWithPostProcess.inputTexture;
  74242. }
  74243. else if (this._forcedOutputTexture) {
  74244. target = this._forcedOutputTexture;
  74245. this.width = this._forcedOutputTexture.width;
  74246. this.height = this._forcedOutputTexture.height;
  74247. }
  74248. else {
  74249. target = this.inputTexture;
  74250. }
  74251. // Bind the input of this post process to be used as the output of the previous post process.
  74252. if (this.enablePixelPerfectMode) {
  74253. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74254. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74255. }
  74256. else {
  74257. this._scaleRatio.copyFromFloats(1, 1);
  74258. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74259. }
  74260. this.onActivateObservable.notifyObservers(camera);
  74261. // Clear
  74262. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74263. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74264. }
  74265. if (this._reusable) {
  74266. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74267. }
  74268. return target;
  74269. };
  74270. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74271. /**
  74272. * If the post process is supported.
  74273. */
  74274. get: function () {
  74275. return this._effect.isSupported;
  74276. },
  74277. enumerable: true,
  74278. configurable: true
  74279. });
  74280. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74281. /**
  74282. * The aspect ratio of the output texture.
  74283. */
  74284. get: function () {
  74285. if (this._shareOutputWithPostProcess) {
  74286. return this._shareOutputWithPostProcess.aspectRatio;
  74287. }
  74288. if (this._forcedOutputTexture) {
  74289. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74290. }
  74291. return this.width / this.height;
  74292. },
  74293. enumerable: true,
  74294. configurable: true
  74295. });
  74296. /**
  74297. * Get a value indicating if the post-process is ready to be used
  74298. * @returns true if the post-process is ready (shader is compiled)
  74299. */
  74300. PostProcess.prototype.isReady = function () {
  74301. return this._effect && this._effect.isReady();
  74302. };
  74303. /**
  74304. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74305. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74306. */
  74307. PostProcess.prototype.apply = function () {
  74308. // Check
  74309. if (!this._effect || !this._effect.isReady())
  74310. return null;
  74311. // States
  74312. this._engine.enableEffect(this._effect);
  74313. this._engine.setState(false);
  74314. this._engine.setDepthBuffer(false);
  74315. this._engine.setDepthWrite(false);
  74316. // Alpha
  74317. this._engine.setAlphaMode(this.alphaMode);
  74318. if (this.alphaConstants) {
  74319. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74320. }
  74321. // Bind the output texture of the preivous post process as the input to this post process.
  74322. var source;
  74323. if (this._shareOutputWithPostProcess) {
  74324. source = this._shareOutputWithPostProcess.inputTexture;
  74325. }
  74326. else if (this._forcedOutputTexture) {
  74327. source = this._forcedOutputTexture;
  74328. }
  74329. else {
  74330. source = this.inputTexture;
  74331. }
  74332. this._effect._bindTexture("textureSampler", source);
  74333. // Parameters
  74334. this._effect.setVector2("scale", this._scaleRatio);
  74335. this.onApplyObservable.notifyObservers(this._effect);
  74336. return this._effect;
  74337. };
  74338. PostProcess.prototype._disposeTextures = function () {
  74339. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74340. return;
  74341. }
  74342. if (this._textures.length > 0) {
  74343. for (var i = 0; i < this._textures.length; i++) {
  74344. this._engine._releaseTexture(this._textures.data[i]);
  74345. }
  74346. }
  74347. this._textures.dispose();
  74348. };
  74349. /**
  74350. * Disposes the post process.
  74351. * @param camera The camera to dispose the post process on.
  74352. */
  74353. PostProcess.prototype.dispose = function (camera) {
  74354. camera = camera || this._camera;
  74355. this._disposeTextures();
  74356. if (this._scene) {
  74357. var index_1 = this._scene.postProcesses.indexOf(this);
  74358. if (index_1 !== -1) {
  74359. this._scene.postProcesses.splice(index_1, 1);
  74360. }
  74361. }
  74362. else {
  74363. var index_2 = this._engine.postProcesses.indexOf(this);
  74364. if (index_2 !== -1) {
  74365. this._engine.postProcesses.splice(index_2, 1);
  74366. }
  74367. }
  74368. if (!camera) {
  74369. return;
  74370. }
  74371. camera.detachPostProcess(this);
  74372. var index = camera._postProcesses.indexOf(this);
  74373. if (index === 0 && camera._postProcesses.length > 0) {
  74374. var firstPostProcess = this._camera._getFirstPostProcess();
  74375. if (firstPostProcess) {
  74376. firstPostProcess.markTextureDirty();
  74377. }
  74378. }
  74379. this.onActivateObservable.clear();
  74380. this.onAfterRenderObservable.clear();
  74381. this.onApplyObservable.clear();
  74382. this.onBeforeRenderObservable.clear();
  74383. this.onSizeChangedObservable.clear();
  74384. };
  74385. return PostProcess;
  74386. }());
  74387. BABYLON.PostProcess = PostProcess;
  74388. })(BABYLON || (BABYLON = {}));
  74389. //# sourceMappingURL=babylon.postProcess.js.map
  74390. var BABYLON;
  74391. (function (BABYLON) {
  74392. /**
  74393. * PassPostProcess which produces an output the same as it's input
  74394. */
  74395. var PassPostProcess = /** @class */ (function (_super) {
  74396. __extends(PassPostProcess, _super);
  74397. /**
  74398. * Creates the PassPostProcess
  74399. * @param name The name of the effect.
  74400. * @param options The required width/height ratio to downsize to before computing the render pass.
  74401. * @param camera The camera to apply the render pass to.
  74402. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74403. * @param engine The engine which the post process will be applied. (default: current engine)
  74404. * @param reusable If the post process can be reused on the same frame. (default: false)
  74405. * @param textureType The type of texture to be used when performing the post processing.
  74406. * @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)
  74407. */
  74408. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74409. if (camera === void 0) { camera = null; }
  74410. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74411. if (blockCompilation === void 0) { blockCompilation = false; }
  74412. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74413. }
  74414. return PassPostProcess;
  74415. }(BABYLON.PostProcess));
  74416. BABYLON.PassPostProcess = PassPostProcess;
  74417. })(BABYLON || (BABYLON = {}));
  74418. //# sourceMappingURL=babylon.passPostProcess.js.map
  74419. var __assign = (this && this.__assign) || function () {
  74420. __assign = Object.assign || function(t) {
  74421. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74422. s = arguments[i];
  74423. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74424. t[p] = s[p];
  74425. }
  74426. return t;
  74427. };
  74428. return __assign.apply(this, arguments);
  74429. };
  74430. var BABYLON;
  74431. (function (BABYLON) {
  74432. /**
  74433. * Default implementation IShadowGenerator.
  74434. * This is the main object responsible of generating shadows in the framework.
  74435. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74436. */
  74437. var ShadowGenerator = /** @class */ (function () {
  74438. /**
  74439. * Creates a ShadowGenerator object.
  74440. * A ShadowGenerator is the required tool to use the shadows.
  74441. * Each light casting shadows needs to use its own ShadowGenerator.
  74442. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74443. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74444. * @param light The light object generating the shadows.
  74445. * @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.
  74446. */
  74447. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74448. this._bias = 0.00005;
  74449. this._normalBias = 0;
  74450. this._blurBoxOffset = 1;
  74451. this._blurScale = 2;
  74452. this._blurKernel = 1;
  74453. this._useKernelBlur = false;
  74454. this._filter = ShadowGenerator.FILTER_NONE;
  74455. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74456. this._contactHardeningLightSizeUVRatio = 0.1;
  74457. this._darkness = 0;
  74458. this._transparencyShadow = false;
  74459. /**
  74460. * Controls the extent to which the shadows fade out at the edge of the frustum
  74461. * Used only by directionals and spots
  74462. */
  74463. this.frustumEdgeFalloff = 0;
  74464. /**
  74465. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74466. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74467. * It might on the other hand introduce peter panning.
  74468. */
  74469. this.forceBackFacesOnly = false;
  74470. this._lightDirection = BABYLON.Vector3.Zero();
  74471. this._viewMatrix = BABYLON.Matrix.Zero();
  74472. this._projectionMatrix = BABYLON.Matrix.Zero();
  74473. this._transformMatrix = BABYLON.Matrix.Zero();
  74474. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74475. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74476. this._currentFaceIndex = 0;
  74477. this._currentFaceIndexCache = 0;
  74478. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74479. this._mapSize = mapSize;
  74480. this._light = light;
  74481. this._scene = light.getScene();
  74482. light._shadowGenerator = this;
  74483. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74484. if (!component) {
  74485. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74486. this._scene._addComponent(component);
  74487. }
  74488. // Texture type fallback from float to int if not supported.
  74489. var caps = this._scene.getEngine().getCaps();
  74490. if (!useFullFloatFirst) {
  74491. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74492. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74493. }
  74494. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74495. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74496. }
  74497. else {
  74498. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74499. }
  74500. }
  74501. else {
  74502. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74503. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74504. }
  74505. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74506. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74507. }
  74508. else {
  74509. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74510. }
  74511. }
  74512. this._initializeGenerator();
  74513. this._applyFilterValues();
  74514. }
  74515. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74516. /**
  74517. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74518. */
  74519. get: function () {
  74520. return this._bias;
  74521. },
  74522. /**
  74523. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74524. */
  74525. set: function (bias) {
  74526. this._bias = bias;
  74527. },
  74528. enumerable: true,
  74529. configurable: true
  74530. });
  74531. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74532. /**
  74533. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74534. */
  74535. get: function () {
  74536. return this._normalBias;
  74537. },
  74538. /**
  74539. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74540. */
  74541. set: function (normalBias) {
  74542. this._normalBias = normalBias;
  74543. },
  74544. enumerable: true,
  74545. configurable: true
  74546. });
  74547. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74548. /**
  74549. * Gets the blur box offset: offset applied during the blur pass.
  74550. * Only usefull if useKernelBlur = false
  74551. */
  74552. get: function () {
  74553. return this._blurBoxOffset;
  74554. },
  74555. /**
  74556. * Sets the blur box offset: offset applied during the blur pass.
  74557. * Only usefull if useKernelBlur = false
  74558. */
  74559. set: function (value) {
  74560. if (this._blurBoxOffset === value) {
  74561. return;
  74562. }
  74563. this._blurBoxOffset = value;
  74564. this._disposeBlurPostProcesses();
  74565. },
  74566. enumerable: true,
  74567. configurable: true
  74568. });
  74569. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74570. /**
  74571. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74572. * 2 means half of the size.
  74573. */
  74574. get: function () {
  74575. return this._blurScale;
  74576. },
  74577. /**
  74578. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74579. * 2 means half of the size.
  74580. */
  74581. set: function (value) {
  74582. if (this._blurScale === value) {
  74583. return;
  74584. }
  74585. this._blurScale = value;
  74586. this._disposeBlurPostProcesses();
  74587. },
  74588. enumerable: true,
  74589. configurable: true
  74590. });
  74591. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74592. /**
  74593. * Gets the blur kernel: kernel size of the blur pass.
  74594. * Only usefull if useKernelBlur = true
  74595. */
  74596. get: function () {
  74597. return this._blurKernel;
  74598. },
  74599. /**
  74600. * Sets the blur kernel: kernel size of the blur pass.
  74601. * Only usefull if useKernelBlur = true
  74602. */
  74603. set: function (value) {
  74604. if (this._blurKernel === value) {
  74605. return;
  74606. }
  74607. this._blurKernel = value;
  74608. this._disposeBlurPostProcesses();
  74609. },
  74610. enumerable: true,
  74611. configurable: true
  74612. });
  74613. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74614. /**
  74615. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74616. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74617. */
  74618. get: function () {
  74619. return this._useKernelBlur;
  74620. },
  74621. /**
  74622. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74623. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74624. */
  74625. set: function (value) {
  74626. if (this._useKernelBlur === value) {
  74627. return;
  74628. }
  74629. this._useKernelBlur = value;
  74630. this._disposeBlurPostProcesses();
  74631. },
  74632. enumerable: true,
  74633. configurable: true
  74634. });
  74635. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74636. /**
  74637. * Gets the depth scale used in ESM mode.
  74638. */
  74639. get: function () {
  74640. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74641. },
  74642. /**
  74643. * Sets the depth scale used in ESM mode.
  74644. * This can override the scale stored on the light.
  74645. */
  74646. set: function (value) {
  74647. this._depthScale = value;
  74648. },
  74649. enumerable: true,
  74650. configurable: true
  74651. });
  74652. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74653. /**
  74654. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74655. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74656. */
  74657. get: function () {
  74658. return this._filter;
  74659. },
  74660. /**
  74661. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74662. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74663. */
  74664. set: function (value) {
  74665. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74666. if (this._light.needCube()) {
  74667. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74668. this.useExponentialShadowMap = true;
  74669. return;
  74670. }
  74671. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74672. this.useCloseExponentialShadowMap = true;
  74673. return;
  74674. }
  74675. // PCF on cubemap would also be expensive
  74676. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74677. this.usePoissonSampling = true;
  74678. return;
  74679. }
  74680. }
  74681. // Weblg1 fallback for PCF.
  74682. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74683. if (this._scene.getEngine().webGLVersion === 1) {
  74684. this.usePoissonSampling = true;
  74685. return;
  74686. }
  74687. }
  74688. if (this._filter === value) {
  74689. return;
  74690. }
  74691. this._filter = value;
  74692. this._disposeBlurPostProcesses();
  74693. this._applyFilterValues();
  74694. this._light._markMeshesAsLightDirty();
  74695. },
  74696. enumerable: true,
  74697. configurable: true
  74698. });
  74699. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74700. /**
  74701. * Gets if the current filter is set to Poisson Sampling.
  74702. */
  74703. get: function () {
  74704. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  74705. },
  74706. /**
  74707. * Sets the current filter to Poisson Sampling.
  74708. */
  74709. set: function (value) {
  74710. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  74711. return;
  74712. }
  74713. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  74714. },
  74715. enumerable: true,
  74716. configurable: true
  74717. });
  74718. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  74719. /**
  74720. * Gets if the current filter is set to VSM.
  74721. * DEPRECATED. Should use useExponentialShadowMap instead.
  74722. */
  74723. get: function () {
  74724. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74725. return this.useExponentialShadowMap;
  74726. },
  74727. /**
  74728. * Sets the current filter is to VSM.
  74729. * DEPRECATED. Should use useExponentialShadowMap instead.
  74730. */
  74731. set: function (value) {
  74732. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74733. this.useExponentialShadowMap = value;
  74734. },
  74735. enumerable: true,
  74736. configurable: true
  74737. });
  74738. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  74739. /**
  74740. * Gets if the current filter is set to blurred VSM.
  74741. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74742. */
  74743. get: function () {
  74744. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74745. return this.useBlurExponentialShadowMap;
  74746. },
  74747. /**
  74748. * Sets the current filter is to blurred VSM.
  74749. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74750. */
  74751. set: function (value) {
  74752. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74753. this.useBlurExponentialShadowMap = value;
  74754. },
  74755. enumerable: true,
  74756. configurable: true
  74757. });
  74758. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  74759. /**
  74760. * Gets if the current filter is set to ESM.
  74761. */
  74762. get: function () {
  74763. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  74764. },
  74765. /**
  74766. * Sets the current filter is to ESM.
  74767. */
  74768. set: function (value) {
  74769. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  74770. return;
  74771. }
  74772. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74773. },
  74774. enumerable: true,
  74775. configurable: true
  74776. });
  74777. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  74778. /**
  74779. * Gets if the current filter is set to filtered ESM.
  74780. */
  74781. get: function () {
  74782. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  74783. },
  74784. /**
  74785. * Gets if the current filter is set to filtered ESM.
  74786. */
  74787. set: function (value) {
  74788. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74789. return;
  74790. }
  74791. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74792. },
  74793. enumerable: true,
  74794. configurable: true
  74795. });
  74796. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  74797. /**
  74798. * Gets if the current filter is set to "close ESM" (using the inverse of the
  74799. * exponential to prevent steep falloff artifacts).
  74800. */
  74801. get: function () {
  74802. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  74803. },
  74804. /**
  74805. * Sets the current filter to "close ESM" (using the inverse of the
  74806. * exponential to prevent steep falloff artifacts).
  74807. */
  74808. set: function (value) {
  74809. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  74810. return;
  74811. }
  74812. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74813. },
  74814. enumerable: true,
  74815. configurable: true
  74816. });
  74817. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  74818. /**
  74819. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  74820. * exponential to prevent steep falloff artifacts).
  74821. */
  74822. get: function () {
  74823. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  74824. },
  74825. /**
  74826. * Sets the current filter to filtered "close ESM" (using the inverse of the
  74827. * exponential to prevent steep falloff artifacts).
  74828. */
  74829. set: function (value) {
  74830. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74831. return;
  74832. }
  74833. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74834. },
  74835. enumerable: true,
  74836. configurable: true
  74837. });
  74838. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  74839. /**
  74840. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  74841. */
  74842. get: function () {
  74843. return this.filter === ShadowGenerator.FILTER_PCF;
  74844. },
  74845. /**
  74846. * Sets the current filter to "PCF" (percentage closer filtering).
  74847. */
  74848. set: function (value) {
  74849. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74850. return;
  74851. }
  74852. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74853. },
  74854. enumerable: true,
  74855. configurable: true
  74856. });
  74857. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74858. /**
  74859. * Gets the PCF or PCSS Quality.
  74860. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74861. */
  74862. get: function () {
  74863. return this._filteringQuality;
  74864. },
  74865. /**
  74866. * Sets the PCF or PCSS Quality.
  74867. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74868. */
  74869. set: function (filteringQuality) {
  74870. this._filteringQuality = filteringQuality;
  74871. },
  74872. enumerable: true,
  74873. configurable: true
  74874. });
  74875. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74876. /**
  74877. * Gets if the current filter is set to "PCSS" (contact hardening).
  74878. */
  74879. get: function () {
  74880. return this.filter === ShadowGenerator.FILTER_PCSS;
  74881. },
  74882. /**
  74883. * Sets the current filter to "PCSS" (contact hardening).
  74884. */
  74885. set: function (value) {
  74886. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74887. return;
  74888. }
  74889. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74890. },
  74891. enumerable: true,
  74892. configurable: true
  74893. });
  74894. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74895. /**
  74896. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74897. * Using a ratio helps keeping shape stability independently of the map size.
  74898. *
  74899. * It does not account for the light projection as it was having too much
  74900. * instability during the light setup or during light position changes.
  74901. *
  74902. * Only valid if useContactHardeningShadow is true.
  74903. */
  74904. get: function () {
  74905. return this._contactHardeningLightSizeUVRatio;
  74906. },
  74907. /**
  74908. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74909. * Using a ratio helps keeping shape stability independently of the map size.
  74910. *
  74911. * It does not account for the light projection as it was having too much
  74912. * instability during the light setup or during light position changes.
  74913. *
  74914. * Only valid if useContactHardeningShadow is true.
  74915. */
  74916. set: function (contactHardeningLightSizeUVRatio) {
  74917. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74918. },
  74919. enumerable: true,
  74920. configurable: true
  74921. });
  74922. /**
  74923. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74924. * 0 means strongest and 1 would means no shadow.
  74925. * @returns the darkness.
  74926. */
  74927. ShadowGenerator.prototype.getDarkness = function () {
  74928. return this._darkness;
  74929. };
  74930. /**
  74931. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74932. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74933. * @returns the shadow generator allowing fluent coding.
  74934. */
  74935. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74936. if (darkness >= 1.0)
  74937. this._darkness = 1.0;
  74938. else if (darkness <= 0.0)
  74939. this._darkness = 0.0;
  74940. else
  74941. this._darkness = darkness;
  74942. return this;
  74943. };
  74944. /**
  74945. * Sets the ability to have transparent shadow (boolean).
  74946. * @param transparent True if transparent else False
  74947. * @returns the shadow generator allowing fluent coding
  74948. */
  74949. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74950. this._transparencyShadow = transparent;
  74951. return this;
  74952. };
  74953. /**
  74954. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74955. * @returns The render target texture if present otherwise, null
  74956. */
  74957. ShadowGenerator.prototype.getShadowMap = function () {
  74958. return this._shadowMap;
  74959. };
  74960. /**
  74961. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74962. * @returns The render target texture if the shadow map is present otherwise, null
  74963. */
  74964. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74965. if (this._shadowMap2) {
  74966. return this._shadowMap2;
  74967. }
  74968. return this._shadowMap;
  74969. };
  74970. /**
  74971. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74972. * @param mesh Mesh to add
  74973. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  74974. * @returns the Shadow Generator itself
  74975. */
  74976. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  74977. if (includeDescendants === void 0) { includeDescendants = true; }
  74978. var _a;
  74979. if (!this._shadowMap) {
  74980. return this;
  74981. }
  74982. if (!this._shadowMap.renderList) {
  74983. this._shadowMap.renderList = [];
  74984. }
  74985. this._shadowMap.renderList.push(mesh);
  74986. if (includeDescendants) {
  74987. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  74988. }
  74989. return this;
  74990. };
  74991. /**
  74992. * Helper function to remove a mesh and its descendants from the list of shadow casters
  74993. * @param mesh Mesh to remove
  74994. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  74995. * @returns the Shadow Generator itself
  74996. */
  74997. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  74998. if (includeDescendants === void 0) { includeDescendants = true; }
  74999. if (!this._shadowMap || !this._shadowMap.renderList) {
  75000. return this;
  75001. }
  75002. var index = this._shadowMap.renderList.indexOf(mesh);
  75003. if (index !== -1) {
  75004. this._shadowMap.renderList.splice(index, 1);
  75005. }
  75006. if (includeDescendants) {
  75007. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  75008. var child = _a[_i];
  75009. this.removeShadowCaster(child);
  75010. }
  75011. }
  75012. return this;
  75013. };
  75014. /**
  75015. * Returns the associated light object.
  75016. * @returns the light generating the shadow
  75017. */
  75018. ShadowGenerator.prototype.getLight = function () {
  75019. return this._light;
  75020. };
  75021. ShadowGenerator.prototype._initializeGenerator = function () {
  75022. this._light._markMeshesAsLightDirty();
  75023. this._initializeShadowMap();
  75024. };
  75025. ShadowGenerator.prototype._initializeShadowMap = function () {
  75026. var _this = this;
  75027. // Render target
  75028. var engine = this._scene.getEngine();
  75029. if (engine.webGLVersion > 1) {
  75030. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75031. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75032. }
  75033. else {
  75034. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75035. }
  75036. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75037. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75038. this._shadowMap.anisotropicFilteringLevel = 1;
  75039. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75040. this._shadowMap.renderParticles = false;
  75041. this._shadowMap.ignoreCameraViewport = true;
  75042. // Record Face Index before render.
  75043. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75044. _this._currentFaceIndex = faceIndex;
  75045. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75046. engine.setColorWrite(false);
  75047. }
  75048. });
  75049. // Custom render function.
  75050. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75051. // Blur if required afer render.
  75052. this._shadowMap.onAfterUnbindObservable.add(function () {
  75053. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75054. engine.setColorWrite(true);
  75055. }
  75056. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75057. return;
  75058. }
  75059. var shadowMap = _this.getShadowMapForRendering();
  75060. if (shadowMap) {
  75061. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75062. }
  75063. });
  75064. // Clear according to the chosen filter.
  75065. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75066. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75067. this._shadowMap.onClearObservable.add(function (engine) {
  75068. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75069. engine.clear(clearOne, false, true, false);
  75070. }
  75071. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75072. engine.clear(clearZero, true, true, false);
  75073. }
  75074. else {
  75075. engine.clear(clearOne, true, true, false);
  75076. }
  75077. });
  75078. };
  75079. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75080. var _this = this;
  75081. var engine = this._scene.getEngine();
  75082. var targetSize = this._mapSize / this.blurScale;
  75083. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75084. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75085. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75086. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75087. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75088. }
  75089. if (this.useKernelBlur) {
  75090. 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);
  75091. this._kernelBlurXPostprocess.width = targetSize;
  75092. this._kernelBlurXPostprocess.height = targetSize;
  75093. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75094. effect.setTexture("textureSampler", _this._shadowMap);
  75095. });
  75096. 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);
  75097. this._kernelBlurXPostprocess.autoClear = false;
  75098. this._kernelBlurYPostprocess.autoClear = false;
  75099. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75100. this._kernelBlurXPostprocess.packedFloat = true;
  75101. this._kernelBlurYPostprocess.packedFloat = true;
  75102. }
  75103. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75104. }
  75105. else {
  75106. 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);
  75107. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75108. effect.setFloat2("screenSize", targetSize, targetSize);
  75109. effect.setTexture("textureSampler", _this._shadowMap);
  75110. });
  75111. this._boxBlurPostprocess.autoClear = false;
  75112. this._blurPostProcesses = [this._boxBlurPostprocess];
  75113. }
  75114. };
  75115. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75116. var index;
  75117. var engine = this._scene.getEngine();
  75118. if (depthOnlySubMeshes.length) {
  75119. engine.setColorWrite(false);
  75120. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75121. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75122. }
  75123. engine.setColorWrite(true);
  75124. }
  75125. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75126. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75127. }
  75128. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75129. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75130. }
  75131. if (this._transparencyShadow) {
  75132. for (index = 0; index < transparentSubMeshes.length; index++) {
  75133. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75134. }
  75135. }
  75136. };
  75137. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75138. var _this = this;
  75139. var mesh = subMesh.getRenderingMesh();
  75140. var scene = this._scene;
  75141. var engine = scene.getEngine();
  75142. var material = subMesh.getMaterial();
  75143. if (!material) {
  75144. return;
  75145. }
  75146. // Culling
  75147. engine.setState(material.backFaceCulling);
  75148. // Managing instances
  75149. var batch = mesh._getInstancesRenderList(subMesh._id);
  75150. if (batch.mustReturn) {
  75151. return;
  75152. }
  75153. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75154. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75155. engine.enableEffect(this._effect);
  75156. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75157. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75158. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75159. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75160. this._effect.setVector3("lightData", this._cachedDirection);
  75161. }
  75162. else {
  75163. this._effect.setVector3("lightData", this._cachedPosition);
  75164. }
  75165. if (scene.activeCamera) {
  75166. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75167. }
  75168. // Alpha test
  75169. if (material && material.needAlphaTesting()) {
  75170. var alphaTexture = material.getAlphaTestTexture();
  75171. if (alphaTexture) {
  75172. this._effect.setTexture("diffuseSampler", alphaTexture);
  75173. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75174. }
  75175. }
  75176. // Bones
  75177. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75178. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75179. }
  75180. // Morph targets
  75181. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75182. if (this.forceBackFacesOnly) {
  75183. engine.setState(true, 0, false, true);
  75184. }
  75185. // Draw
  75186. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75187. if (this.forceBackFacesOnly) {
  75188. engine.setState(true, 0, false, false);
  75189. }
  75190. }
  75191. else {
  75192. // Need to reset refresh rate of the shadowMap
  75193. if (this._shadowMap) {
  75194. this._shadowMap.resetRefreshCounter();
  75195. }
  75196. }
  75197. };
  75198. ShadowGenerator.prototype._applyFilterValues = function () {
  75199. if (!this._shadowMap) {
  75200. return;
  75201. }
  75202. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75203. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75204. }
  75205. else {
  75206. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75207. }
  75208. };
  75209. /**
  75210. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75211. * @param onCompiled Callback triggered at the and of the effects compilation
  75212. * @param options Sets of optional options forcing the compilation with different modes
  75213. */
  75214. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75215. var _this = this;
  75216. var localOptions = __assign({ useInstances: false }, options);
  75217. var shadowMap = this.getShadowMap();
  75218. if (!shadowMap) {
  75219. if (onCompiled) {
  75220. onCompiled(this);
  75221. }
  75222. return;
  75223. }
  75224. var renderList = shadowMap.renderList;
  75225. if (!renderList) {
  75226. if (onCompiled) {
  75227. onCompiled(this);
  75228. }
  75229. return;
  75230. }
  75231. var subMeshes = new Array();
  75232. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75233. var mesh = renderList_1[_i];
  75234. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75235. }
  75236. if (subMeshes.length === 0) {
  75237. if (onCompiled) {
  75238. onCompiled(this);
  75239. }
  75240. return;
  75241. }
  75242. var currentIndex = 0;
  75243. var checkReady = function () {
  75244. if (!_this._scene || !_this._scene.getEngine()) {
  75245. return;
  75246. }
  75247. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75248. currentIndex++;
  75249. if (currentIndex >= subMeshes.length) {
  75250. if (onCompiled) {
  75251. onCompiled(_this);
  75252. }
  75253. return;
  75254. }
  75255. }
  75256. setTimeout(checkReady, 16);
  75257. };
  75258. checkReady();
  75259. };
  75260. /**
  75261. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75262. * @param options Sets of optional options forcing the compilation with different modes
  75263. * @returns A promise that resolves when the compilation completes
  75264. */
  75265. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75266. var _this = this;
  75267. return new Promise(function (resolve) {
  75268. _this.forceCompilation(function () {
  75269. resolve();
  75270. }, options);
  75271. });
  75272. };
  75273. /**
  75274. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75275. * @param subMesh The submesh we want to render in the shadow map
  75276. * @param useInstances Defines wether will draw in the map using instances
  75277. * @returns true if ready otherwise, false
  75278. */
  75279. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75280. var defines = [];
  75281. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75282. defines.push("#define FLOAT");
  75283. }
  75284. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75285. defines.push("#define ESM");
  75286. }
  75287. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75288. defines.push("#define DEPTHTEXTURE");
  75289. }
  75290. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75291. var mesh = subMesh.getMesh();
  75292. var material = subMesh.getMaterial();
  75293. // Normal bias.
  75294. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75295. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75296. defines.push("#define NORMAL");
  75297. if (mesh.nonUniformScaling) {
  75298. defines.push("#define NONUNIFORMSCALING");
  75299. }
  75300. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75301. defines.push("#define DIRECTIONINLIGHTDATA");
  75302. }
  75303. }
  75304. // Alpha test
  75305. if (material && material.needAlphaTesting()) {
  75306. var alphaTexture = material.getAlphaTestTexture();
  75307. if (alphaTexture) {
  75308. defines.push("#define ALPHATEST");
  75309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75310. attribs.push(BABYLON.VertexBuffer.UVKind);
  75311. defines.push("#define UV1");
  75312. }
  75313. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75314. if (alphaTexture.coordinatesIndex === 1) {
  75315. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75316. defines.push("#define UV2");
  75317. }
  75318. }
  75319. }
  75320. }
  75321. // Bones
  75322. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75323. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75324. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75325. if (mesh.numBoneInfluencers > 4) {
  75326. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75327. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75328. }
  75329. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75330. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75331. }
  75332. else {
  75333. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75334. }
  75335. // Morph targets
  75336. var manager = mesh.morphTargetManager;
  75337. var morphInfluencers = 0;
  75338. if (manager) {
  75339. if (manager.numInfluencers > 0) {
  75340. defines.push("#define MORPHTARGETS");
  75341. morphInfluencers = manager.numInfluencers;
  75342. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75343. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75344. }
  75345. }
  75346. // Instances
  75347. if (useInstances) {
  75348. defines.push("#define INSTANCES");
  75349. attribs.push("world0");
  75350. attribs.push("world1");
  75351. attribs.push("world2");
  75352. attribs.push("world3");
  75353. }
  75354. // Get correct effect
  75355. var join = defines.join("\n");
  75356. if (this._cachedDefines !== join) {
  75357. this._cachedDefines = join;
  75358. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75359. }
  75360. if (!this._effect.isReady()) {
  75361. return false;
  75362. }
  75363. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75364. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75365. this._initializeBlurRTTAndPostProcesses();
  75366. }
  75367. }
  75368. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75369. return false;
  75370. }
  75371. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75372. return false;
  75373. }
  75374. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75375. return false;
  75376. }
  75377. return true;
  75378. };
  75379. /**
  75380. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75381. * @param defines Defines of the material we want to update
  75382. * @param lightIndex Index of the light in the enabled light list of the material
  75383. */
  75384. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75385. var scene = this._scene;
  75386. var light = this._light;
  75387. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75388. return;
  75389. }
  75390. defines["SHADOW" + lightIndex] = true;
  75391. if (this.useContactHardeningShadow) {
  75392. defines["SHADOWPCSS" + lightIndex] = true;
  75393. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75394. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75395. }
  75396. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75397. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75398. }
  75399. // else default to high.
  75400. }
  75401. if (this.usePercentageCloserFiltering) {
  75402. defines["SHADOWPCF" + lightIndex] = true;
  75403. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75404. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75405. }
  75406. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75407. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75408. }
  75409. // else default to high.
  75410. }
  75411. else if (this.usePoissonSampling) {
  75412. defines["SHADOWPOISSON" + lightIndex] = true;
  75413. }
  75414. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75415. defines["SHADOWESM" + lightIndex] = true;
  75416. }
  75417. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75418. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75419. }
  75420. if (light.needCube()) {
  75421. defines["SHADOWCUBE" + lightIndex] = true;
  75422. }
  75423. };
  75424. /**
  75425. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75426. * defined in the generator but impacting the effect).
  75427. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75428. * @param effect The effect we are binfing the information for
  75429. */
  75430. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75431. var light = this._light;
  75432. var scene = this._scene;
  75433. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75434. return;
  75435. }
  75436. var camera = scene.activeCamera;
  75437. if (!camera) {
  75438. return;
  75439. }
  75440. var shadowMap = this.getShadowMap();
  75441. if (!shadowMap) {
  75442. return;
  75443. }
  75444. if (!light.needCube()) {
  75445. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75446. }
  75447. // Only PCF uses depth stencil texture.
  75448. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75449. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75450. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75451. }
  75452. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75453. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75454. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75455. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75456. }
  75457. else {
  75458. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75459. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75460. }
  75461. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75462. };
  75463. /**
  75464. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75465. * (eq to shadow prjection matrix * light transform matrix)
  75466. * @returns The transform matrix used to create the shadow map
  75467. */
  75468. ShadowGenerator.prototype.getTransformMatrix = function () {
  75469. var scene = this._scene;
  75470. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75471. return this._transformMatrix;
  75472. }
  75473. this._currentRenderID = scene.getRenderId();
  75474. this._currentFaceIndexCache = this._currentFaceIndex;
  75475. var lightPosition = this._light.position;
  75476. if (this._light.computeTransformedInformation()) {
  75477. lightPosition = this._light.transformedPosition;
  75478. }
  75479. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75480. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75481. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75482. }
  75483. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75484. this._cachedPosition.copyFrom(lightPosition);
  75485. this._cachedDirection.copyFrom(this._lightDirection);
  75486. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75487. var shadowMap = this.getShadowMap();
  75488. if (shadowMap) {
  75489. var renderList = shadowMap.renderList;
  75490. if (renderList) {
  75491. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75492. }
  75493. }
  75494. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75495. }
  75496. return this._transformMatrix;
  75497. };
  75498. /**
  75499. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75500. * Cube and 2D textures for instance.
  75501. */
  75502. ShadowGenerator.prototype.recreateShadowMap = function () {
  75503. var shadowMap = this._shadowMap;
  75504. if (!shadowMap) {
  75505. return;
  75506. }
  75507. // Track render list.
  75508. var renderList = shadowMap.renderList;
  75509. // Clean up existing data.
  75510. this._disposeRTTandPostProcesses();
  75511. // Reinitializes.
  75512. this._initializeGenerator();
  75513. // Reaffect the filter to ensure a correct fallback if necessary.
  75514. this.filter = this.filter;
  75515. // Reaffect the filter.
  75516. this._applyFilterValues();
  75517. // Reaffect Render List.
  75518. this._shadowMap.renderList = renderList;
  75519. };
  75520. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75521. if (this._shadowMap2) {
  75522. this._shadowMap2.dispose();
  75523. this._shadowMap2 = null;
  75524. }
  75525. if (this._boxBlurPostprocess) {
  75526. this._boxBlurPostprocess.dispose();
  75527. this._boxBlurPostprocess = null;
  75528. }
  75529. if (this._kernelBlurXPostprocess) {
  75530. this._kernelBlurXPostprocess.dispose();
  75531. this._kernelBlurXPostprocess = null;
  75532. }
  75533. if (this._kernelBlurYPostprocess) {
  75534. this._kernelBlurYPostprocess.dispose();
  75535. this._kernelBlurYPostprocess = null;
  75536. }
  75537. this._blurPostProcesses = [];
  75538. };
  75539. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75540. if (this._shadowMap) {
  75541. this._shadowMap.dispose();
  75542. this._shadowMap = null;
  75543. }
  75544. this._disposeBlurPostProcesses();
  75545. };
  75546. /**
  75547. * Disposes the ShadowGenerator.
  75548. * Returns nothing.
  75549. */
  75550. ShadowGenerator.prototype.dispose = function () {
  75551. this._disposeRTTandPostProcesses();
  75552. if (this._light) {
  75553. this._light._shadowGenerator = null;
  75554. this._light._markMeshesAsLightDirty();
  75555. }
  75556. };
  75557. /**
  75558. * Serializes the shadow generator setup to a json object.
  75559. * @returns The serialized JSON object
  75560. */
  75561. ShadowGenerator.prototype.serialize = function () {
  75562. var serializationObject = {};
  75563. var shadowMap = this.getShadowMap();
  75564. if (!shadowMap) {
  75565. return serializationObject;
  75566. }
  75567. serializationObject.lightId = this._light.id;
  75568. serializationObject.mapSize = shadowMap.getRenderSize();
  75569. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75570. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75571. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75572. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75573. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75574. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75575. serializationObject.depthScale = this.depthScale;
  75576. serializationObject.darkness = this.getDarkness();
  75577. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75578. serializationObject.blurKernel = this.blurKernel;
  75579. serializationObject.blurScale = this.blurScale;
  75580. serializationObject.useKernelBlur = this.useKernelBlur;
  75581. serializationObject.transparencyShadow = this._transparencyShadow;
  75582. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75583. serializationObject.bias = this.bias;
  75584. serializationObject.normalBias = this.normalBias;
  75585. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75586. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75587. serializationObject.filteringQuality = this.filteringQuality;
  75588. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75589. serializationObject.renderList = [];
  75590. if (shadowMap.renderList) {
  75591. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75592. var mesh = shadowMap.renderList[meshIndex];
  75593. serializationObject.renderList.push(mesh.id);
  75594. }
  75595. }
  75596. return serializationObject;
  75597. };
  75598. /**
  75599. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75600. * @param parsedShadowGenerator The JSON object to parse
  75601. * @param scene The scene to create the shadow map for
  75602. * @returns The parsed shadow generator
  75603. */
  75604. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75605. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75606. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75607. var shadowMap = shadowGenerator.getShadowMap();
  75608. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75609. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75610. meshes.forEach(function (mesh) {
  75611. if (!shadowMap) {
  75612. return;
  75613. }
  75614. if (!shadowMap.renderList) {
  75615. shadowMap.renderList = [];
  75616. }
  75617. shadowMap.renderList.push(mesh);
  75618. });
  75619. }
  75620. if (parsedShadowGenerator.usePoissonSampling) {
  75621. shadowGenerator.usePoissonSampling = true;
  75622. }
  75623. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75624. shadowGenerator.useExponentialShadowMap = true;
  75625. }
  75626. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75627. shadowGenerator.useBlurExponentialShadowMap = true;
  75628. }
  75629. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75630. shadowGenerator.useCloseExponentialShadowMap = true;
  75631. }
  75632. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75633. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75634. }
  75635. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75636. shadowGenerator.usePercentageCloserFiltering = true;
  75637. }
  75638. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75639. shadowGenerator.useContactHardeningShadow = true;
  75640. }
  75641. if (parsedShadowGenerator.filteringQuality) {
  75642. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75643. }
  75644. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75645. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75646. }
  75647. // Backward compat
  75648. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75649. shadowGenerator.useExponentialShadowMap = true;
  75650. }
  75651. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75652. shadowGenerator.useBlurExponentialShadowMap = true;
  75653. }
  75654. if (parsedShadowGenerator.depthScale) {
  75655. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75656. }
  75657. if (parsedShadowGenerator.blurScale) {
  75658. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75659. }
  75660. if (parsedShadowGenerator.blurBoxOffset) {
  75661. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75662. }
  75663. if (parsedShadowGenerator.useKernelBlur) {
  75664. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75665. }
  75666. if (parsedShadowGenerator.blurKernel) {
  75667. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75668. }
  75669. if (parsedShadowGenerator.bias !== undefined) {
  75670. shadowGenerator.bias = parsedShadowGenerator.bias;
  75671. }
  75672. if (parsedShadowGenerator.normalBias !== undefined) {
  75673. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75674. }
  75675. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75676. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75677. }
  75678. if (parsedShadowGenerator.darkness) {
  75679. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75680. }
  75681. if (parsedShadowGenerator.transparencyShadow) {
  75682. shadowGenerator.setTransparencyShadow(true);
  75683. }
  75684. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75685. return shadowGenerator;
  75686. };
  75687. /**
  75688. * Shadow generator mode None: no filtering applied.
  75689. */
  75690. ShadowGenerator.FILTER_NONE = 0;
  75691. /**
  75692. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75693. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75694. */
  75695. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75696. /**
  75697. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75698. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75699. */
  75700. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75701. /**
  75702. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  75703. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75704. */
  75705. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  75706. /**
  75707. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  75708. * edge artifacts on steep falloff.
  75709. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75710. */
  75711. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  75712. /**
  75713. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  75714. * edge artifacts on steep falloff.
  75715. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75716. */
  75717. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  75718. /**
  75719. * Shadow generator mode PCF: Percentage Closer Filtering
  75720. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75721. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  75722. */
  75723. ShadowGenerator.FILTER_PCF = 6;
  75724. /**
  75725. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  75726. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75727. * Contact Hardening
  75728. */
  75729. ShadowGenerator.FILTER_PCSS = 7;
  75730. /**
  75731. * Reserved for PCF and PCSS
  75732. * Highest Quality.
  75733. *
  75734. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  75735. *
  75736. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  75737. */
  75738. ShadowGenerator.QUALITY_HIGH = 0;
  75739. /**
  75740. * Reserved for PCF and PCSS
  75741. * Good tradeoff for quality/perf cross devices
  75742. *
  75743. * Execute PCF on a 3*3 kernel.
  75744. *
  75745. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  75746. */
  75747. ShadowGenerator.QUALITY_MEDIUM = 1;
  75748. /**
  75749. * Reserved for PCF and PCSS
  75750. * The lowest quality but the fastest.
  75751. *
  75752. * Execute PCF on a 1*1 kernel.
  75753. *
  75754. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  75755. */
  75756. ShadowGenerator.QUALITY_LOW = 2;
  75757. return ShadowGenerator;
  75758. }());
  75759. BABYLON.ShadowGenerator = ShadowGenerator;
  75760. })(BABYLON || (BABYLON = {}));
  75761. //# sourceMappingURL=babylon.shadowGenerator.js.map
  75762. var BABYLON;
  75763. (function (BABYLON) {
  75764. // Adds the parser to the scene parsers.
  75765. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  75766. // Shadows
  75767. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  75768. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  75769. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  75770. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  75771. // SG would be available on their associated lights
  75772. }
  75773. }
  75774. });
  75775. /**
  75776. * Defines the shadow generator component responsible to manage any shadow generators
  75777. * in a given scene.
  75778. */
  75779. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  75780. /**
  75781. * Creates a new instance of the component for the given scene
  75782. * @param scene Defines the scene to register the component in
  75783. */
  75784. function ShadowGeneratorSceneComponent(scene) {
  75785. /**
  75786. * The component name helpfull to identify the component in the list of scene components.
  75787. */
  75788. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  75789. this.scene = scene;
  75790. }
  75791. /**
  75792. * Registers the component in a given scene
  75793. */
  75794. ShadowGeneratorSceneComponent.prototype.register = function () {
  75795. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  75796. };
  75797. /**
  75798. * Rebuilds the elements related to this component in case of
  75799. * context lost for instance.
  75800. */
  75801. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  75802. // Nothing To Do Here.
  75803. };
  75804. /**
  75805. * Serializes the component data to the specified json object
  75806. * @param serializationObject The object to serialize to
  75807. */
  75808. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  75809. // Shadows
  75810. serializationObject.shadowGenerators = [];
  75811. var lights = this.scene.lights;
  75812. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  75813. var light = lights_1[_i];
  75814. var shadowGenerator = light.getShadowGenerator();
  75815. if (shadowGenerator) {
  75816. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75817. }
  75818. }
  75819. };
  75820. /**
  75821. * Adds all the element from the container to the scene
  75822. * @param container the container holding the elements
  75823. */
  75824. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  75825. // Nothing To Do Here. (directly attached to a light)
  75826. };
  75827. /**
  75828. * Removes all the elements in the container from the scene
  75829. * @param container contains the elements to remove
  75830. */
  75831. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  75832. // Nothing To Do Here. (directly attached to a light)
  75833. };
  75834. /**
  75835. * Rebuilds the elements related to this component in case of
  75836. * context lost for instance.
  75837. */
  75838. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  75839. // Nothing To Do Here.
  75840. };
  75841. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75842. // Shadows
  75843. var scene = this.scene;
  75844. if (this.scene.shadowsEnabled) {
  75845. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  75846. var light = scene.lights[lightIndex];
  75847. var shadowGenerator = light.getShadowGenerator();
  75848. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75849. var shadowMap = (shadowGenerator.getShadowMap());
  75850. if (scene.textures.indexOf(shadowMap) !== -1) {
  75851. renderTargets.push(shadowMap);
  75852. }
  75853. }
  75854. }
  75855. }
  75856. };
  75857. return ShadowGeneratorSceneComponent;
  75858. }());
  75859. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75860. })(BABYLON || (BABYLON = {}));
  75861. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75862. var BABYLON;
  75863. (function (BABYLON) {
  75864. /**
  75865. * Class used for the default loading screen
  75866. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  75867. */
  75868. var DefaultLoadingScreen = /** @class */ (function () {
  75869. /**
  75870. * Creates a new default loading screen
  75871. * @param _renderingCanvas defines the canvas used to render the scene
  75872. * @param _loadingText defines the default text to display
  75873. * @param _loadingDivBackgroundColor defines the default background color
  75874. */
  75875. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75876. if (_loadingText === void 0) { _loadingText = ""; }
  75877. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75878. var _this = this;
  75879. this._renderingCanvas = _renderingCanvas;
  75880. this._loadingText = _loadingText;
  75881. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75882. // Resize
  75883. this._resizeLoadingUI = function () {
  75884. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75885. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75886. if (!_this._loadingDiv) {
  75887. return;
  75888. }
  75889. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75890. _this._loadingDiv.style.left = canvasRect.left + "px";
  75891. _this._loadingDiv.style.top = canvasRect.top + "px";
  75892. _this._loadingDiv.style.width = canvasRect.width + "px";
  75893. _this._loadingDiv.style.height = canvasRect.height + "px";
  75894. };
  75895. }
  75896. /**
  75897. * Function called to display the loading screen
  75898. */
  75899. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75900. if (this._loadingDiv) {
  75901. // Do not add a loading screen if there is already one
  75902. return;
  75903. }
  75904. this._loadingDiv = document.createElement("div");
  75905. this._loadingDiv.id = "babylonjsLoadingDiv";
  75906. this._loadingDiv.style.opacity = "0";
  75907. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75908. this._loadingDiv.style.pointerEvents = "none";
  75909. // Loading text
  75910. this._loadingTextDiv = document.createElement("div");
  75911. this._loadingTextDiv.style.position = "absolute";
  75912. this._loadingTextDiv.style.left = "0";
  75913. this._loadingTextDiv.style.top = "50%";
  75914. this._loadingTextDiv.style.marginTop = "80px";
  75915. this._loadingTextDiv.style.width = "100%";
  75916. this._loadingTextDiv.style.height = "20px";
  75917. this._loadingTextDiv.style.fontFamily = "Arial";
  75918. this._loadingTextDiv.style.fontSize = "14px";
  75919. this._loadingTextDiv.style.color = "white";
  75920. this._loadingTextDiv.style.textAlign = "center";
  75921. this._loadingTextDiv.innerHTML = "Loading";
  75922. this._loadingDiv.appendChild(this._loadingTextDiv);
  75923. //set the predefined text
  75924. this._loadingTextDiv.innerHTML = this._loadingText;
  75925. // Generating keyframes
  75926. var style = document.createElement('style');
  75927. style.type = 'text/css';
  75928. 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 }";
  75929. style.innerHTML = keyFrames;
  75930. document.getElementsByTagName('head')[0].appendChild(style);
  75931. // Loading img
  75932. var imgBack = new Image();
  75933. 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";
  75934. imgBack.style.position = "absolute";
  75935. imgBack.style.left = "50%";
  75936. imgBack.style.top = "50%";
  75937. imgBack.style.marginLeft = "-60px";
  75938. imgBack.style.marginTop = "-60px";
  75939. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75940. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75941. imgBack.style.transformOrigin = "50% 50%";
  75942. imgBack.style.webkitTransformOrigin = "50% 50%";
  75943. this._loadingDiv.appendChild(imgBack);
  75944. this._resizeLoadingUI();
  75945. window.addEventListener("resize", this._resizeLoadingUI);
  75946. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75947. document.body.appendChild(this._loadingDiv);
  75948. this._loadingDiv.style.opacity = "1";
  75949. };
  75950. /**
  75951. * Function called to hide the loading screen
  75952. */
  75953. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75954. var _this = this;
  75955. if (!this._loadingDiv) {
  75956. return;
  75957. }
  75958. var onTransitionEnd = function () {
  75959. if (!_this._loadingDiv) {
  75960. return;
  75961. }
  75962. document.body.removeChild(_this._loadingDiv);
  75963. window.removeEventListener("resize", _this._resizeLoadingUI);
  75964. _this._loadingDiv = null;
  75965. };
  75966. this._loadingDiv.style.opacity = "0";
  75967. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75968. };
  75969. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75970. get: function () {
  75971. return this._loadingText;
  75972. },
  75973. /**
  75974. * Gets or sets the text to display while loading
  75975. */
  75976. set: function (text) {
  75977. this._loadingText = text;
  75978. if (this._loadingTextDiv) {
  75979. this._loadingTextDiv.innerHTML = this._loadingText;
  75980. }
  75981. },
  75982. enumerable: true,
  75983. configurable: true
  75984. });
  75985. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  75986. /**
  75987. * Gets or sets the color to use for the background
  75988. */
  75989. get: function () {
  75990. return this._loadingDivBackgroundColor;
  75991. },
  75992. set: function (color) {
  75993. this._loadingDivBackgroundColor = color;
  75994. if (!this._loadingDiv) {
  75995. return;
  75996. }
  75997. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75998. },
  75999. enumerable: true,
  76000. configurable: true
  76001. });
  76002. return DefaultLoadingScreen;
  76003. }());
  76004. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  76005. })(BABYLON || (BABYLON = {}));
  76006. //# sourceMappingURL=babylon.loadingScreen.js.map
  76007. var BABYLON;
  76008. (function (BABYLON) {
  76009. /**
  76010. * Class used to represent data loading progression
  76011. */
  76012. var SceneLoaderProgressEvent = /** @class */ (function () {
  76013. /**
  76014. * Create a new progress event
  76015. * @param lengthComputable defines if data length to load can be evaluated
  76016. * @param loaded defines the loaded data length
  76017. * @param total defines the data length to load
  76018. */
  76019. function SceneLoaderProgressEvent(
  76020. /** defines if data length to load can be evaluated */
  76021. lengthComputable,
  76022. /** defines the loaded data length */
  76023. loaded,
  76024. /** defines the data length to load */
  76025. total) {
  76026. this.lengthComputable = lengthComputable;
  76027. this.loaded = loaded;
  76028. this.total = total;
  76029. }
  76030. /**
  76031. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76032. * @param event defines the source event
  76033. * @returns a new SceneLoaderProgressEvent
  76034. */
  76035. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76036. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76037. };
  76038. return SceneLoaderProgressEvent;
  76039. }());
  76040. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76041. /**
  76042. * Class used to load scene from various file formats using registered plugins
  76043. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76044. */
  76045. var SceneLoader = /** @class */ (function () {
  76046. function SceneLoader() {
  76047. }
  76048. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76049. /**
  76050. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76051. */
  76052. get: function () {
  76053. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76054. },
  76055. set: function (value) {
  76056. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76057. },
  76058. enumerable: true,
  76059. configurable: true
  76060. });
  76061. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76062. /**
  76063. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76064. */
  76065. get: function () {
  76066. return SceneLoader._ShowLoadingScreen;
  76067. },
  76068. set: function (value) {
  76069. SceneLoader._ShowLoadingScreen = value;
  76070. },
  76071. enumerable: true,
  76072. configurable: true
  76073. });
  76074. Object.defineProperty(SceneLoader, "loggingLevel", {
  76075. /**
  76076. * Defines the current logging level (while loading the scene)
  76077. * @ignorenaming
  76078. */
  76079. get: function () {
  76080. return SceneLoader._loggingLevel;
  76081. },
  76082. set: function (value) {
  76083. SceneLoader._loggingLevel = value;
  76084. },
  76085. enumerable: true,
  76086. configurable: true
  76087. });
  76088. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76089. /**
  76090. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76091. */
  76092. get: function () {
  76093. return SceneLoader._CleanBoneMatrixWeights;
  76094. },
  76095. set: function (value) {
  76096. SceneLoader._CleanBoneMatrixWeights = value;
  76097. },
  76098. enumerable: true,
  76099. configurable: true
  76100. });
  76101. SceneLoader._getDefaultPlugin = function () {
  76102. return SceneLoader._registeredPlugins[".babylon"];
  76103. };
  76104. SceneLoader._getPluginForExtension = function (extension) {
  76105. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76106. if (registeredPlugin) {
  76107. return registeredPlugin;
  76108. }
  76109. 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");
  76110. return SceneLoader._getDefaultPlugin();
  76111. };
  76112. SceneLoader._getPluginForDirectLoad = function (data) {
  76113. for (var extension in SceneLoader._registeredPlugins) {
  76114. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76115. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76116. return SceneLoader._registeredPlugins[extension];
  76117. }
  76118. }
  76119. return SceneLoader._getDefaultPlugin();
  76120. };
  76121. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76122. var queryStringPosition = sceneFilename.indexOf("?");
  76123. if (queryStringPosition !== -1) {
  76124. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76125. }
  76126. var dotPosition = sceneFilename.lastIndexOf(".");
  76127. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76128. return SceneLoader._getPluginForExtension(extension);
  76129. };
  76130. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76131. SceneLoader._getDirectLoad = function (sceneFilename) {
  76132. if (sceneFilename.substr(0, 5) === "data:") {
  76133. return sceneFilename.substr(5);
  76134. }
  76135. return null;
  76136. };
  76137. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76138. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76139. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76140. var plugin;
  76141. if (registeredPlugin.plugin.createPlugin) {
  76142. plugin = registeredPlugin.plugin.createPlugin();
  76143. }
  76144. else {
  76145. plugin = registeredPlugin.plugin;
  76146. }
  76147. var useArrayBuffer = registeredPlugin.isBinary;
  76148. var database;
  76149. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76150. var dataCallback = function (data, responseURL) {
  76151. if (scene.isDisposed) {
  76152. onError("Scene has been disposed");
  76153. return;
  76154. }
  76155. scene.database = database;
  76156. onSuccess(plugin, data, responseURL);
  76157. };
  76158. var request = null;
  76159. var pluginDisposed = false;
  76160. var onDisposeObservable = plugin.onDisposeObservable;
  76161. if (onDisposeObservable) {
  76162. onDisposeObservable.add(function () {
  76163. pluginDisposed = true;
  76164. if (request) {
  76165. request.abort();
  76166. request = null;
  76167. }
  76168. onDispose();
  76169. });
  76170. }
  76171. var manifestChecked = function () {
  76172. if (pluginDisposed) {
  76173. return;
  76174. }
  76175. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76176. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76177. } : undefined, database, useArrayBuffer, function (request, exception) {
  76178. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76179. });
  76180. };
  76181. if (directLoad) {
  76182. dataCallback(directLoad);
  76183. return plugin;
  76184. }
  76185. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76186. var engine = scene.getEngine();
  76187. var canUseOfflineSupport = engine.enableOfflineSupport;
  76188. if (canUseOfflineSupport) {
  76189. // Also check for exceptions
  76190. var exceptionFound = false;
  76191. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76192. var regex = _a[_i];
  76193. if (regex.test(fileInfo.url)) {
  76194. exceptionFound = true;
  76195. break;
  76196. }
  76197. }
  76198. canUseOfflineSupport = !exceptionFound;
  76199. }
  76200. if (canUseOfflineSupport) {
  76201. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76202. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76203. }
  76204. else {
  76205. manifestChecked();
  76206. }
  76207. }
  76208. // Loading file from disk via input file or drag'n'drop
  76209. else {
  76210. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76211. if (file) {
  76212. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76213. }
  76214. else {
  76215. onError("Unable to find file named " + fileInfo.name);
  76216. }
  76217. }
  76218. return plugin;
  76219. };
  76220. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76221. var url;
  76222. var name;
  76223. if (!sceneFilename) {
  76224. url = rootUrl;
  76225. name = BABYLON.Tools.GetFilename(rootUrl);
  76226. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76227. }
  76228. else {
  76229. if (sceneFilename.substr(0, 1) === "/") {
  76230. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76231. return null;
  76232. }
  76233. url = rootUrl + sceneFilename;
  76234. name = sceneFilename;
  76235. }
  76236. ;
  76237. return {
  76238. url: url,
  76239. rootUrl: rootUrl,
  76240. name: name
  76241. };
  76242. };
  76243. // Public functions
  76244. /**
  76245. * Gets a plugin that can load the given extension
  76246. * @param extension defines the extension to load
  76247. * @returns a plugin or null if none works
  76248. */
  76249. SceneLoader.GetPluginForExtension = function (extension) {
  76250. return SceneLoader._getPluginForExtension(extension).plugin;
  76251. };
  76252. /**
  76253. * Gets a boolean indicating that the given extension can be loaded
  76254. * @param extension defines the extension to load
  76255. * @returns true if the extension is supported
  76256. */
  76257. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76258. return !!SceneLoader._registeredPlugins[extension];
  76259. };
  76260. /**
  76261. * Adds a new plugin to the list of registered plugins
  76262. * @param plugin defines the plugin to add
  76263. */
  76264. SceneLoader.RegisterPlugin = function (plugin) {
  76265. if (typeof plugin.extensions === "string") {
  76266. var extension = plugin.extensions;
  76267. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76268. plugin: plugin,
  76269. isBinary: false
  76270. };
  76271. }
  76272. else {
  76273. var extensions = plugin.extensions;
  76274. Object.keys(extensions).forEach(function (extension) {
  76275. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76276. plugin: plugin,
  76277. isBinary: extensions[extension].isBinary
  76278. };
  76279. });
  76280. }
  76281. };
  76282. /**
  76283. * Import meshes into a scene
  76284. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76285. * @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)
  76286. * @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)
  76287. * @param scene the instance of BABYLON.Scene to append to
  76288. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76289. * @param onProgress a callback with a progress event for each file being loaded
  76290. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76291. * @param pluginExtension the extension used to determine the plugin
  76292. * @returns The loaded plugin
  76293. */
  76294. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76295. if (sceneFilename === void 0) { sceneFilename = ""; }
  76296. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76297. if (onSuccess === void 0) { onSuccess = null; }
  76298. if (onProgress === void 0) { onProgress = null; }
  76299. if (onError === void 0) { onError = null; }
  76300. if (pluginExtension === void 0) { pluginExtension = null; }
  76301. if (!scene) {
  76302. BABYLON.Tools.Error("No scene available to import mesh to");
  76303. return null;
  76304. }
  76305. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76306. if (!fileInfo) {
  76307. return null;
  76308. }
  76309. var loadingToken = {};
  76310. scene._addPendingData(loadingToken);
  76311. var disposeHandler = function () {
  76312. scene._removePendingData(loadingToken);
  76313. };
  76314. var errorHandler = function (message, exception) {
  76315. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76316. if (onError) {
  76317. onError(scene, errorMessage, exception);
  76318. }
  76319. else {
  76320. BABYLON.Tools.Error(errorMessage);
  76321. // should the exception be thrown?
  76322. }
  76323. disposeHandler();
  76324. };
  76325. var progressHandler = onProgress ? function (event) {
  76326. try {
  76327. onProgress(event);
  76328. }
  76329. catch (e) {
  76330. errorHandler("Error in onProgress callback", e);
  76331. }
  76332. } : undefined;
  76333. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76334. scene.importedMeshesFiles.push(fileInfo.url);
  76335. if (onSuccess) {
  76336. try {
  76337. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76338. }
  76339. catch (e) {
  76340. errorHandler("Error in onSuccess callback", e);
  76341. }
  76342. }
  76343. scene._removePendingData(loadingToken);
  76344. };
  76345. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76346. if (plugin.rewriteRootURL) {
  76347. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76348. }
  76349. if (plugin.importMesh) {
  76350. var syncedPlugin = plugin;
  76351. var meshes = new Array();
  76352. var particleSystems = new Array();
  76353. var skeletons = new Array();
  76354. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76355. return;
  76356. }
  76357. scene.loadingPluginName = plugin.name;
  76358. successHandler(meshes, particleSystems, skeletons, []);
  76359. }
  76360. else {
  76361. var asyncedPlugin = plugin;
  76362. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76363. scene.loadingPluginName = plugin.name;
  76364. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76365. }).catch(function (error) {
  76366. errorHandler(error.message, error);
  76367. });
  76368. }
  76369. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76370. };
  76371. /**
  76372. * Import meshes into a scene
  76373. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76374. * @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)
  76375. * @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)
  76376. * @param scene the instance of BABYLON.Scene to append to
  76377. * @param onProgress a callback with a progress event for each file being loaded
  76378. * @param pluginExtension the extension used to determine the plugin
  76379. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76380. */
  76381. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76382. if (sceneFilename === void 0) { sceneFilename = ""; }
  76383. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76384. if (onProgress === void 0) { onProgress = null; }
  76385. if (pluginExtension === void 0) { pluginExtension = null; }
  76386. return new Promise(function (resolve, reject) {
  76387. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76388. resolve({
  76389. meshes: meshes,
  76390. particleSystems: particleSystems,
  76391. skeletons: skeletons,
  76392. animationGroups: animationGroups
  76393. });
  76394. }, onProgress, function (scene, message, exception) {
  76395. reject(exception || new Error(message));
  76396. }, pluginExtension);
  76397. });
  76398. };
  76399. /**
  76400. * Load a scene
  76401. * @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)
  76402. * @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)
  76403. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76404. * @param onSuccess a callback with the scene when import succeeds
  76405. * @param onProgress a callback with a progress event for each file being loaded
  76406. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76407. * @param pluginExtension the extension used to determine the plugin
  76408. * @returns The loaded plugin
  76409. */
  76410. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76411. if (onSuccess === void 0) { onSuccess = null; }
  76412. if (onProgress === void 0) { onProgress = null; }
  76413. if (onError === void 0) { onError = null; }
  76414. if (pluginExtension === void 0) { pluginExtension = null; }
  76415. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76416. };
  76417. /**
  76418. * Load a scene
  76419. * @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)
  76420. * @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)
  76421. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76422. * @param onProgress a callback with a progress event for each file being loaded
  76423. * @param pluginExtension the extension used to determine the plugin
  76424. * @returns The loaded scene
  76425. */
  76426. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76427. if (onProgress === void 0) { onProgress = null; }
  76428. if (pluginExtension === void 0) { pluginExtension = null; }
  76429. return new Promise(function (resolve, reject) {
  76430. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76431. resolve(scene);
  76432. }, onProgress, function (scene, message, exception) {
  76433. reject(exception || new Error(message));
  76434. }, pluginExtension);
  76435. });
  76436. };
  76437. /**
  76438. * Append a scene
  76439. * @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)
  76440. * @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)
  76441. * @param scene is the instance of BABYLON.Scene to append to
  76442. * @param onSuccess a callback with the scene when import succeeds
  76443. * @param onProgress a callback with a progress event for each file being loaded
  76444. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76445. * @param pluginExtension the extension used to determine the plugin
  76446. * @returns The loaded plugin
  76447. */
  76448. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76449. if (sceneFilename === void 0) { sceneFilename = ""; }
  76450. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76451. if (onSuccess === void 0) { onSuccess = null; }
  76452. if (onProgress === void 0) { onProgress = null; }
  76453. if (onError === void 0) { onError = null; }
  76454. if (pluginExtension === void 0) { pluginExtension = null; }
  76455. if (!scene) {
  76456. BABYLON.Tools.Error("No scene available to append to");
  76457. return null;
  76458. }
  76459. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76460. if (!fileInfo) {
  76461. return null;
  76462. }
  76463. if (SceneLoader.ShowLoadingScreen) {
  76464. scene.getEngine().displayLoadingUI();
  76465. }
  76466. var loadingToken = {};
  76467. scene._addPendingData(loadingToken);
  76468. var disposeHandler = function () {
  76469. scene._removePendingData(loadingToken);
  76470. scene.getEngine().hideLoadingUI();
  76471. };
  76472. var errorHandler = function (message, exception) {
  76473. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76474. if (onError) {
  76475. onError(scene, errorMessage, exception);
  76476. }
  76477. else {
  76478. BABYLON.Tools.Error(errorMessage);
  76479. // should the exception be thrown?
  76480. }
  76481. disposeHandler();
  76482. };
  76483. var progressHandler = onProgress ? function (event) {
  76484. try {
  76485. onProgress(event);
  76486. }
  76487. catch (e) {
  76488. errorHandler("Error in onProgress callback", e);
  76489. }
  76490. } : undefined;
  76491. var successHandler = function () {
  76492. if (onSuccess) {
  76493. try {
  76494. onSuccess(scene);
  76495. }
  76496. catch (e) {
  76497. errorHandler("Error in onSuccess callback", e);
  76498. }
  76499. }
  76500. scene._removePendingData(loadingToken);
  76501. };
  76502. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76503. if (plugin.load) {
  76504. var syncedPlugin = plugin;
  76505. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76506. return;
  76507. }
  76508. scene.loadingPluginName = plugin.name;
  76509. successHandler();
  76510. }
  76511. else {
  76512. var asyncedPlugin = plugin;
  76513. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76514. scene.loadingPluginName = plugin.name;
  76515. successHandler();
  76516. }).catch(function (error) {
  76517. errorHandler(error.message, error);
  76518. });
  76519. }
  76520. if (SceneLoader.ShowLoadingScreen) {
  76521. scene.executeWhenReady(function () {
  76522. scene.getEngine().hideLoadingUI();
  76523. });
  76524. }
  76525. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76526. };
  76527. /**
  76528. * Append a scene
  76529. * @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)
  76530. * @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)
  76531. * @param scene is the instance of BABYLON.Scene to append to
  76532. * @param onProgress a callback with a progress event for each file being loaded
  76533. * @param pluginExtension the extension used to determine the plugin
  76534. * @returns The given scene
  76535. */
  76536. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76537. if (sceneFilename === void 0) { sceneFilename = ""; }
  76538. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76539. if (onProgress === void 0) { onProgress = null; }
  76540. if (pluginExtension === void 0) { pluginExtension = null; }
  76541. return new Promise(function (resolve, reject) {
  76542. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76543. resolve(scene);
  76544. }, onProgress, function (scene, message, exception) {
  76545. reject(exception || new Error(message));
  76546. }, pluginExtension);
  76547. });
  76548. };
  76549. /**
  76550. * Load a scene into an asset container
  76551. * @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)
  76552. * @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)
  76553. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76554. * @param onSuccess a callback with the scene when import succeeds
  76555. * @param onProgress a callback with a progress event for each file being loaded
  76556. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76557. * @param pluginExtension the extension used to determine the plugin
  76558. * @returns The loaded plugin
  76559. */
  76560. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76561. if (sceneFilename === void 0) { sceneFilename = ""; }
  76562. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76563. if (onSuccess === void 0) { onSuccess = null; }
  76564. if (onProgress === void 0) { onProgress = null; }
  76565. if (onError === void 0) { onError = null; }
  76566. if (pluginExtension === void 0) { pluginExtension = null; }
  76567. if (!scene) {
  76568. BABYLON.Tools.Error("No scene available to load asset container to");
  76569. return null;
  76570. }
  76571. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76572. if (!fileInfo) {
  76573. return null;
  76574. }
  76575. var loadingToken = {};
  76576. scene._addPendingData(loadingToken);
  76577. var disposeHandler = function () {
  76578. scene._removePendingData(loadingToken);
  76579. };
  76580. var errorHandler = function (message, exception) {
  76581. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76582. if (onError) {
  76583. onError(scene, errorMessage, exception);
  76584. }
  76585. else {
  76586. BABYLON.Tools.Error(errorMessage);
  76587. // should the exception be thrown?
  76588. }
  76589. disposeHandler();
  76590. };
  76591. var progressHandler = onProgress ? function (event) {
  76592. try {
  76593. onProgress(event);
  76594. }
  76595. catch (e) {
  76596. errorHandler("Error in onProgress callback", e);
  76597. }
  76598. } : undefined;
  76599. var successHandler = function (assets) {
  76600. if (onSuccess) {
  76601. try {
  76602. onSuccess(assets);
  76603. }
  76604. catch (e) {
  76605. errorHandler("Error in onSuccess callback", e);
  76606. }
  76607. }
  76608. scene._removePendingData(loadingToken);
  76609. };
  76610. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76611. if (plugin.loadAssetContainer) {
  76612. var syncedPlugin = plugin;
  76613. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76614. if (!assetContainer) {
  76615. return;
  76616. }
  76617. scene.loadingPluginName = plugin.name;
  76618. successHandler(assetContainer);
  76619. }
  76620. else if (plugin.loadAssetContainerAsync) {
  76621. var asyncedPlugin = plugin;
  76622. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76623. scene.loadingPluginName = plugin.name;
  76624. successHandler(assetContainer);
  76625. }).catch(function (error) {
  76626. errorHandler(error.message, error);
  76627. });
  76628. }
  76629. else {
  76630. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76631. }
  76632. if (SceneLoader.ShowLoadingScreen) {
  76633. scene.executeWhenReady(function () {
  76634. scene.getEngine().hideLoadingUI();
  76635. });
  76636. }
  76637. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76638. };
  76639. /**
  76640. * Load a scene into an asset container
  76641. * @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)
  76642. * @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)
  76643. * @param scene is the instance of BABYLON.Scene to append to
  76644. * @param onProgress a callback with a progress event for each file being loaded
  76645. * @param pluginExtension the extension used to determine the plugin
  76646. * @returns The loaded asset container
  76647. */
  76648. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76649. if (sceneFilename === void 0) { sceneFilename = ""; }
  76650. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76651. if (onProgress === void 0) { onProgress = null; }
  76652. if (pluginExtension === void 0) { pluginExtension = null; }
  76653. return new Promise(function (resolve, reject) {
  76654. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76655. resolve(assetContainer);
  76656. }, onProgress, function (scene, message, exception) {
  76657. reject(exception || new Error(message));
  76658. }, pluginExtension);
  76659. });
  76660. };
  76661. // Flags
  76662. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76663. SceneLoader._ShowLoadingScreen = true;
  76664. SceneLoader._CleanBoneMatrixWeights = false;
  76665. /**
  76666. * No logging while loading
  76667. */
  76668. SceneLoader.NO_LOGGING = 0;
  76669. /**
  76670. * Minimal logging while loading
  76671. */
  76672. SceneLoader.MINIMAL_LOGGING = 1;
  76673. /**
  76674. * Summary logging while loading
  76675. */
  76676. SceneLoader.SUMMARY_LOGGING = 2;
  76677. /**
  76678. * Detailled logging while loading
  76679. */
  76680. SceneLoader.DETAILED_LOGGING = 3;
  76681. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76682. // Members
  76683. /**
  76684. * Event raised when a plugin is used to load a scene
  76685. */
  76686. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76687. SceneLoader._registeredPlugins = {};
  76688. return SceneLoader;
  76689. }());
  76690. BABYLON.SceneLoader = SceneLoader;
  76691. ;
  76692. })(BABYLON || (BABYLON = {}));
  76693. //# sourceMappingURL=babylon.sceneLoader.js.map
  76694. var BABYLON;
  76695. (function (BABYLON) {
  76696. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76697. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76698. var parsedMaterial = parsedData.materials[index];
  76699. if (parsedMaterial.id === id) {
  76700. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76701. }
  76702. }
  76703. return null;
  76704. };
  76705. var isDescendantOf = function (mesh, names, hierarchyIds) {
  76706. for (var i in names) {
  76707. if (mesh.name === names[i]) {
  76708. hierarchyIds.push(mesh.id);
  76709. return true;
  76710. }
  76711. }
  76712. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  76713. hierarchyIds.push(mesh.id);
  76714. return true;
  76715. }
  76716. return false;
  76717. };
  76718. var logOperation = function (operation, producer) {
  76719. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  76720. };
  76721. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  76722. if (addToScene === void 0) { addToScene = false; }
  76723. var container = new BABYLON.AssetContainer(scene);
  76724. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76725. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76726. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76727. // and avoid problems with multiple concurrent .babylon loads.
  76728. var log = "importScene has failed JSON parse";
  76729. try {
  76730. var parsedData = JSON.parse(data);
  76731. log = "";
  76732. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76733. var index;
  76734. var cache;
  76735. // Lights
  76736. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  76737. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  76738. var parsedLight = parsedData.lights[index];
  76739. var light = BABYLON.Light.Parse(parsedLight, scene);
  76740. if (light) {
  76741. container.lights.push(light);
  76742. log += (index === 0 ? "\n\tLights:" : "");
  76743. log += "\n\t\t" + light.toString(fullDetails);
  76744. }
  76745. }
  76746. }
  76747. // Animations
  76748. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  76749. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  76750. var parsedAnimation = parsedData.animations[index];
  76751. var animation = BABYLON.Animation.Parse(parsedAnimation);
  76752. scene.animations.push(animation);
  76753. container.animations.push(animation);
  76754. log += (index === 0 ? "\n\tAnimations:" : "");
  76755. log += "\n\t\t" + animation.toString(fullDetails);
  76756. }
  76757. }
  76758. // Materials
  76759. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  76760. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76761. var parsedMaterial = parsedData.materials[index];
  76762. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76763. container.materials.push(mat);
  76764. log += (index === 0 ? "\n\tMaterials:" : "");
  76765. log += "\n\t\t" + mat.toString(fullDetails);
  76766. }
  76767. }
  76768. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76769. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  76770. var parsedMultiMaterial = parsedData.multiMaterials[index];
  76771. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76772. container.multiMaterials.push(mmat);
  76773. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  76774. log += "\n\t\t" + mmat.toString(fullDetails);
  76775. }
  76776. }
  76777. // Morph targets
  76778. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76779. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76780. var managerData = _a[_i];
  76781. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  76782. }
  76783. }
  76784. // Skeletons
  76785. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76786. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  76787. var parsedSkeleton = parsedData.skeletons[index];
  76788. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76789. container.skeletons.push(skeleton);
  76790. log += (index === 0 ? "\n\tSkeletons:" : "");
  76791. log += "\n\t\t" + skeleton.toString(fullDetails);
  76792. }
  76793. }
  76794. // Geometries
  76795. var geometries = parsedData.geometries;
  76796. if (geometries !== undefined && geometries !== null) {
  76797. var addedGeometry = new Array();
  76798. // Boxes
  76799. var boxes = geometries.boxes;
  76800. if (boxes !== undefined && boxes !== null) {
  76801. for (index = 0, cache = boxes.length; index < cache; index++) {
  76802. var parsedBox = boxes[index];
  76803. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  76804. }
  76805. }
  76806. // Spheres
  76807. var spheres = geometries.spheres;
  76808. if (spheres !== undefined && spheres !== null) {
  76809. for (index = 0, cache = spheres.length; index < cache; index++) {
  76810. var parsedSphere = spheres[index];
  76811. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  76812. }
  76813. }
  76814. // Cylinders
  76815. var cylinders = geometries.cylinders;
  76816. if (cylinders !== undefined && cylinders !== null) {
  76817. for (index = 0, cache = cylinders.length; index < cache; index++) {
  76818. var parsedCylinder = cylinders[index];
  76819. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  76820. }
  76821. }
  76822. // Toruses
  76823. var toruses = geometries.toruses;
  76824. if (toruses !== undefined && toruses !== null) {
  76825. for (index = 0, cache = toruses.length; index < cache; index++) {
  76826. var parsedTorus = toruses[index];
  76827. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  76828. }
  76829. }
  76830. // Grounds
  76831. var grounds = geometries.grounds;
  76832. if (grounds !== undefined && grounds !== null) {
  76833. for (index = 0, cache = grounds.length; index < cache; index++) {
  76834. var parsedGround = grounds[index];
  76835. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  76836. }
  76837. }
  76838. // Planes
  76839. var planes = geometries.planes;
  76840. if (planes !== undefined && planes !== null) {
  76841. for (index = 0, cache = planes.length; index < cache; index++) {
  76842. var parsedPlane = planes[index];
  76843. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  76844. }
  76845. }
  76846. // TorusKnots
  76847. var torusKnots = geometries.torusKnots;
  76848. if (torusKnots !== undefined && torusKnots !== null) {
  76849. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  76850. var parsedTorusKnot = torusKnots[index];
  76851. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  76852. }
  76853. }
  76854. // VertexData
  76855. var vertexData = geometries.vertexData;
  76856. if (vertexData !== undefined && vertexData !== null) {
  76857. for (index = 0, cache = vertexData.length; index < cache; index++) {
  76858. var parsedVertexData = vertexData[index];
  76859. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  76860. }
  76861. }
  76862. addedGeometry.forEach(function (g) {
  76863. if (g) {
  76864. container.geometries.push(g);
  76865. }
  76866. });
  76867. }
  76868. // Transform nodes
  76869. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  76870. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  76871. var parsedTransformNode = parsedData.transformNodes[index];
  76872. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  76873. container.transformNodes.push(node);
  76874. }
  76875. }
  76876. // Meshes
  76877. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76878. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76879. var parsedMesh = parsedData.meshes[index];
  76880. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76881. container.meshes.push(mesh);
  76882. log += (index === 0 ? "\n\tMeshes:" : "");
  76883. log += "\n\t\t" + mesh.toString(fullDetails);
  76884. }
  76885. }
  76886. // Cameras
  76887. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  76888. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  76889. var parsedCamera = parsedData.cameras[index];
  76890. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  76891. container.cameras.push(camera);
  76892. log += (index === 0 ? "\n\tCameras:" : "");
  76893. log += "\n\t\t" + camera.toString(fullDetails);
  76894. }
  76895. }
  76896. // Animation Groups
  76897. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  76898. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  76899. var parsedAnimationGroup = parsedData.animationGroups[index];
  76900. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  76901. container.animationGroups.push(animationGroup);
  76902. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  76903. log += "\n\t\t" + animationGroup.toString(fullDetails);
  76904. }
  76905. }
  76906. // Browsing all the graph to connect the dots
  76907. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  76908. var camera = scene.cameras[index];
  76909. if (camera._waitingParentId) {
  76910. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  76911. camera._waitingParentId = null;
  76912. }
  76913. }
  76914. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76915. var light_1 = scene.lights[index];
  76916. if (light_1 && light_1._waitingParentId) {
  76917. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76918. light_1._waitingParentId = null;
  76919. }
  76920. }
  76921. // Connect parents & children and parse actions
  76922. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76923. var transformNode = scene.transformNodes[index];
  76924. if (transformNode._waitingParentId) {
  76925. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76926. transformNode._waitingParentId = null;
  76927. }
  76928. }
  76929. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76930. var mesh = scene.meshes[index];
  76931. if (mesh._waitingParentId) {
  76932. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76933. mesh._waitingParentId = null;
  76934. }
  76935. }
  76936. // freeze world matrix application
  76937. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76938. var currentMesh = scene.meshes[index];
  76939. if (currentMesh._waitingFreezeWorldMatrix) {
  76940. currentMesh.freezeWorldMatrix();
  76941. currentMesh._waitingFreezeWorldMatrix = null;
  76942. }
  76943. else {
  76944. currentMesh.computeWorldMatrix(true);
  76945. }
  76946. }
  76947. // Lights exclusions / inclusions
  76948. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76949. var light_2 = scene.lights[index];
  76950. // Excluded check
  76951. if (light_2._excludedMeshesIds.length > 0) {
  76952. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76953. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76954. if (excludedMesh) {
  76955. light_2.excludedMeshes.push(excludedMesh);
  76956. }
  76957. }
  76958. light_2._excludedMeshesIds = [];
  76959. }
  76960. // Included check
  76961. if (light_2._includedOnlyMeshesIds.length > 0) {
  76962. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76963. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76964. if (includedOnlyMesh) {
  76965. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76966. }
  76967. }
  76968. light_2._includedOnlyMeshesIds = [];
  76969. }
  76970. }
  76971. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76972. // Actions (scene) Done last as it can access other objects.
  76973. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76974. var mesh = scene.meshes[index];
  76975. if (mesh._waitingActions) {
  76976. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  76977. mesh._waitingActions = null;
  76978. }
  76979. }
  76980. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  76981. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  76982. }
  76983. if (!addToScene) {
  76984. container.removeAllFromScene();
  76985. }
  76986. }
  76987. catch (err) {
  76988. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  76989. if (onError) {
  76990. onError(msg, err);
  76991. }
  76992. else {
  76993. BABYLON.Tools.Log(msg);
  76994. throw err;
  76995. }
  76996. }
  76997. finally {
  76998. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  76999. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77000. }
  77001. }
  77002. return container;
  77003. };
  77004. BABYLON.SceneLoader.RegisterPlugin({
  77005. name: "babylon.js",
  77006. extensions: ".babylon",
  77007. canDirectLoad: function (data) {
  77008. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  77009. return true;
  77010. }
  77011. return false;
  77012. },
  77013. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  77014. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77015. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77016. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77017. // and avoid problems with multiple concurrent .babylon loads.
  77018. var log = "importMesh has failed JSON parse";
  77019. try {
  77020. var parsedData = JSON.parse(data);
  77021. log = "";
  77022. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77023. if (!meshesNames) {
  77024. meshesNames = null;
  77025. }
  77026. else if (!Array.isArray(meshesNames)) {
  77027. meshesNames = [meshesNames];
  77028. }
  77029. var hierarchyIds = new Array();
  77030. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77031. var loadedSkeletonsIds = [];
  77032. var loadedMaterialsIds = [];
  77033. var index;
  77034. var cache;
  77035. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77036. var parsedMesh = parsedData.meshes[index];
  77037. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77038. if (meshesNames !== null) {
  77039. // Remove found mesh name from list.
  77040. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77041. }
  77042. //Geometry?
  77043. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77044. //does the file contain geometries?
  77045. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77046. //find the correct geometry and add it to the scene
  77047. var found = false;
  77048. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77049. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77050. return;
  77051. }
  77052. else {
  77053. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77054. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77055. switch (geometryType) {
  77056. case "boxes":
  77057. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77058. break;
  77059. case "spheres":
  77060. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77061. break;
  77062. case "cylinders":
  77063. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77064. break;
  77065. case "toruses":
  77066. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77067. break;
  77068. case "grounds":
  77069. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77070. break;
  77071. case "planes":
  77072. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77073. break;
  77074. case "torusKnots":
  77075. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77076. break;
  77077. case "vertexData":
  77078. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77079. break;
  77080. }
  77081. found = true;
  77082. }
  77083. });
  77084. }
  77085. });
  77086. if (found === false) {
  77087. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77088. }
  77089. }
  77090. }
  77091. // Material ?
  77092. if (parsedMesh.materialId) {
  77093. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77094. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77095. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77096. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77097. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77098. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77099. var subMatId = parsedMultiMaterial.materials[matIndex];
  77100. loadedMaterialsIds.push(subMatId);
  77101. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77102. if (mat) {
  77103. log += "\n\tMaterial " + mat.toString(fullDetails);
  77104. }
  77105. }
  77106. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77107. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77108. if (mmat) {
  77109. materialFound = true;
  77110. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77111. }
  77112. break;
  77113. }
  77114. }
  77115. }
  77116. if (materialFound === false) {
  77117. loadedMaterialsIds.push(parsedMesh.materialId);
  77118. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77119. if (!mat) {
  77120. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77121. }
  77122. else {
  77123. log += "\n\tMaterial " + mat.toString(fullDetails);
  77124. }
  77125. }
  77126. }
  77127. // Skeleton ?
  77128. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77129. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77130. if (skeletonAlreadyLoaded === false) {
  77131. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77132. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77133. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77134. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77135. skeletons.push(skeleton);
  77136. loadedSkeletonsIds.push(parsedSkeleton.id);
  77137. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77138. }
  77139. }
  77140. }
  77141. }
  77142. // Morph targets ?
  77143. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77144. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77145. var managerData = _a[_i];
  77146. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77147. }
  77148. }
  77149. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77150. meshes.push(mesh);
  77151. log += "\n\tMesh " + mesh.toString(fullDetails);
  77152. }
  77153. }
  77154. // Connecting parents
  77155. var currentMesh;
  77156. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77157. currentMesh = scene.meshes[index];
  77158. if (currentMesh._waitingParentId) {
  77159. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77160. currentMesh._waitingParentId = null;
  77161. }
  77162. }
  77163. // freeze and compute world matrix application
  77164. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77165. currentMesh = scene.meshes[index];
  77166. if (currentMesh._waitingFreezeWorldMatrix) {
  77167. currentMesh.freezeWorldMatrix();
  77168. currentMesh._waitingFreezeWorldMatrix = null;
  77169. }
  77170. else {
  77171. currentMesh.computeWorldMatrix(true);
  77172. }
  77173. }
  77174. }
  77175. // Particles
  77176. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77177. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77178. if (parser) {
  77179. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77180. var parsedParticleSystem = parsedData.particleSystems[index];
  77181. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77182. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77183. }
  77184. }
  77185. }
  77186. }
  77187. return true;
  77188. }
  77189. catch (err) {
  77190. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77191. if (onError) {
  77192. onError(msg, err);
  77193. }
  77194. else {
  77195. BABYLON.Tools.Log(msg);
  77196. throw err;
  77197. }
  77198. }
  77199. finally {
  77200. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77201. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77202. }
  77203. }
  77204. return false;
  77205. },
  77206. load: function (scene, data, rootUrl, onError) {
  77207. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77208. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77209. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77210. // and avoid problems with multiple concurrent .babylon loads.
  77211. var log = "importScene has failed JSON parse";
  77212. try {
  77213. var parsedData = JSON.parse(data);
  77214. log = "";
  77215. // Scene
  77216. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77217. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77218. }
  77219. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77220. scene.autoClear = parsedData.autoClear;
  77221. }
  77222. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77223. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77224. }
  77225. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77226. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77227. }
  77228. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77229. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77230. }
  77231. // Fog
  77232. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77233. scene.fogMode = parsedData.fogMode;
  77234. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77235. scene.fogStart = parsedData.fogStart;
  77236. scene.fogEnd = parsedData.fogEnd;
  77237. scene.fogDensity = parsedData.fogDensity;
  77238. log += "\tFog mode for scene: ";
  77239. switch (scene.fogMode) {
  77240. // getters not compiling, so using hardcoded
  77241. case 1:
  77242. log += "exp\n";
  77243. break;
  77244. case 2:
  77245. log += "exp2\n";
  77246. break;
  77247. case 3:
  77248. log += "linear\n";
  77249. break;
  77250. }
  77251. }
  77252. //Physics
  77253. if (parsedData.physicsEnabled) {
  77254. var physicsPlugin;
  77255. if (parsedData.physicsEngine === "cannon") {
  77256. physicsPlugin = new BABYLON.CannonJSPlugin();
  77257. }
  77258. else if (parsedData.physicsEngine === "oimo") {
  77259. physicsPlugin = new BABYLON.OimoJSPlugin();
  77260. }
  77261. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77262. //else - default engine, which is currently oimo
  77263. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77264. scene.enablePhysics(physicsGravity, physicsPlugin);
  77265. }
  77266. // Metadata
  77267. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77268. scene.metadata = parsedData.metadata;
  77269. }
  77270. //collisions, if defined. otherwise, default is true
  77271. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77272. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77273. }
  77274. scene.workerCollisions = !!parsedData.workerCollisions;
  77275. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77276. if (!container) {
  77277. return false;
  77278. }
  77279. if (parsedData.autoAnimate) {
  77280. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77281. }
  77282. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77283. scene.setActiveCameraByID(parsedData.activeCameraID);
  77284. }
  77285. // Environment texture
  77286. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77287. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77288. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77289. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77290. if (parsedData.environmentTextureRotationY) {
  77291. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77292. }
  77293. scene.environmentTexture = hdrTexture;
  77294. }
  77295. else {
  77296. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77297. if (parsedData.environmentTextureRotationY) {
  77298. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77299. }
  77300. scene.environmentTexture = cubeTexture;
  77301. }
  77302. if (parsedData.createDefaultSkybox === true) {
  77303. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77304. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77305. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77306. }
  77307. }
  77308. // Finish
  77309. return true;
  77310. }
  77311. catch (err) {
  77312. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77313. if (onError) {
  77314. onError(msg, err);
  77315. }
  77316. else {
  77317. BABYLON.Tools.Log(msg);
  77318. throw err;
  77319. }
  77320. }
  77321. finally {
  77322. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77323. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77324. }
  77325. }
  77326. return false;
  77327. },
  77328. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77329. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77330. return container;
  77331. }
  77332. });
  77333. })(BABYLON || (BABYLON = {}));
  77334. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77335. var BABYLON;
  77336. (function (BABYLON) {
  77337. /**
  77338. * Class used to help managing file picking and drag'n'drop
  77339. */
  77340. var FilesInput = /** @class */ (function () {
  77341. /**
  77342. * Creates a new FilesInput
  77343. * @param engine defines the rendering engine
  77344. * @param scene defines the hosting scene
  77345. * @param sceneLoadedCallback callback called when scene is loaded
  77346. * @param progressCallback callback called to track progress
  77347. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77348. * @param textureLoadingCallback callback called when a texture is loading
  77349. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77350. * @param onReloadCallback callback called when a reload is requested
  77351. * @param errorCallback callback call if an error occurs
  77352. */
  77353. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77354. /**
  77355. * Callback called when a file is processed
  77356. */
  77357. this.onProcessFileCallback = function () { return true; };
  77358. this._engine = engine;
  77359. this._currentScene = scene;
  77360. this._sceneLoadedCallback = sceneLoadedCallback;
  77361. this._progressCallback = progressCallback;
  77362. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77363. this._textureLoadingCallback = textureLoadingCallback;
  77364. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77365. this._onReloadCallback = onReloadCallback;
  77366. this._errorCallback = errorCallback;
  77367. }
  77368. /**
  77369. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77370. * @param elementToMonitor defines the DOM element to track
  77371. */
  77372. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77373. var _this = this;
  77374. if (elementToMonitor) {
  77375. this._elementToMonitor = elementToMonitor;
  77376. this._dragEnterHandler = function (e) { _this.drag(e); };
  77377. this._dragOverHandler = function (e) { _this.drag(e); };
  77378. this._dropHandler = function (e) { _this.drop(e); };
  77379. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77380. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77381. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77382. }
  77383. };
  77384. /**
  77385. * Release all associated resources
  77386. */
  77387. FilesInput.prototype.dispose = function () {
  77388. if (!this._elementToMonitor) {
  77389. return;
  77390. }
  77391. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77392. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77393. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77394. };
  77395. FilesInput.prototype.renderFunction = function () {
  77396. if (this._additionalRenderLoopLogicCallback) {
  77397. this._additionalRenderLoopLogicCallback();
  77398. }
  77399. if (this._currentScene) {
  77400. if (this._textureLoadingCallback) {
  77401. var remaining = this._currentScene.getWaitingItemsCount();
  77402. if (remaining > 0) {
  77403. this._textureLoadingCallback(remaining);
  77404. }
  77405. }
  77406. this._currentScene.render();
  77407. }
  77408. };
  77409. FilesInput.prototype.drag = function (e) {
  77410. e.stopPropagation();
  77411. e.preventDefault();
  77412. };
  77413. FilesInput.prototype.drop = function (eventDrop) {
  77414. eventDrop.stopPropagation();
  77415. eventDrop.preventDefault();
  77416. this.loadFiles(eventDrop);
  77417. };
  77418. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77419. var _this = this;
  77420. var reader = folder.createReader();
  77421. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77422. reader.readEntries(function (entries) {
  77423. remaining.count += entries.length;
  77424. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77425. var entry = entries_1[_i];
  77426. if (entry.isFile) {
  77427. entry.file(function (file) {
  77428. file.correctName = relativePath + file.name;
  77429. files.push(file);
  77430. if (--remaining.count === 0) {
  77431. callback();
  77432. }
  77433. });
  77434. }
  77435. else if (entry.isDirectory) {
  77436. _this._traverseFolder(entry, files, remaining, callback);
  77437. }
  77438. }
  77439. if (--remaining.count) {
  77440. callback();
  77441. }
  77442. });
  77443. };
  77444. FilesInput.prototype._processFiles = function (files) {
  77445. for (var i = 0; i < files.length; i++) {
  77446. var name = files[i].correctName.toLowerCase();
  77447. var extension = name.split('.').pop();
  77448. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77449. continue;
  77450. }
  77451. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77452. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77453. this._sceneFileToLoad = files[i];
  77454. }
  77455. FilesInput.FilesToLoad[name] = files[i];
  77456. }
  77457. };
  77458. /**
  77459. * Load files from a drop event
  77460. * @param event defines the drop event to use as source
  77461. */
  77462. FilesInput.prototype.loadFiles = function (event) {
  77463. var _this = this;
  77464. // Handling data transfer via drag'n'drop
  77465. if (event && event.dataTransfer && event.dataTransfer.files) {
  77466. this._filesToLoad = event.dataTransfer.files;
  77467. }
  77468. // Handling files from input files
  77469. if (event && event.target && event.target.files) {
  77470. this._filesToLoad = event.target.files;
  77471. }
  77472. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77473. return;
  77474. }
  77475. if (this._startingProcessingFilesCallback) {
  77476. this._startingProcessingFilesCallback(this._filesToLoad);
  77477. }
  77478. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77479. var files_1 = new Array();
  77480. var folders = [];
  77481. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77482. for (var i = 0; i < this._filesToLoad.length; i++) {
  77483. var fileToLoad = this._filesToLoad[i];
  77484. var name_1 = fileToLoad.name.toLowerCase();
  77485. var entry = void 0;
  77486. fileToLoad.correctName = name_1;
  77487. if (items) {
  77488. var item = items[i];
  77489. if (item.getAsEntry) {
  77490. entry = item.getAsEntry();
  77491. }
  77492. else if (item.webkitGetAsEntry) {
  77493. entry = item.webkitGetAsEntry();
  77494. }
  77495. }
  77496. if (!entry) {
  77497. files_1.push(fileToLoad);
  77498. }
  77499. else {
  77500. if (entry.isDirectory) {
  77501. folders.push(entry);
  77502. }
  77503. else {
  77504. files_1.push(fileToLoad);
  77505. }
  77506. }
  77507. }
  77508. if (folders.length === 0) {
  77509. this._processFiles(files_1);
  77510. this._processReload();
  77511. }
  77512. else {
  77513. var remaining = { count: folders.length };
  77514. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77515. var folder = folders_1[_i];
  77516. this._traverseFolder(folder, files_1, remaining, function () {
  77517. _this._processFiles(files_1);
  77518. if (remaining.count === 0) {
  77519. _this._processReload();
  77520. }
  77521. });
  77522. }
  77523. }
  77524. }
  77525. };
  77526. FilesInput.prototype._processReload = function () {
  77527. if (this._onReloadCallback) {
  77528. this._onReloadCallback(this._sceneFileToLoad);
  77529. }
  77530. else {
  77531. this.reload();
  77532. }
  77533. };
  77534. /**
  77535. * Reload the current scene from the loaded files
  77536. */
  77537. FilesInput.prototype.reload = function () {
  77538. var _this = this;
  77539. // If a scene file has been provided
  77540. if (this._sceneFileToLoad) {
  77541. if (this._currentScene) {
  77542. if (BABYLON.Tools.errorsCount > 0) {
  77543. BABYLON.Tools.ClearLogCache();
  77544. }
  77545. this._engine.stopRenderLoop();
  77546. }
  77547. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77548. if (_this._progressCallback) {
  77549. _this._progressCallback(progress);
  77550. }
  77551. }).then(function (scene) {
  77552. if (_this._currentScene) {
  77553. _this._currentScene.dispose();
  77554. }
  77555. _this._currentScene = scene;
  77556. if (_this._sceneLoadedCallback) {
  77557. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77558. }
  77559. // Wait for textures and shaders to be ready
  77560. _this._currentScene.executeWhenReady(function () {
  77561. _this._engine.runRenderLoop(function () {
  77562. _this.renderFunction();
  77563. });
  77564. });
  77565. }).catch(function (error) {
  77566. if (_this._errorCallback) {
  77567. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77568. }
  77569. });
  77570. }
  77571. else {
  77572. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77573. }
  77574. };
  77575. /**
  77576. * List of files ready to be loaded
  77577. */
  77578. FilesInput.FilesToLoad = {};
  77579. return FilesInput;
  77580. }());
  77581. BABYLON.FilesInput = FilesInput;
  77582. })(BABYLON || (BABYLON = {}));
  77583. //# sourceMappingURL=babylon.filesInput.js.map
  77584. var BABYLON;
  77585. (function (BABYLON) {
  77586. /**
  77587. * Class used to store custom tags
  77588. */
  77589. var Tags = /** @class */ (function () {
  77590. function Tags() {
  77591. }
  77592. /**
  77593. * Adds support for tags on the given object
  77594. * @param obj defines the object to use
  77595. */
  77596. Tags.EnableFor = function (obj) {
  77597. obj._tags = obj._tags || {};
  77598. obj.hasTags = function () {
  77599. return Tags.HasTags(obj);
  77600. };
  77601. obj.addTags = function (tagsString) {
  77602. return Tags.AddTagsTo(obj, tagsString);
  77603. };
  77604. obj.removeTags = function (tagsString) {
  77605. return Tags.RemoveTagsFrom(obj, tagsString);
  77606. };
  77607. obj.matchesTagsQuery = function (tagsQuery) {
  77608. return Tags.MatchesQuery(obj, tagsQuery);
  77609. };
  77610. };
  77611. /**
  77612. * Removes tags support
  77613. * @param obj defines the object to use
  77614. */
  77615. Tags.DisableFor = function (obj) {
  77616. delete obj._tags;
  77617. delete obj.hasTags;
  77618. delete obj.addTags;
  77619. delete obj.removeTags;
  77620. delete obj.matchesTagsQuery;
  77621. };
  77622. /**
  77623. * Gets a boolean indicating if the given object has tags
  77624. * @param obj defines the object to use
  77625. * @returns a boolean
  77626. */
  77627. Tags.HasTags = function (obj) {
  77628. if (!obj._tags) {
  77629. return false;
  77630. }
  77631. return !BABYLON.Tools.IsEmpty(obj._tags);
  77632. };
  77633. /**
  77634. * Gets the tags available on a given object
  77635. * @param obj defines the object to use
  77636. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77637. * @returns the tags
  77638. */
  77639. Tags.GetTags = function (obj, asString) {
  77640. if (asString === void 0) { asString = true; }
  77641. if (!obj._tags) {
  77642. return null;
  77643. }
  77644. if (asString) {
  77645. var tagsArray = [];
  77646. for (var tag in obj._tags) {
  77647. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77648. tagsArray.push(tag);
  77649. }
  77650. }
  77651. return tagsArray.join(" ");
  77652. }
  77653. else {
  77654. return obj._tags;
  77655. }
  77656. };
  77657. /**
  77658. * Adds tags to an object
  77659. * @param obj defines the object to use
  77660. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77661. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77662. */
  77663. Tags.AddTagsTo = function (obj, tagsString) {
  77664. if (!tagsString) {
  77665. return;
  77666. }
  77667. if (typeof tagsString !== "string") {
  77668. return;
  77669. }
  77670. var tags = tagsString.split(" ");
  77671. tags.forEach(function (tag, index, array) {
  77672. Tags._AddTagTo(obj, tag);
  77673. });
  77674. };
  77675. /**
  77676. * @hidden
  77677. */
  77678. Tags._AddTagTo = function (obj, tag) {
  77679. tag = tag.trim();
  77680. if (tag === "" || tag === "true" || tag === "false") {
  77681. return;
  77682. }
  77683. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77684. return;
  77685. }
  77686. Tags.EnableFor(obj);
  77687. obj._tags[tag] = true;
  77688. };
  77689. /**
  77690. * Removes specific tags from a specific object
  77691. * @param obj defines the object to use
  77692. * @param tagsString defines the tags to remove
  77693. */
  77694. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77695. if (!Tags.HasTags(obj)) {
  77696. return;
  77697. }
  77698. var tags = tagsString.split(" ");
  77699. for (var t in tags) {
  77700. Tags._RemoveTagFrom(obj, tags[t]);
  77701. }
  77702. };
  77703. /**
  77704. * @hidden
  77705. */
  77706. Tags._RemoveTagFrom = function (obj, tag) {
  77707. delete obj._tags[tag];
  77708. };
  77709. /**
  77710. * Defines if tags hosted on an object match a given query
  77711. * @param obj defines the object to use
  77712. * @param tagsQuery defines the tag query
  77713. * @returns a boolean
  77714. */
  77715. Tags.MatchesQuery = function (obj, tagsQuery) {
  77716. if (tagsQuery === undefined) {
  77717. return true;
  77718. }
  77719. if (tagsQuery === "") {
  77720. return Tags.HasTags(obj);
  77721. }
  77722. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  77723. };
  77724. return Tags;
  77725. }());
  77726. BABYLON.Tags = Tags;
  77727. })(BABYLON || (BABYLON = {}));
  77728. //# sourceMappingURL=babylon.tags.js.map
  77729. var BABYLON;
  77730. (function (BABYLON) {
  77731. /**
  77732. * Class used to evalaute queries containing `and` and `or` operators
  77733. */
  77734. var AndOrNotEvaluator = /** @class */ (function () {
  77735. function AndOrNotEvaluator() {
  77736. }
  77737. /**
  77738. * Evaluate a query
  77739. * @param query defines the query to evaluate
  77740. * @param evaluateCallback defines the callback used to filter result
  77741. * @returns true if the query matches
  77742. */
  77743. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  77744. if (!query.match(/\([^\(\)]*\)/g)) {
  77745. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  77746. }
  77747. else {
  77748. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  77749. // remove parenthesis
  77750. r = r.slice(1, r.length - 1);
  77751. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  77752. });
  77753. }
  77754. if (query === "true") {
  77755. return true;
  77756. }
  77757. if (query === "false") {
  77758. return false;
  77759. }
  77760. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  77761. };
  77762. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  77763. evaluateCallback = evaluateCallback || (function (r) {
  77764. return r === "true" ? true : false;
  77765. });
  77766. var result;
  77767. var or = parenthesisContent.split("||");
  77768. for (var i in or) {
  77769. if (or.hasOwnProperty(i)) {
  77770. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  77771. var and = ori.split("&&");
  77772. if (and.length > 1) {
  77773. for (var j = 0; j < and.length; ++j) {
  77774. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  77775. if (andj !== "true" && andj !== "false") {
  77776. if (andj[0] === "!") {
  77777. result = !evaluateCallback(andj.substring(1));
  77778. }
  77779. else {
  77780. result = evaluateCallback(andj);
  77781. }
  77782. }
  77783. else {
  77784. result = andj === "true" ? true : false;
  77785. }
  77786. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  77787. ori = "false";
  77788. break;
  77789. }
  77790. }
  77791. }
  77792. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  77793. result = true;
  77794. break;
  77795. }
  77796. // result equals false (or undefined)
  77797. if (ori !== "true" && ori !== "false") {
  77798. if (ori[0] === "!") {
  77799. result = !evaluateCallback(ori.substring(1));
  77800. }
  77801. else {
  77802. result = evaluateCallback(ori);
  77803. }
  77804. }
  77805. else {
  77806. result = ori === "true" ? true : false;
  77807. }
  77808. }
  77809. }
  77810. // the whole parenthesis scope is replaced by 'true' or 'false'
  77811. return result ? "true" : "false";
  77812. };
  77813. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  77814. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  77815. // remove whitespaces
  77816. r = r.replace(/[\s]/g, function () { return ""; });
  77817. return r.length % 2 ? "!" : "";
  77818. });
  77819. booleanString = booleanString.trim();
  77820. if (booleanString === "!true") {
  77821. booleanString = "false";
  77822. }
  77823. else if (booleanString === "!false") {
  77824. booleanString = "true";
  77825. }
  77826. return booleanString;
  77827. };
  77828. return AndOrNotEvaluator;
  77829. }());
  77830. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  77831. })(BABYLON || (BABYLON = {}));
  77832. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  77833. var BABYLON;
  77834. (function (BABYLON) {
  77835. /**
  77836. * Class used to enable access to IndexedDB
  77837. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  77838. */
  77839. var Database = /** @class */ (function () {
  77840. /**
  77841. * Creates a new Database
  77842. * @param urlToScene defines the url to load the scene
  77843. * @param callbackManifestChecked defines the callback to use when manifest is checked
  77844. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  77845. */
  77846. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  77847. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  77848. var _this = this;
  77849. // Handling various flavors of prefixed version of IndexedDB
  77850. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  77851. this.callbackManifestChecked = callbackManifestChecked;
  77852. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  77853. this.db = null;
  77854. this._enableSceneOffline = false;
  77855. this._enableTexturesOffline = false;
  77856. this.manifestVersionFound = 0;
  77857. this.mustUpdateRessources = false;
  77858. this.hasReachedQuota = false;
  77859. if (!Database.IDBStorageEnabled) {
  77860. this.callbackManifestChecked(true);
  77861. }
  77862. else {
  77863. if (disableManifestCheck) {
  77864. this._enableSceneOffline = true;
  77865. this._enableTexturesOffline = true;
  77866. this.manifestVersionFound = 1;
  77867. BABYLON.Tools.SetImmediate(function () {
  77868. _this.callbackManifestChecked(true);
  77869. });
  77870. }
  77871. else {
  77872. this._checkManifestFile();
  77873. }
  77874. }
  77875. }
  77876. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  77877. /**
  77878. * Gets a boolean indicating if scene must be saved in the database
  77879. */
  77880. get: function () {
  77881. return this._enableSceneOffline;
  77882. },
  77883. enumerable: true,
  77884. configurable: true
  77885. });
  77886. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  77887. /**
  77888. * Gets a boolean indicating if textures must be saved in the database
  77889. */
  77890. get: function () {
  77891. return this._enableTexturesOffline;
  77892. },
  77893. enumerable: true,
  77894. configurable: true
  77895. });
  77896. Database.prototype._checkManifestFile = function () {
  77897. var _this = this;
  77898. var noManifestFile = function () {
  77899. _this._enableSceneOffline = false;
  77900. _this._enableTexturesOffline = false;
  77901. _this.callbackManifestChecked(false);
  77902. };
  77903. var timeStampUsed = false;
  77904. var manifestURL = this.currentSceneUrl + ".manifest";
  77905. var xhr = new XMLHttpRequest();
  77906. if (navigator.onLine) {
  77907. // Adding a timestamp to by-pass browsers' cache
  77908. timeStampUsed = true;
  77909. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  77910. }
  77911. xhr.open("GET", manifestURL, true);
  77912. xhr.addEventListener("load", function () {
  77913. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77914. try {
  77915. var manifestFile = JSON.parse(xhr.response);
  77916. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77917. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77918. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77919. _this.manifestVersionFound = manifestFile.version;
  77920. }
  77921. if (_this.callbackManifestChecked) {
  77922. _this.callbackManifestChecked(true);
  77923. }
  77924. }
  77925. catch (ex) {
  77926. noManifestFile();
  77927. }
  77928. }
  77929. else {
  77930. noManifestFile();
  77931. }
  77932. }, false);
  77933. xhr.addEventListener("error", function (event) {
  77934. if (timeStampUsed) {
  77935. timeStampUsed = false;
  77936. // Let's retry without the timeStamp
  77937. // It could fail when coupled with HTML5 Offline API
  77938. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77939. xhr.open("GET", retryManifestURL, true);
  77940. xhr.send();
  77941. }
  77942. else {
  77943. noManifestFile();
  77944. }
  77945. }, false);
  77946. try {
  77947. xhr.send();
  77948. }
  77949. catch (ex) {
  77950. BABYLON.Tools.Error("Error on XHR send request.");
  77951. this.callbackManifestChecked(false);
  77952. }
  77953. };
  77954. /**
  77955. * Open the database and make it available
  77956. * @param successCallback defines the callback to call on success
  77957. * @param errorCallback defines the callback to call on error
  77958. */
  77959. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77960. var _this = this;
  77961. var handleError = function () {
  77962. _this.isSupported = false;
  77963. if (errorCallback)
  77964. errorCallback();
  77965. };
  77966. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77967. // Your browser doesn't support IndexedDB
  77968. this.isSupported = false;
  77969. if (errorCallback)
  77970. errorCallback();
  77971. }
  77972. else {
  77973. // If the DB hasn't been opened or created yet
  77974. if (!this.db) {
  77975. this.hasReachedQuota = false;
  77976. this.isSupported = true;
  77977. var request = this.idbFactory.open("babylonjs", 1);
  77978. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  77979. request.onerror = function (event) {
  77980. handleError();
  77981. };
  77982. // executes when a version change transaction cannot complete due to other active transactions
  77983. request.onblocked = function (event) {
  77984. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  77985. handleError();
  77986. };
  77987. // DB has been opened successfully
  77988. request.onsuccess = function (event) {
  77989. _this.db = request.result;
  77990. successCallback();
  77991. };
  77992. // Initialization of the DB. Creating Scenes & Textures stores
  77993. request.onupgradeneeded = function (event) {
  77994. _this.db = (event.target).result;
  77995. if (_this.db) {
  77996. try {
  77997. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  77998. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  77999. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  78000. }
  78001. catch (ex) {
  78002. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  78003. handleError();
  78004. }
  78005. }
  78006. };
  78007. }
  78008. // DB has already been created and opened
  78009. else {
  78010. if (successCallback)
  78011. successCallback();
  78012. }
  78013. }
  78014. };
  78015. /**
  78016. * Loads an image from the database
  78017. * @param url defines the url to load from
  78018. * @param image defines the target DOM image
  78019. */
  78020. Database.prototype.loadImageFromDB = function (url, image) {
  78021. var _this = this;
  78022. var completeURL = Database._ReturnFullUrlLocation(url);
  78023. var saveAndLoadImage = function () {
  78024. if (!_this.hasReachedQuota && _this.db !== null) {
  78025. // the texture is not yet in the DB, let's try to save it
  78026. _this._saveImageIntoDBAsync(completeURL, image);
  78027. }
  78028. // If the texture is not in the DB and we've reached the DB quota limit
  78029. // let's load it directly from the web
  78030. else {
  78031. image.src = url;
  78032. }
  78033. };
  78034. if (!this.mustUpdateRessources) {
  78035. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78036. }
  78037. // First time we're download the images or update requested in the manifest file by a version change
  78038. else {
  78039. saveAndLoadImage();
  78040. }
  78041. };
  78042. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78043. if (this.isSupported && this.db !== null) {
  78044. var texture;
  78045. var transaction = this.db.transaction(["textures"]);
  78046. transaction.onabort = function (event) {
  78047. image.src = url;
  78048. };
  78049. transaction.oncomplete = function (event) {
  78050. var blobTextureURL;
  78051. if (texture) {
  78052. var URL = window.URL || window.webkitURL;
  78053. blobTextureURL = URL.createObjectURL(texture.data);
  78054. image.onerror = function () {
  78055. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78056. image.src = url;
  78057. };
  78058. image.src = blobTextureURL;
  78059. }
  78060. else {
  78061. notInDBCallback();
  78062. }
  78063. };
  78064. var getRequest = transaction.objectStore("textures").get(url);
  78065. getRequest.onsuccess = function (event) {
  78066. texture = (event.target).result;
  78067. };
  78068. getRequest.onerror = function (event) {
  78069. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78070. image.src = url;
  78071. };
  78072. }
  78073. else {
  78074. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78075. image.src = url;
  78076. }
  78077. };
  78078. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78079. var _this = this;
  78080. if (this.isSupported) {
  78081. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78082. var generateBlobUrl = function () {
  78083. var blobTextureURL;
  78084. if (blob) {
  78085. var URL = window.URL || window.webkitURL;
  78086. try {
  78087. blobTextureURL = URL.createObjectURL(blob);
  78088. }
  78089. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78090. catch (ex) {
  78091. blobTextureURL = URL.createObjectURL(blob);
  78092. }
  78093. }
  78094. if (blobTextureURL) {
  78095. image.src = blobTextureURL;
  78096. }
  78097. };
  78098. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78099. var xhr = new XMLHttpRequest(), blob;
  78100. xhr.open("GET", url, true);
  78101. xhr.responseType = "blob";
  78102. xhr.addEventListener("load", function () {
  78103. if (xhr.status === 200 && _this.db) {
  78104. // Blob as response (XHR2)
  78105. blob = xhr.response;
  78106. var transaction = _this.db.transaction(["textures"], "readwrite");
  78107. // the transaction could abort because of a QuotaExceededError error
  78108. transaction.onabort = function (event) {
  78109. try {
  78110. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78111. var srcElement = (event.srcElement || event.target);
  78112. var error = srcElement.error;
  78113. if (error && error.name === "QuotaExceededError") {
  78114. _this.hasReachedQuota = true;
  78115. }
  78116. }
  78117. catch (ex) { }
  78118. generateBlobUrl();
  78119. };
  78120. transaction.oncomplete = function (event) {
  78121. generateBlobUrl();
  78122. };
  78123. var newTexture = { textureUrl: url, data: blob };
  78124. try {
  78125. // Put the blob into the dabase
  78126. var addRequest = transaction.objectStore("textures").put(newTexture);
  78127. addRequest.onsuccess = function (event) {
  78128. };
  78129. addRequest.onerror = function (event) {
  78130. generateBlobUrl();
  78131. };
  78132. }
  78133. catch (ex) {
  78134. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78135. if (ex.code === 25) {
  78136. Database.IsUASupportingBlobStorage = false;
  78137. }
  78138. image.src = url;
  78139. }
  78140. }
  78141. else {
  78142. image.src = url;
  78143. }
  78144. }, false);
  78145. xhr.addEventListener("error", function (event) {
  78146. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78147. image.src = url;
  78148. }, false);
  78149. xhr.send();
  78150. }
  78151. else {
  78152. image.src = url;
  78153. }
  78154. }
  78155. else {
  78156. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78157. image.src = url;
  78158. }
  78159. };
  78160. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78161. var _this = this;
  78162. var updateVersion = function () {
  78163. // the version is not yet in the DB or we need to update it
  78164. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78165. };
  78166. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78167. };
  78168. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78169. var _this = this;
  78170. if (this.isSupported && this.db) {
  78171. var version;
  78172. try {
  78173. var transaction = this.db.transaction(["versions"]);
  78174. transaction.oncomplete = function (event) {
  78175. if (version) {
  78176. // If the version in the JSON file is different from the version in DB
  78177. if (_this.manifestVersionFound !== version.data) {
  78178. _this.mustUpdateRessources = true;
  78179. updateInDBCallback();
  78180. }
  78181. else {
  78182. callback(version.data);
  78183. }
  78184. }
  78185. // version was not found in DB
  78186. else {
  78187. _this.mustUpdateRessources = true;
  78188. updateInDBCallback();
  78189. }
  78190. };
  78191. transaction.onabort = function (event) {
  78192. callback(-1);
  78193. };
  78194. var getRequest = transaction.objectStore("versions").get(url);
  78195. getRequest.onsuccess = function (event) {
  78196. version = (event.target).result;
  78197. };
  78198. getRequest.onerror = function (event) {
  78199. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78200. callback(-1);
  78201. };
  78202. }
  78203. catch (ex) {
  78204. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78205. callback(-1);
  78206. }
  78207. }
  78208. else {
  78209. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78210. callback(-1);
  78211. }
  78212. };
  78213. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78214. var _this = this;
  78215. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78216. try {
  78217. // Open a transaction to the database
  78218. var transaction = this.db.transaction(["versions"], "readwrite");
  78219. // the transaction could abort because of a QuotaExceededError error
  78220. transaction.onabort = function (event) {
  78221. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78222. var error = event.srcElement['error'];
  78223. if (error && error.name === "QuotaExceededError") {
  78224. _this.hasReachedQuota = true;
  78225. }
  78226. }
  78227. catch (ex) { }
  78228. callback(-1);
  78229. };
  78230. transaction.oncomplete = function (event) {
  78231. callback(_this.manifestVersionFound);
  78232. };
  78233. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78234. // Put the scene into the database
  78235. var addRequest = transaction.objectStore("versions").put(newVersion);
  78236. addRequest.onsuccess = function (event) {
  78237. };
  78238. addRequest.onerror = function (event) {
  78239. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78240. };
  78241. }
  78242. catch (ex) {
  78243. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78244. callback(-1);
  78245. }
  78246. }
  78247. else {
  78248. callback(-1);
  78249. }
  78250. };
  78251. /**
  78252. * Loads a file from database
  78253. * @param url defines the URL to load from
  78254. * @param sceneLoaded defines a callback to call on success
  78255. * @param progressCallBack defines a callback to call when progress changed
  78256. * @param errorCallback defines a callback to call on error
  78257. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78258. */
  78259. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78260. var _this = this;
  78261. var completeUrl = Database._ReturnFullUrlLocation(url);
  78262. var saveAndLoadFile = function () {
  78263. // the scene is not yet in the DB, let's try to save it
  78264. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78265. };
  78266. this._checkVersionFromDB(completeUrl, function (version) {
  78267. if (version !== -1) {
  78268. if (!_this.mustUpdateRessources) {
  78269. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78270. }
  78271. else {
  78272. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78273. }
  78274. }
  78275. else {
  78276. if (errorCallback) {
  78277. errorCallback();
  78278. }
  78279. }
  78280. });
  78281. };
  78282. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78283. if (this.isSupported && this.db) {
  78284. var targetStore;
  78285. if (url.indexOf(".babylon") !== -1) {
  78286. targetStore = "scenes";
  78287. }
  78288. else {
  78289. targetStore = "textures";
  78290. }
  78291. var file;
  78292. var transaction = this.db.transaction([targetStore]);
  78293. transaction.oncomplete = function (event) {
  78294. if (file) {
  78295. callback(file.data);
  78296. }
  78297. // file was not found in DB
  78298. else {
  78299. notInDBCallback();
  78300. }
  78301. };
  78302. transaction.onabort = function (event) {
  78303. notInDBCallback();
  78304. };
  78305. var getRequest = transaction.objectStore(targetStore).get(url);
  78306. getRequest.onsuccess = function (event) {
  78307. file = (event.target).result;
  78308. };
  78309. getRequest.onerror = function (event) {
  78310. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78311. notInDBCallback();
  78312. };
  78313. }
  78314. else {
  78315. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78316. callback();
  78317. }
  78318. };
  78319. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78320. var _this = this;
  78321. if (this.isSupported) {
  78322. var targetStore;
  78323. if (url.indexOf(".babylon") !== -1) {
  78324. targetStore = "scenes";
  78325. }
  78326. else {
  78327. targetStore = "textures";
  78328. }
  78329. // Create XHR
  78330. var xhr = new XMLHttpRequest();
  78331. var fileData;
  78332. xhr.open("GET", url + "?" + Date.now(), true);
  78333. if (useArrayBuffer) {
  78334. xhr.responseType = "arraybuffer";
  78335. }
  78336. if (progressCallback) {
  78337. xhr.onprogress = progressCallback;
  78338. }
  78339. xhr.addEventListener("load", function () {
  78340. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78341. // Blob as response (XHR2)
  78342. //fileData = xhr.responseText;
  78343. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78344. if (!_this.hasReachedQuota && _this.db) {
  78345. // Open a transaction to the database
  78346. var transaction = _this.db.transaction([targetStore], "readwrite");
  78347. // the transaction could abort because of a QuotaExceededError error
  78348. transaction.onabort = function (event) {
  78349. try {
  78350. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78351. var error = event.srcElement['error'];
  78352. if (error && error.name === "QuotaExceededError") {
  78353. _this.hasReachedQuota = true;
  78354. }
  78355. }
  78356. catch (ex) { }
  78357. callback(fileData);
  78358. };
  78359. transaction.oncomplete = function (event) {
  78360. callback(fileData);
  78361. };
  78362. var newFile;
  78363. if (targetStore === "scenes") {
  78364. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78365. }
  78366. else {
  78367. newFile = { textureUrl: url, data: fileData };
  78368. }
  78369. try {
  78370. // Put the scene into the database
  78371. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78372. addRequest.onsuccess = function (event) {
  78373. };
  78374. addRequest.onerror = function (event) {
  78375. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78376. };
  78377. }
  78378. catch (ex) {
  78379. callback(fileData);
  78380. }
  78381. }
  78382. else {
  78383. callback(fileData);
  78384. }
  78385. }
  78386. else {
  78387. if (xhr.status >= 400 && errorCallback) {
  78388. errorCallback(xhr);
  78389. }
  78390. else {
  78391. callback();
  78392. }
  78393. }
  78394. }, false);
  78395. xhr.addEventListener("error", function (event) {
  78396. BABYLON.Tools.Error("error on XHR request.");
  78397. callback();
  78398. }, false);
  78399. xhr.send();
  78400. }
  78401. else {
  78402. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78403. callback();
  78404. }
  78405. };
  78406. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78407. Database.IsUASupportingBlobStorage = true;
  78408. /** Gets a boolean indicating if Database storate is enabled */
  78409. Database.IDBStorageEnabled = true;
  78410. Database._ParseURL = function (url) {
  78411. var a = document.createElement('a');
  78412. a.href = url;
  78413. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78414. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78415. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78416. return absLocation;
  78417. };
  78418. Database._ReturnFullUrlLocation = function (url) {
  78419. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78420. return (Database._ParseURL(window.location.href) + url);
  78421. }
  78422. else {
  78423. return url;
  78424. }
  78425. };
  78426. return Database;
  78427. }());
  78428. BABYLON.Database = Database;
  78429. })(BABYLON || (BABYLON = {}));
  78430. //# sourceMappingURL=babylon.database.js.map
  78431. var BABYLON;
  78432. (function (BABYLON) {
  78433. /**
  78434. * This represents all the required information to add a fresnel effect on a material:
  78435. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78436. */
  78437. var FresnelParameters = /** @class */ (function () {
  78438. function FresnelParameters() {
  78439. this._isEnabled = true;
  78440. /**
  78441. * Define the color used on edges (grazing angle)
  78442. */
  78443. this.leftColor = BABYLON.Color3.White();
  78444. /**
  78445. * Define the color used on center
  78446. */
  78447. this.rightColor = BABYLON.Color3.Black();
  78448. /**
  78449. * Define bias applied to computed fresnel term
  78450. */
  78451. this.bias = 0;
  78452. /**
  78453. * Defined the power exponent applied to fresnel term
  78454. */
  78455. this.power = 1;
  78456. }
  78457. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78458. /**
  78459. * Define if the fresnel effect is enable or not.
  78460. */
  78461. get: function () {
  78462. return this._isEnabled;
  78463. },
  78464. set: function (value) {
  78465. if (this._isEnabled === value) {
  78466. return;
  78467. }
  78468. this._isEnabled = value;
  78469. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78470. },
  78471. enumerable: true,
  78472. configurable: true
  78473. });
  78474. /**
  78475. * Clones the current fresnel and its valuues
  78476. * @returns a clone fresnel configuration
  78477. */
  78478. FresnelParameters.prototype.clone = function () {
  78479. var newFresnelParameters = new FresnelParameters();
  78480. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78481. return newFresnelParameters;
  78482. };
  78483. /**
  78484. * Serializes the current fresnel parameters to a JSON representation.
  78485. * @return the JSON serialization
  78486. */
  78487. FresnelParameters.prototype.serialize = function () {
  78488. var serializationObject = {};
  78489. serializationObject.isEnabled = this.isEnabled;
  78490. serializationObject.leftColor = this.leftColor.asArray();
  78491. serializationObject.rightColor = this.rightColor.asArray();
  78492. serializationObject.bias = this.bias;
  78493. serializationObject.power = this.power;
  78494. return serializationObject;
  78495. };
  78496. /**
  78497. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78498. * @param parsedFresnelParameters Define the JSON representation
  78499. * @returns the parsed parameters
  78500. */
  78501. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78502. var fresnelParameters = new FresnelParameters();
  78503. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78504. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78505. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78506. fresnelParameters.bias = parsedFresnelParameters.bias;
  78507. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78508. return fresnelParameters;
  78509. };
  78510. return FresnelParameters;
  78511. }());
  78512. BABYLON.FresnelParameters = FresnelParameters;
  78513. })(BABYLON || (BABYLON = {}));
  78514. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78515. var BABYLON;
  78516. (function (BABYLON) {
  78517. /**
  78518. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78519. * separate meshes. This can be use to improve performances.
  78520. * @see http://doc.babylonjs.com/how_to/multi_materials
  78521. */
  78522. var MultiMaterial = /** @class */ (function (_super) {
  78523. __extends(MultiMaterial, _super);
  78524. /**
  78525. * Instantiates a new Multi Material
  78526. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78527. * separate meshes. This can be use to improve performances.
  78528. * @see http://doc.babylonjs.com/how_to/multi_materials
  78529. * @param name Define the name in the scene
  78530. * @param scene Define the scene the material belongs to
  78531. */
  78532. function MultiMaterial(name, scene) {
  78533. var _this = _super.call(this, name, scene, true) || this;
  78534. scene.multiMaterials.push(_this);
  78535. _this.subMaterials = new Array();
  78536. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78537. return _this;
  78538. }
  78539. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78540. /**
  78541. * Gets or Sets the list of Materials used within the multi material.
  78542. * They need to be ordered according to the submeshes order in the associated mesh
  78543. */
  78544. get: function () {
  78545. return this._subMaterials;
  78546. },
  78547. set: function (value) {
  78548. this._subMaterials = value;
  78549. this._hookArray(value);
  78550. },
  78551. enumerable: true,
  78552. configurable: true
  78553. });
  78554. MultiMaterial.prototype._hookArray = function (array) {
  78555. var _this = this;
  78556. var oldPush = array.push;
  78557. array.push = function () {
  78558. var items = [];
  78559. for (var _i = 0; _i < arguments.length; _i++) {
  78560. items[_i] = arguments[_i];
  78561. }
  78562. var result = oldPush.apply(array, items);
  78563. _this._markAllSubMeshesAsTexturesDirty();
  78564. return result;
  78565. };
  78566. var oldSplice = array.splice;
  78567. array.splice = function (index, deleteCount) {
  78568. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78569. _this._markAllSubMeshesAsTexturesDirty();
  78570. return deleted;
  78571. };
  78572. };
  78573. /**
  78574. * Get one of the submaterial by its index in the submaterials array
  78575. * @param index The index to look the sub material at
  78576. * @returns The Material if the index has been defined
  78577. */
  78578. MultiMaterial.prototype.getSubMaterial = function (index) {
  78579. if (index < 0 || index >= this.subMaterials.length) {
  78580. return this.getScene().defaultMaterial;
  78581. }
  78582. return this.subMaterials[index];
  78583. };
  78584. /**
  78585. * Get the list of active textures for the whole sub materials list.
  78586. * @returns All the textures that will be used during the rendering
  78587. */
  78588. MultiMaterial.prototype.getActiveTextures = function () {
  78589. var _a;
  78590. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78591. if (subMaterial) {
  78592. return subMaterial.getActiveTextures();
  78593. }
  78594. else {
  78595. return [];
  78596. }
  78597. }));
  78598. };
  78599. /**
  78600. * Gets the current class name of the material e.g. "MultiMaterial"
  78601. * Mainly use in serialization.
  78602. * @returns the class name
  78603. */
  78604. MultiMaterial.prototype.getClassName = function () {
  78605. return "MultiMaterial";
  78606. };
  78607. /**
  78608. * Checks if the material is ready to render the requested sub mesh
  78609. * @param mesh Define the mesh the submesh belongs to
  78610. * @param subMesh Define the sub mesh to look readyness for
  78611. * @param useInstances Define whether or not the material is used with instances
  78612. * @returns true if ready, otherwise false
  78613. */
  78614. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78615. for (var index = 0; index < this.subMaterials.length; index++) {
  78616. var subMaterial = this.subMaterials[index];
  78617. if (subMaterial) {
  78618. if (subMaterial.storeEffectOnSubMeshes) {
  78619. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78620. return false;
  78621. }
  78622. continue;
  78623. }
  78624. if (!subMaterial.isReady(mesh)) {
  78625. return false;
  78626. }
  78627. }
  78628. }
  78629. return true;
  78630. };
  78631. /**
  78632. * Clones the current material and its related sub materials
  78633. * @param name Define the name of the newly cloned material
  78634. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78635. * @returns the cloned material
  78636. */
  78637. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78638. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78639. for (var index = 0; index < this.subMaterials.length; index++) {
  78640. var subMaterial = null;
  78641. var current = this.subMaterials[index];
  78642. if (cloneChildren && current) {
  78643. subMaterial = current.clone(name + "-" + current.name);
  78644. }
  78645. else {
  78646. subMaterial = this.subMaterials[index];
  78647. }
  78648. newMultiMaterial.subMaterials.push(subMaterial);
  78649. }
  78650. return newMultiMaterial;
  78651. };
  78652. /**
  78653. * Serializes the materials into a JSON representation.
  78654. * @returns the JSON representation
  78655. */
  78656. MultiMaterial.prototype.serialize = function () {
  78657. var serializationObject = {};
  78658. serializationObject.name = this.name;
  78659. serializationObject.id = this.id;
  78660. if (BABYLON.Tags) {
  78661. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78662. }
  78663. serializationObject.materials = [];
  78664. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78665. var subMat = this.subMaterials[matIndex];
  78666. if (subMat) {
  78667. serializationObject.materials.push(subMat.id);
  78668. }
  78669. else {
  78670. serializationObject.materials.push(null);
  78671. }
  78672. }
  78673. return serializationObject;
  78674. };
  78675. /**
  78676. * Dispose the material and release its associated resources
  78677. * @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)
  78678. * @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)
  78679. */
  78680. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78681. var scene = this.getScene();
  78682. if (!scene) {
  78683. return;
  78684. }
  78685. var index = scene.multiMaterials.indexOf(this);
  78686. if (index >= 0) {
  78687. scene.multiMaterials.splice(index, 1);
  78688. }
  78689. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78690. };
  78691. return MultiMaterial;
  78692. }(BABYLON.Material));
  78693. BABYLON.MultiMaterial = MultiMaterial;
  78694. })(BABYLON || (BABYLON = {}));
  78695. //# sourceMappingURL=babylon.multiMaterial.js.map
  78696. var BABYLON;
  78697. (function (BABYLON) {
  78698. /**
  78699. * Manage the touch inputs to control the movement of a free camera.
  78700. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78701. */
  78702. var FreeCameraTouchInput = /** @class */ (function () {
  78703. function FreeCameraTouchInput() {
  78704. /**
  78705. * Defines the touch sensibility for rotation.
  78706. * The higher the faster.
  78707. */
  78708. this.touchAngularSensibility = 200000.0;
  78709. /**
  78710. * Defines the touch sensibility for move.
  78711. * The higher the faster.
  78712. */
  78713. this.touchMoveSensibility = 250.0;
  78714. this._offsetX = null;
  78715. this._offsetY = null;
  78716. this._pointerPressed = new Array();
  78717. }
  78718. /**
  78719. * Attach the input controls to a specific dom element to get the input from.
  78720. * @param element Defines the element the controls should be listened from
  78721. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78722. */
  78723. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  78724. var _this = this;
  78725. var previousPosition = null;
  78726. if (this._pointerInput === undefined) {
  78727. this._onLostFocus = function (evt) {
  78728. _this._offsetX = null;
  78729. _this._offsetY = null;
  78730. };
  78731. this._pointerInput = function (p, s) {
  78732. var evt = p.event;
  78733. if (evt.pointerType === "mouse") {
  78734. return;
  78735. }
  78736. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78737. if (!noPreventDefault) {
  78738. evt.preventDefault();
  78739. }
  78740. _this._pointerPressed.push(evt.pointerId);
  78741. if (_this._pointerPressed.length !== 1) {
  78742. return;
  78743. }
  78744. previousPosition = {
  78745. x: evt.clientX,
  78746. y: evt.clientY
  78747. };
  78748. }
  78749. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  78750. if (!noPreventDefault) {
  78751. evt.preventDefault();
  78752. }
  78753. var index = _this._pointerPressed.indexOf(evt.pointerId);
  78754. if (index === -1) {
  78755. return;
  78756. }
  78757. _this._pointerPressed.splice(index, 1);
  78758. if (index != 0) {
  78759. return;
  78760. }
  78761. previousPosition = null;
  78762. _this._offsetX = null;
  78763. _this._offsetY = null;
  78764. }
  78765. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  78766. if (!noPreventDefault) {
  78767. evt.preventDefault();
  78768. }
  78769. if (!previousPosition) {
  78770. return;
  78771. }
  78772. var index = _this._pointerPressed.indexOf(evt.pointerId);
  78773. if (index != 0) {
  78774. return;
  78775. }
  78776. _this._offsetX = evt.clientX - previousPosition.x;
  78777. _this._offsetY = -(evt.clientY - previousPosition.y);
  78778. }
  78779. };
  78780. }
  78781. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  78782. if (this._onLostFocus) {
  78783. element.addEventListener("blur", this._onLostFocus);
  78784. }
  78785. };
  78786. /**
  78787. * Detach the current controls from the specified dom element.
  78788. * @param element Defines the element to stop listening the inputs from
  78789. */
  78790. FreeCameraTouchInput.prototype.detachControl = function (element) {
  78791. if (this._pointerInput && element) {
  78792. if (this._observer) {
  78793. this.camera.getScene().onPointerObservable.remove(this._observer);
  78794. this._observer = null;
  78795. }
  78796. if (this._onLostFocus) {
  78797. element.removeEventListener("blur", this._onLostFocus);
  78798. this._onLostFocus = null;
  78799. }
  78800. this._pointerPressed = [];
  78801. this._offsetX = null;
  78802. this._offsetY = null;
  78803. }
  78804. };
  78805. /**
  78806. * Update the current camera state depending on the inputs that have been used this frame.
  78807. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78808. */
  78809. FreeCameraTouchInput.prototype.checkInputs = function () {
  78810. if (this._offsetX && this._offsetY) {
  78811. var camera = this.camera;
  78812. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  78813. if (this._pointerPressed.length > 1) {
  78814. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  78815. }
  78816. else {
  78817. var speed = camera._computeLocalCameraSpeed();
  78818. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  78819. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  78820. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  78821. }
  78822. }
  78823. };
  78824. /**
  78825. * Gets the class name of the current intput.
  78826. * @returns the class name
  78827. */
  78828. FreeCameraTouchInput.prototype.getClassName = function () {
  78829. return "FreeCameraTouchInput";
  78830. };
  78831. /**
  78832. * Get the friendly name associated with the input class.
  78833. * @returns the input friendly name
  78834. */
  78835. FreeCameraTouchInput.prototype.getSimpleName = function () {
  78836. return "touch";
  78837. };
  78838. __decorate([
  78839. BABYLON.serialize()
  78840. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  78841. __decorate([
  78842. BABYLON.serialize()
  78843. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  78844. return FreeCameraTouchInput;
  78845. }());
  78846. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  78847. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  78848. })(BABYLON || (BABYLON = {}));
  78849. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  78850. var BABYLON;
  78851. (function (BABYLON) {
  78852. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  78853. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  78854. });
  78855. /**
  78856. * This represents a FPS type of camera controlled by touch.
  78857. * This is like a universal camera minus the Gamepad controls.
  78858. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78859. */
  78860. var TouchCamera = /** @class */ (function (_super) {
  78861. __extends(TouchCamera, _super);
  78862. /**
  78863. * Instantiates a new touch camera.
  78864. * This represents a FPS type of camera controlled by touch.
  78865. * This is like a universal camera minus the Gamepad controls.
  78866. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78867. * @param name Define the name of the camera in the scene
  78868. * @param position Define the start position of the camera in the scene
  78869. * @param scene Define the scene the camera belongs to
  78870. */
  78871. function TouchCamera(name, position, scene) {
  78872. var _this = _super.call(this, name, position, scene) || this;
  78873. _this.inputs.addTouch();
  78874. _this._setupInputs();
  78875. return _this;
  78876. }
  78877. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  78878. /**
  78879. * Defines the touch sensibility for rotation.
  78880. * The higher the faster.
  78881. */
  78882. get: function () {
  78883. var touch = this.inputs.attached["touch"];
  78884. if (touch)
  78885. return touch.touchAngularSensibility;
  78886. return 0;
  78887. },
  78888. set: function (value) {
  78889. var touch = this.inputs.attached["touch"];
  78890. if (touch)
  78891. touch.touchAngularSensibility = value;
  78892. },
  78893. enumerable: true,
  78894. configurable: true
  78895. });
  78896. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  78897. /**
  78898. * Defines the touch sensibility for move.
  78899. * The higher the faster.
  78900. */
  78901. get: function () {
  78902. var touch = this.inputs.attached["touch"];
  78903. if (touch)
  78904. return touch.touchMoveSensibility;
  78905. return 0;
  78906. },
  78907. set: function (value) {
  78908. var touch = this.inputs.attached["touch"];
  78909. if (touch)
  78910. touch.touchMoveSensibility = value;
  78911. },
  78912. enumerable: true,
  78913. configurable: true
  78914. });
  78915. /**
  78916. * Gets the current object class name.
  78917. * @return the class name
  78918. */
  78919. TouchCamera.prototype.getClassName = function () {
  78920. return "TouchCamera";
  78921. };
  78922. /** @hidden */
  78923. TouchCamera.prototype._setupInputs = function () {
  78924. var mouse = this.inputs.attached["mouse"];
  78925. if (mouse) {
  78926. mouse.touchEnabled = false;
  78927. }
  78928. };
  78929. return TouchCamera;
  78930. }(BABYLON.FreeCamera));
  78931. BABYLON.TouchCamera = TouchCamera;
  78932. })(BABYLON || (BABYLON = {}));
  78933. //# sourceMappingURL=babylon.touchCamera.js.map
  78934. var BABYLON;
  78935. (function (BABYLON) {
  78936. /**
  78937. * 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.
  78938. * This is the base class of any Procedural texture and contains most of the shareable code.
  78939. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78940. */
  78941. var ProceduralTexture = /** @class */ (function (_super) {
  78942. __extends(ProceduralTexture, _super);
  78943. /**
  78944. * Instantiates a new procedural texture.
  78945. * 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.
  78946. * This is the base class of any Procedural texture and contains most of the shareable code.
  78947. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78948. * @param name Define the name of the texture
  78949. * @param size Define the size of the texture to create
  78950. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78951. * @param scene Define the scene the texture belongs to
  78952. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78953. * @param generateMipMaps Define if the texture should creates mip maps or not
  78954. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78955. */
  78956. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78957. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78958. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78959. if (isCube === void 0) { isCube = false; }
  78960. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78961. _this.isCube = isCube;
  78962. /**
  78963. * Define if the texture is enabled or not (disabled texture will not render)
  78964. */
  78965. _this.isEnabled = true;
  78966. /**
  78967. * Event raised when the texture is generated
  78968. */
  78969. _this.onGeneratedObservable = new BABYLON.Observable();
  78970. /** @hidden */
  78971. _this._textures = {};
  78972. _this._currentRefreshId = -1;
  78973. _this._refreshRate = 1;
  78974. _this._vertexBuffers = {};
  78975. _this._uniforms = new Array();
  78976. _this._samplers = new Array();
  78977. _this._floats = {};
  78978. _this._ints = {};
  78979. _this._floatsArrays = {};
  78980. _this._colors3 = {};
  78981. _this._colors4 = {};
  78982. _this._vectors2 = {};
  78983. _this._vectors3 = {};
  78984. _this._matrices = {};
  78985. _this._fallbackTextureUsed = false;
  78986. _this._cachedDefines = "";
  78987. _this._contentUpdateId = -1;
  78988. scene = _this.getScene();
  78989. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  78990. if (!component) {
  78991. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  78992. scene._addComponent(component);
  78993. }
  78994. scene.proceduralTextures.push(_this);
  78995. _this._engine = scene.getEngine();
  78996. _this.name = name;
  78997. _this.isRenderTarget = true;
  78998. _this._size = size;
  78999. _this._generateMipMaps = generateMipMaps;
  79000. _this.setFragment(fragment);
  79001. _this._fallbackTexture = fallbackTexture;
  79002. if (isCube) {
  79003. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  79004. _this.setFloat("face", 0);
  79005. }
  79006. else {
  79007. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  79008. }
  79009. // VBO
  79010. var vertices = [];
  79011. vertices.push(1, 1);
  79012. vertices.push(-1, 1);
  79013. vertices.push(-1, -1);
  79014. vertices.push(1, -1);
  79015. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79016. _this._createIndexBuffer();
  79017. return _this;
  79018. }
  79019. /**
  79020. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79021. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79022. */
  79023. ProceduralTexture.prototype.getContent = function () {
  79024. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79025. return this._contentData;
  79026. }
  79027. this._contentData = this.readPixels(0, 0, this._contentData);
  79028. this._contentUpdateId = this._currentRefreshId;
  79029. return this._contentData;
  79030. };
  79031. ProceduralTexture.prototype._createIndexBuffer = function () {
  79032. var engine = this._engine;
  79033. // Indices
  79034. var indices = [];
  79035. indices.push(0);
  79036. indices.push(1);
  79037. indices.push(2);
  79038. indices.push(0);
  79039. indices.push(2);
  79040. indices.push(3);
  79041. this._indexBuffer = engine.createIndexBuffer(indices);
  79042. };
  79043. /** @hidden */
  79044. ProceduralTexture.prototype._rebuild = function () {
  79045. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79046. if (vb) {
  79047. vb._rebuild();
  79048. }
  79049. this._createIndexBuffer();
  79050. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79051. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79052. }
  79053. };
  79054. /**
  79055. * Resets the texture in order to recreate its associated resources.
  79056. * This can be called in case of context loss
  79057. */
  79058. ProceduralTexture.prototype.reset = function () {
  79059. if (this._effect === undefined) {
  79060. return;
  79061. }
  79062. var engine = this._engine;
  79063. engine._releaseEffect(this._effect);
  79064. };
  79065. ProceduralTexture.prototype._getDefines = function () {
  79066. return "";
  79067. };
  79068. /**
  79069. * Is the texture ready to be used ? (rendered at least once)
  79070. * @returns true if ready, otherwise, false.
  79071. */
  79072. ProceduralTexture.prototype.isReady = function () {
  79073. var _this = this;
  79074. var engine = this._engine;
  79075. var shaders;
  79076. if (!this._fragment) {
  79077. return false;
  79078. }
  79079. if (this._fallbackTextureUsed) {
  79080. return true;
  79081. }
  79082. var defines = this._getDefines();
  79083. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79084. return true;
  79085. }
  79086. if (this._fragment.fragmentElement !== undefined) {
  79087. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79088. }
  79089. else {
  79090. shaders = { vertex: "procedural", fragment: this._fragment };
  79091. }
  79092. this._cachedDefines = defines;
  79093. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79094. _this.releaseInternalTexture();
  79095. if (_this._fallbackTexture) {
  79096. _this._texture = _this._fallbackTexture._texture;
  79097. if (_this._texture) {
  79098. _this._texture.incrementReferences();
  79099. }
  79100. }
  79101. _this._fallbackTextureUsed = true;
  79102. });
  79103. return this._effect.isReady();
  79104. };
  79105. /**
  79106. * Resets the refresh counter of the texture and start bak from scratch.
  79107. * Could be usefull to regenerate the texture if it is setup to render only once.
  79108. */
  79109. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79110. this._currentRefreshId = -1;
  79111. };
  79112. /**
  79113. * Set the fragment shader to use in order to render the texture.
  79114. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79115. */
  79116. ProceduralTexture.prototype.setFragment = function (fragment) {
  79117. this._fragment = fragment;
  79118. };
  79119. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79120. /**
  79121. * Define the refresh rate of the texture or the rendering frequency.
  79122. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79123. */
  79124. get: function () {
  79125. return this._refreshRate;
  79126. },
  79127. set: function (value) {
  79128. this._refreshRate = value;
  79129. this.resetRefreshCounter();
  79130. },
  79131. enumerable: true,
  79132. configurable: true
  79133. });
  79134. /** @hidden */
  79135. ProceduralTexture.prototype._shouldRender = function () {
  79136. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79137. if (this._texture) {
  79138. this._texture.isReady = false;
  79139. }
  79140. return false;
  79141. }
  79142. if (this._fallbackTextureUsed) {
  79143. return false;
  79144. }
  79145. if (this._currentRefreshId === -1) { // At least render once
  79146. this._currentRefreshId = 1;
  79147. return true;
  79148. }
  79149. if (this.refreshRate === this._currentRefreshId) {
  79150. this._currentRefreshId = 1;
  79151. return true;
  79152. }
  79153. this._currentRefreshId++;
  79154. return false;
  79155. };
  79156. /**
  79157. * Get the size the texture is rendering at.
  79158. * @returns the size (texture is always squared)
  79159. */
  79160. ProceduralTexture.prototype.getRenderSize = function () {
  79161. return this._size;
  79162. };
  79163. /**
  79164. * Resize the texture to new value.
  79165. * @param size Define the new size the texture should have
  79166. * @param generateMipMaps Define whether the new texture should create mip maps
  79167. */
  79168. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79169. if (this._fallbackTextureUsed) {
  79170. return;
  79171. }
  79172. this.releaseInternalTexture();
  79173. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79174. // Update properties
  79175. this._size = size;
  79176. this._generateMipMaps = generateMipMaps;
  79177. };
  79178. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79179. if (this._uniforms.indexOf(uniformName) === -1) {
  79180. this._uniforms.push(uniformName);
  79181. }
  79182. };
  79183. /**
  79184. * Set a texture in the shader program used to render.
  79185. * @param name Define the name of the uniform samplers as defined in the shader
  79186. * @param texture Define the texture to bind to this sampler
  79187. * @return the texture itself allowing "fluent" like uniform updates
  79188. */
  79189. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79190. if (this._samplers.indexOf(name) === -1) {
  79191. this._samplers.push(name);
  79192. }
  79193. this._textures[name] = texture;
  79194. return this;
  79195. };
  79196. /**
  79197. * Set a float in the shader.
  79198. * @param name Define the name of the uniform as defined in the shader
  79199. * @param value Define the value to give to the uniform
  79200. * @return the texture itself allowing "fluent" like uniform updates
  79201. */
  79202. ProceduralTexture.prototype.setFloat = function (name, value) {
  79203. this._checkUniform(name);
  79204. this._floats[name] = value;
  79205. return this;
  79206. };
  79207. /**
  79208. * Set a int in the shader.
  79209. * @param name Define the name of the uniform as defined in the shader
  79210. * @param value Define the value to give to the uniform
  79211. * @return the texture itself allowing "fluent" like uniform updates
  79212. */
  79213. ProceduralTexture.prototype.setInt = function (name, value) {
  79214. this._checkUniform(name);
  79215. this._ints[name] = value;
  79216. return this;
  79217. };
  79218. /**
  79219. * Set an array of floats in the shader.
  79220. * @param name Define the name of the uniform as defined in the shader
  79221. * @param value Define the value to give to the uniform
  79222. * @return the texture itself allowing "fluent" like uniform updates
  79223. */
  79224. ProceduralTexture.prototype.setFloats = function (name, value) {
  79225. this._checkUniform(name);
  79226. this._floatsArrays[name] = value;
  79227. return this;
  79228. };
  79229. /**
  79230. * Set a vec3 in the shader from a Color3.
  79231. * @param name Define the name of the uniform as defined in the shader
  79232. * @param value Define the value to give to the uniform
  79233. * @return the texture itself allowing "fluent" like uniform updates
  79234. */
  79235. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79236. this._checkUniform(name);
  79237. this._colors3[name] = value;
  79238. return this;
  79239. };
  79240. /**
  79241. * Set a vec4 in the shader from a Color4.
  79242. * @param name Define the name of the uniform as defined in the shader
  79243. * @param value Define the value to give to the uniform
  79244. * @return the texture itself allowing "fluent" like uniform updates
  79245. */
  79246. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79247. this._checkUniform(name);
  79248. this._colors4[name] = value;
  79249. return this;
  79250. };
  79251. /**
  79252. * Set a vec2 in the shader from a Vector2.
  79253. * @param name Define the name of the uniform as defined in the shader
  79254. * @param value Define the value to give to the uniform
  79255. * @return the texture itself allowing "fluent" like uniform updates
  79256. */
  79257. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79258. this._checkUniform(name);
  79259. this._vectors2[name] = value;
  79260. return this;
  79261. };
  79262. /**
  79263. * Set a vec3 in the shader from a Vector3.
  79264. * @param name Define the name of the uniform as defined in the shader
  79265. * @param value Define the value to give to the uniform
  79266. * @return the texture itself allowing "fluent" like uniform updates
  79267. */
  79268. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79269. this._checkUniform(name);
  79270. this._vectors3[name] = value;
  79271. return this;
  79272. };
  79273. /**
  79274. * Set a mat4 in the shader from a MAtrix.
  79275. * @param name Define the name of the uniform as defined in the shader
  79276. * @param value Define the value to give to the uniform
  79277. * @return the texture itself allowing "fluent" like uniform updates
  79278. */
  79279. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79280. this._checkUniform(name);
  79281. this._matrices[name] = value;
  79282. return this;
  79283. };
  79284. /**
  79285. * Render the texture to its associated render target.
  79286. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79287. */
  79288. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79289. var scene = this.getScene();
  79290. if (!scene) {
  79291. return;
  79292. }
  79293. var engine = this._engine;
  79294. // Render
  79295. engine.enableEffect(this._effect);
  79296. engine.setState(false);
  79297. // Texture
  79298. for (var name in this._textures) {
  79299. this._effect.setTexture(name, this._textures[name]);
  79300. }
  79301. // Float
  79302. for (name in this._ints) {
  79303. this._effect.setInt(name, this._ints[name]);
  79304. }
  79305. // Float
  79306. for (name in this._floats) {
  79307. this._effect.setFloat(name, this._floats[name]);
  79308. }
  79309. // Floats
  79310. for (name in this._floatsArrays) {
  79311. this._effect.setArray(name, this._floatsArrays[name]);
  79312. }
  79313. // Color3
  79314. for (name in this._colors3) {
  79315. this._effect.setColor3(name, this._colors3[name]);
  79316. }
  79317. // Color4
  79318. for (name in this._colors4) {
  79319. var color = this._colors4[name];
  79320. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79321. }
  79322. // Vector2
  79323. for (name in this._vectors2) {
  79324. this._effect.setVector2(name, this._vectors2[name]);
  79325. }
  79326. // Vector3
  79327. for (name in this._vectors3) {
  79328. this._effect.setVector3(name, this._vectors3[name]);
  79329. }
  79330. // Matrix
  79331. for (name in this._matrices) {
  79332. this._effect.setMatrix(name, this._matrices[name]);
  79333. }
  79334. if (!this._texture) {
  79335. return;
  79336. }
  79337. if (this.isCube) {
  79338. for (var face = 0; face < 6; face++) {
  79339. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79340. // VBOs
  79341. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79342. this._effect.setFloat("face", face);
  79343. // Clear
  79344. engine.clear(scene.clearColor, true, true, true);
  79345. // Draw order
  79346. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79347. // Mipmaps
  79348. if (face === 5) {
  79349. engine.generateMipMapsForCubemap(this._texture);
  79350. }
  79351. }
  79352. }
  79353. else {
  79354. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79355. // VBOs
  79356. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79357. // Clear
  79358. engine.clear(scene.clearColor, true, true, true);
  79359. // Draw order
  79360. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79361. }
  79362. // Unbind
  79363. engine.unBindFramebuffer(this._texture, this.isCube);
  79364. if (this.onGenerated) {
  79365. this.onGenerated();
  79366. }
  79367. this.onGeneratedObservable.notifyObservers(this);
  79368. };
  79369. /**
  79370. * Clone the texture.
  79371. * @returns the cloned texture
  79372. */
  79373. ProceduralTexture.prototype.clone = function () {
  79374. var textureSize = this.getSize();
  79375. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79376. // Base texture
  79377. newTexture.hasAlpha = this.hasAlpha;
  79378. newTexture.level = this.level;
  79379. // RenderTarget Texture
  79380. newTexture.coordinatesMode = this.coordinatesMode;
  79381. return newTexture;
  79382. };
  79383. /**
  79384. * Dispose the texture and release its asoociated resources.
  79385. */
  79386. ProceduralTexture.prototype.dispose = function () {
  79387. var scene = this.getScene();
  79388. if (!scene) {
  79389. return;
  79390. }
  79391. var index = scene.proceduralTextures.indexOf(this);
  79392. if (index >= 0) {
  79393. scene.proceduralTextures.splice(index, 1);
  79394. }
  79395. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79396. if (vertexBuffer) {
  79397. vertexBuffer.dispose();
  79398. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79399. }
  79400. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79401. this._indexBuffer = null;
  79402. }
  79403. _super.prototype.dispose.call(this);
  79404. };
  79405. __decorate([
  79406. BABYLON.serialize()
  79407. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79408. __decorate([
  79409. BABYLON.serialize()
  79410. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79411. __decorate([
  79412. BABYLON.serialize()
  79413. ], ProceduralTexture.prototype, "_size", void 0);
  79414. __decorate([
  79415. BABYLON.serialize()
  79416. ], ProceduralTexture.prototype, "refreshRate", null);
  79417. return ProceduralTexture;
  79418. }(BABYLON.Texture));
  79419. BABYLON.ProceduralTexture = ProceduralTexture;
  79420. })(BABYLON || (BABYLON = {}));
  79421. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79422. var BABYLON;
  79423. (function (BABYLON) {
  79424. /**
  79425. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79426. * in a given scene.
  79427. */
  79428. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79429. /**
  79430. * Creates a new instance of the component for the given scene
  79431. * @param scene Defines the scene to register the component in
  79432. */
  79433. function ProceduralTextureSceneComponent(scene) {
  79434. /**
  79435. * The component name helpfull to identify the component in the list of scene components.
  79436. */
  79437. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79438. this.scene = scene;
  79439. this.scene.proceduralTextures = new Array();
  79440. scene.layers = new Array();
  79441. }
  79442. /**
  79443. * Registers the component in a given scene
  79444. */
  79445. ProceduralTextureSceneComponent.prototype.register = function () {
  79446. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79447. };
  79448. /**
  79449. * Rebuilds the elements related to this component in case of
  79450. * context lost for instance.
  79451. */
  79452. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79453. // Nothing to do here.
  79454. };
  79455. /**
  79456. * Disposes the component and the associated ressources.
  79457. */
  79458. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79459. // Nothing to do here.
  79460. };
  79461. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79462. if (this.scene.proceduralTexturesEnabled) {
  79463. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79464. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79465. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79466. if (proceduralTexture._shouldRender()) {
  79467. proceduralTexture.render();
  79468. }
  79469. }
  79470. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79471. }
  79472. };
  79473. return ProceduralTextureSceneComponent;
  79474. }());
  79475. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79476. })(BABYLON || (BABYLON = {}));
  79477. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79478. var BABYLON;
  79479. (function (BABYLON) {
  79480. /**
  79481. * 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.
  79482. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79483. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79484. */
  79485. var CustomProceduralTexture = /** @class */ (function (_super) {
  79486. __extends(CustomProceduralTexture, _super);
  79487. /**
  79488. * Instantiates a new Custom Procedural Texture.
  79489. * 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.
  79490. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79491. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79492. * @param name Define the name of the texture
  79493. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79494. * @param size Define the size of the texture to create
  79495. * @param scene Define the scene the texture belongs to
  79496. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79497. * @param generateMipMaps Define if the texture should creates mip maps or not
  79498. */
  79499. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79500. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79501. _this._animate = true;
  79502. _this._time = 0;
  79503. _this._texturePath = texturePath;
  79504. //Try to load json
  79505. _this._loadJson(texturePath);
  79506. _this.refreshRate = 1;
  79507. return _this;
  79508. }
  79509. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79510. var _this = this;
  79511. var noConfigFile = function () {
  79512. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79513. try {
  79514. _this.setFragment(_this._texturePath);
  79515. }
  79516. catch (ex) {
  79517. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79518. }
  79519. };
  79520. var configFileUrl = jsonUrl + "/config.json";
  79521. var xhr = new XMLHttpRequest();
  79522. xhr.open("GET", configFileUrl, true);
  79523. xhr.addEventListener("load", function () {
  79524. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79525. try {
  79526. _this._config = JSON.parse(xhr.response);
  79527. _this.updateShaderUniforms();
  79528. _this.updateTextures();
  79529. _this.setFragment(_this._texturePath + "/custom");
  79530. _this._animate = _this._config.animate;
  79531. _this.refreshRate = _this._config.refreshrate;
  79532. }
  79533. catch (ex) {
  79534. noConfigFile();
  79535. }
  79536. }
  79537. else {
  79538. noConfigFile();
  79539. }
  79540. }, false);
  79541. xhr.addEventListener("error", function () {
  79542. noConfigFile();
  79543. }, false);
  79544. try {
  79545. xhr.send();
  79546. }
  79547. catch (ex) {
  79548. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79549. }
  79550. };
  79551. /**
  79552. * Is the texture ready to be used ? (rendered at least once)
  79553. * @returns true if ready, otherwise, false.
  79554. */
  79555. CustomProceduralTexture.prototype.isReady = function () {
  79556. if (!_super.prototype.isReady.call(this)) {
  79557. return false;
  79558. }
  79559. for (var name in this._textures) {
  79560. var texture = this._textures[name];
  79561. if (!texture.isReady()) {
  79562. return false;
  79563. }
  79564. }
  79565. return true;
  79566. };
  79567. /**
  79568. * Render the texture to its associated render target.
  79569. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79570. */
  79571. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79572. var scene = this.getScene();
  79573. if (this._animate && scene) {
  79574. this._time += scene.getAnimationRatio() * 0.03;
  79575. this.updateShaderUniforms();
  79576. }
  79577. _super.prototype.render.call(this, useCameraPostProcess);
  79578. };
  79579. /**
  79580. * Update the list of dependant textures samplers in the shader.
  79581. */
  79582. CustomProceduralTexture.prototype.updateTextures = function () {
  79583. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79584. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79585. }
  79586. };
  79587. /**
  79588. * Update the uniform values of the procedural texture in the shader.
  79589. */
  79590. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79591. if (this._config) {
  79592. for (var j = 0; j < this._config.uniforms.length; j++) {
  79593. var uniform = this._config.uniforms[j];
  79594. switch (uniform.type) {
  79595. case "float":
  79596. this.setFloat(uniform.name, uniform.value);
  79597. break;
  79598. case "color3":
  79599. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79600. break;
  79601. case "color4":
  79602. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79603. break;
  79604. case "vector2":
  79605. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79606. break;
  79607. case "vector3":
  79608. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79609. break;
  79610. }
  79611. }
  79612. }
  79613. this.setFloat("time", this._time);
  79614. };
  79615. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79616. /**
  79617. * Define if the texture animates or not.
  79618. */
  79619. get: function () {
  79620. return this._animate;
  79621. },
  79622. set: function (value) {
  79623. this._animate = value;
  79624. },
  79625. enumerable: true,
  79626. configurable: true
  79627. });
  79628. return CustomProceduralTexture;
  79629. }(BABYLON.ProceduralTexture));
  79630. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79631. })(BABYLON || (BABYLON = {}));
  79632. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79633. var BABYLON;
  79634. (function (BABYLON) {
  79635. /**
  79636. * Manage the gamepad inputs to control a free camera.
  79637. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79638. */
  79639. var FreeCameraGamepadInput = /** @class */ (function () {
  79640. function FreeCameraGamepadInput() {
  79641. /**
  79642. * Defines the gamepad rotation sensiblity.
  79643. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79644. */
  79645. this.gamepadAngularSensibility = 200;
  79646. /**
  79647. * Defines the gamepad move sensiblity.
  79648. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79649. */
  79650. this.gamepadMoveSensibility = 40;
  79651. this._cameraTransform = BABYLON.Matrix.Identity();
  79652. this._deltaTransform = BABYLON.Vector3.Zero();
  79653. this._vector3 = BABYLON.Vector3.Zero();
  79654. this._vector2 = BABYLON.Vector2.Zero();
  79655. }
  79656. /**
  79657. * Attach the input controls to a specific dom element to get the input from.
  79658. * @param element Defines the element the controls should be listened from
  79659. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79660. */
  79661. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79662. var _this = this;
  79663. var manager = this.camera.getScene().gamepadManager;
  79664. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79665. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79666. // prioritize XBOX gamepads.
  79667. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79668. _this.gamepad = gamepad;
  79669. }
  79670. }
  79671. });
  79672. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79673. if (_this.gamepad === gamepad) {
  79674. _this.gamepad = null;
  79675. }
  79676. });
  79677. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79678. };
  79679. /**
  79680. * Detach the current controls from the specified dom element.
  79681. * @param element Defines the element to stop listening the inputs from
  79682. */
  79683. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79684. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79685. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79686. this.gamepad = null;
  79687. };
  79688. /**
  79689. * Update the current camera state depending on the inputs that have been used this frame.
  79690. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79691. */
  79692. FreeCameraGamepadInput.prototype.checkInputs = function () {
  79693. if (this.gamepad && this.gamepad.leftStick) {
  79694. var camera = this.camera;
  79695. var LSValues = this.gamepad.leftStick;
  79696. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  79697. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79698. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  79699. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  79700. var RSValues = this.gamepad.rightStick;
  79701. if (RSValues) {
  79702. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  79703. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  79704. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  79705. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  79706. }
  79707. else {
  79708. RSValues = { x: 0, y: 0 };
  79709. }
  79710. if (!camera.rotationQuaternion) {
  79711. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  79712. }
  79713. else {
  79714. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  79715. }
  79716. var speed = camera._computeLocalCameraSpeed() * 50.0;
  79717. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  79718. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  79719. camera.cameraDirection.addInPlace(this._deltaTransform);
  79720. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  79721. camera.cameraRotation.addInPlace(this._vector2);
  79722. }
  79723. };
  79724. /**
  79725. * Gets the class name of the current intput.
  79726. * @returns the class name
  79727. */
  79728. FreeCameraGamepadInput.prototype.getClassName = function () {
  79729. return "FreeCameraGamepadInput";
  79730. };
  79731. /**
  79732. * Get the friendly name associated with the input class.
  79733. * @returns the input friendly name
  79734. */
  79735. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  79736. return "gamepad";
  79737. };
  79738. __decorate([
  79739. BABYLON.serialize()
  79740. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  79741. __decorate([
  79742. BABYLON.serialize()
  79743. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79744. return FreeCameraGamepadInput;
  79745. }());
  79746. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  79747. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  79748. })(BABYLON || (BABYLON = {}));
  79749. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  79750. var BABYLON;
  79751. (function (BABYLON) {
  79752. /**
  79753. * Manage the gamepad inputs to control an arc rotate camera.
  79754. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79755. */
  79756. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  79757. function ArcRotateCameraGamepadInput() {
  79758. /**
  79759. * Defines the gamepad rotation sensiblity.
  79760. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79761. */
  79762. this.gamepadRotationSensibility = 80;
  79763. /**
  79764. * Defines the gamepad move sensiblity.
  79765. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79766. */
  79767. this.gamepadMoveSensibility = 40;
  79768. }
  79769. /**
  79770. * Attach the input controls to a specific dom element to get the input from.
  79771. * @param element Defines the element the controls should be listened from
  79772. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79773. */
  79774. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79775. var _this = this;
  79776. var manager = this.camera.getScene().gamepadManager;
  79777. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79778. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79779. // prioritize XBOX gamepads.
  79780. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79781. _this.gamepad = gamepad;
  79782. }
  79783. }
  79784. });
  79785. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79786. if (_this.gamepad === gamepad) {
  79787. _this.gamepad = null;
  79788. }
  79789. });
  79790. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79791. };
  79792. /**
  79793. * Detach the current controls from the specified dom element.
  79794. * @param element Defines the element to stop listening the inputs from
  79795. */
  79796. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  79797. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79798. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79799. this.gamepad = null;
  79800. };
  79801. /**
  79802. * Update the current camera state depending on the inputs that have been used this frame.
  79803. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79804. */
  79805. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  79806. if (this.gamepad) {
  79807. var camera = this.camera;
  79808. var RSValues = this.gamepad.rightStick;
  79809. if (RSValues) {
  79810. if (RSValues.x != 0) {
  79811. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  79812. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  79813. camera.inertialAlphaOffset += normalizedRX;
  79814. }
  79815. }
  79816. if (RSValues.y != 0) {
  79817. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  79818. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  79819. camera.inertialBetaOffset += normalizedRY;
  79820. }
  79821. }
  79822. }
  79823. var LSValues = this.gamepad.leftStick;
  79824. if (LSValues && LSValues.y != 0) {
  79825. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79826. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  79827. this.camera.inertialRadiusOffset -= normalizedLY;
  79828. }
  79829. }
  79830. }
  79831. };
  79832. /**
  79833. * Gets the class name of the current intput.
  79834. * @returns the class name
  79835. */
  79836. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  79837. return "ArcRotateCameraGamepadInput";
  79838. };
  79839. /**
  79840. * Get the friendly name associated with the input class.
  79841. * @returns the input friendly name
  79842. */
  79843. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  79844. return "gamepad";
  79845. };
  79846. __decorate([
  79847. BABYLON.serialize()
  79848. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  79849. __decorate([
  79850. BABYLON.serialize()
  79851. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79852. return ArcRotateCameraGamepadInput;
  79853. }());
  79854. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  79855. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  79856. })(BABYLON || (BABYLON = {}));
  79857. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  79858. var BABYLON;
  79859. (function (BABYLON) {
  79860. /**
  79861. * Manager for handling gamepads
  79862. */
  79863. var GamepadManager = /** @class */ (function () {
  79864. /**
  79865. * Initializes the gamepad manager
  79866. * @param _scene BabylonJS scene
  79867. */
  79868. function GamepadManager(_scene) {
  79869. var _this = this;
  79870. this._scene = _scene;
  79871. this._babylonGamepads = [];
  79872. this._oneGamepadConnected = false;
  79873. /** @hidden */
  79874. this._isMonitoring = false;
  79875. /**
  79876. * observable to be triggered when the gamepad controller has been disconnected
  79877. */
  79878. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  79879. if (!BABYLON.Tools.IsWindowObjectExist()) {
  79880. this._gamepadEventSupported = false;
  79881. }
  79882. else {
  79883. this._gamepadEventSupported = 'GamepadEvent' in window;
  79884. this._gamepadSupport = (navigator.getGamepads ||
  79885. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  79886. }
  79887. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  79888. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  79889. for (var i in _this._babylonGamepads) {
  79890. var gamepad = _this._babylonGamepads[i];
  79891. if (gamepad && gamepad._isConnected) {
  79892. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  79893. }
  79894. }
  79895. });
  79896. this._onGamepadConnectedEvent = function (evt) {
  79897. var gamepad = evt.gamepad;
  79898. if (gamepad.index in _this._babylonGamepads) {
  79899. if (_this._babylonGamepads[gamepad.index].isConnected) {
  79900. return;
  79901. }
  79902. }
  79903. var newGamepad;
  79904. if (_this._babylonGamepads[gamepad.index]) {
  79905. newGamepad = _this._babylonGamepads[gamepad.index];
  79906. newGamepad.browserGamepad = gamepad;
  79907. newGamepad._isConnected = true;
  79908. }
  79909. else {
  79910. newGamepad = _this._addNewGamepad(gamepad);
  79911. }
  79912. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79913. _this._startMonitoringGamepads();
  79914. };
  79915. this._onGamepadDisconnectedEvent = function (evt) {
  79916. var gamepad = evt.gamepad;
  79917. // Remove the gamepad from the list of gamepads to monitor.
  79918. for (var i in _this._babylonGamepads) {
  79919. if (_this._babylonGamepads[i].index === gamepad.index) {
  79920. var disconnectedGamepad = _this._babylonGamepads[i];
  79921. disconnectedGamepad._isConnected = false;
  79922. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79923. break;
  79924. }
  79925. }
  79926. };
  79927. if (this._gamepadSupport) {
  79928. //first add already-connected gamepads
  79929. this._updateGamepadObjects();
  79930. if (this._babylonGamepads.length) {
  79931. this._startMonitoringGamepads();
  79932. }
  79933. // Checking if the gamepad connected event is supported (like in Firefox)
  79934. if (this._gamepadEventSupported) {
  79935. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79936. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79937. }
  79938. else {
  79939. this._startMonitoringGamepads();
  79940. }
  79941. }
  79942. }
  79943. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79944. /**
  79945. * The gamepads in the game pad manager
  79946. */
  79947. get: function () {
  79948. return this._babylonGamepads;
  79949. },
  79950. enumerable: true,
  79951. configurable: true
  79952. });
  79953. /**
  79954. * Get the gamepad controllers based on type
  79955. * @param type The type of gamepad controller
  79956. * @returns Nullable gamepad
  79957. */
  79958. GamepadManager.prototype.getGamepadByType = function (type) {
  79959. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79960. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79961. var gamepad = _a[_i];
  79962. if (gamepad && gamepad.type === type) {
  79963. return gamepad;
  79964. }
  79965. }
  79966. return null;
  79967. };
  79968. /**
  79969. * Disposes the gamepad manager
  79970. */
  79971. GamepadManager.prototype.dispose = function () {
  79972. if (this._gamepadEventSupported) {
  79973. if (this._onGamepadConnectedEvent) {
  79974. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  79975. }
  79976. if (this._onGamepadDisconnectedEvent) {
  79977. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  79978. }
  79979. this._onGamepadConnectedEvent = null;
  79980. this._onGamepadDisconnectedEvent = null;
  79981. }
  79982. this._babylonGamepads.forEach(function (gamepad) {
  79983. gamepad.dispose();
  79984. });
  79985. this.onGamepadConnectedObservable.clear();
  79986. this.onGamepadDisconnectedObservable.clear();
  79987. this._oneGamepadConnected = false;
  79988. this._stopMonitoringGamepads();
  79989. this._babylonGamepads = [];
  79990. };
  79991. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  79992. if (!this._oneGamepadConnected) {
  79993. this._oneGamepadConnected = true;
  79994. }
  79995. var newGamepad;
  79996. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  79997. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  79998. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  79999. }
  80000. // if pose is supported, use the (WebVR) pose enabled controller
  80001. else if (gamepad.pose) {
  80002. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  80003. }
  80004. else {
  80005. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  80006. }
  80007. this._babylonGamepads[newGamepad.index] = newGamepad;
  80008. return newGamepad;
  80009. };
  80010. GamepadManager.prototype._startMonitoringGamepads = function () {
  80011. if (!this._isMonitoring) {
  80012. this._isMonitoring = true;
  80013. //back-comp
  80014. if (!this._scene) {
  80015. this._checkGamepadsStatus();
  80016. }
  80017. }
  80018. };
  80019. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80020. this._isMonitoring = false;
  80021. };
  80022. /** @hidden */
  80023. GamepadManager.prototype._checkGamepadsStatus = function () {
  80024. var _this = this;
  80025. // Hack to be compatible Chrome
  80026. this._updateGamepadObjects();
  80027. for (var i in this._babylonGamepads) {
  80028. var gamepad = this._babylonGamepads[i];
  80029. if (!gamepad || !gamepad.isConnected) {
  80030. continue;
  80031. }
  80032. gamepad.update();
  80033. }
  80034. if (this._isMonitoring && !this._scene) {
  80035. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80036. }
  80037. };
  80038. // This function is called only on Chrome, which does not properly support
  80039. // connection/disconnection events and forces you to recopy again the gamepad object
  80040. GamepadManager.prototype._updateGamepadObjects = function () {
  80041. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80042. for (var i = 0; i < gamepads.length; i++) {
  80043. var gamepad = gamepads[i];
  80044. if (gamepad) {
  80045. if (!this._babylonGamepads[gamepad.index]) {
  80046. var newGamepad = this._addNewGamepad(gamepad);
  80047. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80048. }
  80049. else {
  80050. // Forced to copy again this object for Chrome for unknown reason
  80051. this._babylonGamepads[i].browserGamepad = gamepad;
  80052. if (!this._babylonGamepads[i].isConnected) {
  80053. this._babylonGamepads[i]._isConnected = true;
  80054. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80055. }
  80056. }
  80057. }
  80058. }
  80059. };
  80060. return GamepadManager;
  80061. }());
  80062. BABYLON.GamepadManager = GamepadManager;
  80063. })(BABYLON || (BABYLON = {}));
  80064. //# sourceMappingURL=babylon.gamepadManager.js.map
  80065. var BABYLON;
  80066. (function (BABYLON) {
  80067. /**
  80068. * Represents a gamepad control stick position
  80069. */
  80070. var StickValues = /** @class */ (function () {
  80071. /**
  80072. * Initializes the gamepad x and y control stick values
  80073. * @param x The x component of the gamepad control stick value
  80074. * @param y The y component of the gamepad control stick value
  80075. */
  80076. function StickValues(
  80077. /**
  80078. * The x component of the control stick
  80079. */
  80080. x,
  80081. /**
  80082. * The y component of the control stick
  80083. */
  80084. y) {
  80085. this.x = x;
  80086. this.y = y;
  80087. }
  80088. return StickValues;
  80089. }());
  80090. BABYLON.StickValues = StickValues;
  80091. /**
  80092. * Represents a gamepad
  80093. */
  80094. var Gamepad = /** @class */ (function () {
  80095. /**
  80096. * Initializes the gamepad
  80097. * @param id The id of the gamepad
  80098. * @param index The index of the gamepad
  80099. * @param browserGamepad The browser gamepad
  80100. * @param leftStickX The x component of the left joystick
  80101. * @param leftStickY The y component of the left joystick
  80102. * @param rightStickX The x component of the right joystick
  80103. * @param rightStickY The y component of the right joystick
  80104. */
  80105. function Gamepad(
  80106. /**
  80107. * The id of the gamepad
  80108. */
  80109. id,
  80110. /**
  80111. * The index of the gamepad
  80112. */
  80113. index,
  80114. /**
  80115. * The browser gamepad
  80116. */
  80117. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80118. if (leftStickX === void 0) { leftStickX = 0; }
  80119. if (leftStickY === void 0) { leftStickY = 1; }
  80120. if (rightStickX === void 0) { rightStickX = 2; }
  80121. if (rightStickY === void 0) { rightStickY = 3; }
  80122. this.id = id;
  80123. this.index = index;
  80124. this.browserGamepad = browserGamepad;
  80125. this._leftStick = { x: 0, y: 0 };
  80126. this._rightStick = { x: 0, y: 0 };
  80127. /** @hidden */
  80128. this._isConnected = true;
  80129. /**
  80130. * Specifies whether the left control stick should be Y-inverted
  80131. */
  80132. this._invertLeftStickY = false;
  80133. this.type = Gamepad.GAMEPAD;
  80134. this._leftStickAxisX = leftStickX;
  80135. this._leftStickAxisY = leftStickY;
  80136. this._rightStickAxisX = rightStickX;
  80137. this._rightStickAxisY = rightStickY;
  80138. if (this.browserGamepad.axes.length >= 2) {
  80139. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80140. }
  80141. if (this.browserGamepad.axes.length >= 4) {
  80142. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80143. }
  80144. }
  80145. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80146. /**
  80147. * Specifies if the gamepad has been connected
  80148. */
  80149. get: function () {
  80150. return this._isConnected;
  80151. },
  80152. enumerable: true,
  80153. configurable: true
  80154. });
  80155. /**
  80156. * Callback triggered when the left joystick has changed
  80157. * @param callback
  80158. */
  80159. Gamepad.prototype.onleftstickchanged = function (callback) {
  80160. this._onleftstickchanged = callback;
  80161. };
  80162. /**
  80163. * Callback triggered when the right joystick has changed
  80164. * @param callback
  80165. */
  80166. Gamepad.prototype.onrightstickchanged = function (callback) {
  80167. this._onrightstickchanged = callback;
  80168. };
  80169. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80170. /**
  80171. * Gets the left joystick
  80172. */
  80173. get: function () {
  80174. return this._leftStick;
  80175. },
  80176. /**
  80177. * Sets the left joystick values
  80178. */
  80179. set: function (newValues) {
  80180. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80181. this._onleftstickchanged(newValues);
  80182. }
  80183. this._leftStick = newValues;
  80184. },
  80185. enumerable: true,
  80186. configurable: true
  80187. });
  80188. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80189. /**
  80190. * Gets the right joystick
  80191. */
  80192. get: function () {
  80193. return this._rightStick;
  80194. },
  80195. /**
  80196. * Sets the right joystick value
  80197. */
  80198. set: function (newValues) {
  80199. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80200. this._onrightstickchanged(newValues);
  80201. }
  80202. this._rightStick = newValues;
  80203. },
  80204. enumerable: true,
  80205. configurable: true
  80206. });
  80207. /**
  80208. * Updates the gamepad joystick positions
  80209. */
  80210. Gamepad.prototype.update = function () {
  80211. if (this._leftStick) {
  80212. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80213. if (this._invertLeftStickY) {
  80214. this.leftStick.y *= -1;
  80215. }
  80216. }
  80217. if (this._rightStick) {
  80218. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80219. }
  80220. };
  80221. /**
  80222. * Disposes the gamepad
  80223. */
  80224. Gamepad.prototype.dispose = function () {
  80225. };
  80226. /**
  80227. * Represents a gamepad controller
  80228. */
  80229. Gamepad.GAMEPAD = 0;
  80230. /**
  80231. * Represents a generic controller
  80232. */
  80233. Gamepad.GENERIC = 1;
  80234. /**
  80235. * Represents an XBox controller
  80236. */
  80237. Gamepad.XBOX = 2;
  80238. /**
  80239. * Represents a pose-enabled controller
  80240. */
  80241. Gamepad.POSE_ENABLED = 3;
  80242. return Gamepad;
  80243. }());
  80244. BABYLON.Gamepad = Gamepad;
  80245. /**
  80246. * Represents a generic gamepad
  80247. */
  80248. var GenericPad = /** @class */ (function (_super) {
  80249. __extends(GenericPad, _super);
  80250. /**
  80251. * Initializes the generic gamepad
  80252. * @param id The id of the generic gamepad
  80253. * @param index The index of the generic gamepad
  80254. * @param browserGamepad The browser gamepad
  80255. */
  80256. function GenericPad(id, index, browserGamepad) {
  80257. var _this = _super.call(this, id, index, browserGamepad) || this;
  80258. /**
  80259. * Observable triggered when a button has been pressed
  80260. */
  80261. _this.onButtonDownObservable = new BABYLON.Observable();
  80262. /**
  80263. * Observable triggered when a button has been released
  80264. */
  80265. _this.onButtonUpObservable = new BABYLON.Observable();
  80266. _this.type = Gamepad.GENERIC;
  80267. _this._buttons = new Array(browserGamepad.buttons.length);
  80268. return _this;
  80269. }
  80270. /**
  80271. * Callback triggered when a button has been pressed
  80272. * @param callback Called when a button has been pressed
  80273. */
  80274. GenericPad.prototype.onbuttondown = function (callback) {
  80275. this._onbuttondown = callback;
  80276. };
  80277. /**
  80278. * Callback triggered when a button has been released
  80279. * @param callback Called when a button has been released
  80280. */
  80281. GenericPad.prototype.onbuttonup = function (callback) {
  80282. this._onbuttonup = callback;
  80283. };
  80284. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80285. if (newValue !== currentValue) {
  80286. if (newValue === 1) {
  80287. if (this._onbuttondown) {
  80288. this._onbuttondown(buttonIndex);
  80289. }
  80290. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80291. }
  80292. if (newValue === 0) {
  80293. if (this._onbuttonup) {
  80294. this._onbuttonup(buttonIndex);
  80295. }
  80296. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80297. }
  80298. }
  80299. return newValue;
  80300. };
  80301. /**
  80302. * Updates the generic gamepad
  80303. */
  80304. GenericPad.prototype.update = function () {
  80305. _super.prototype.update.call(this);
  80306. for (var index = 0; index < this._buttons.length; index++) {
  80307. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80308. }
  80309. };
  80310. /**
  80311. * Disposes the generic gamepad
  80312. */
  80313. GenericPad.prototype.dispose = function () {
  80314. _super.prototype.dispose.call(this);
  80315. this.onButtonDownObservable.clear();
  80316. this.onButtonUpObservable.clear();
  80317. };
  80318. return GenericPad;
  80319. }(Gamepad));
  80320. BABYLON.GenericPad = GenericPad;
  80321. })(BABYLON || (BABYLON = {}));
  80322. //# sourceMappingURL=babylon.gamepad.js.map
  80323. var BABYLON;
  80324. (function (BABYLON) {
  80325. /**
  80326. * Defines supported buttons for XBox360 compatible gamepads
  80327. */
  80328. var Xbox360Button;
  80329. (function (Xbox360Button) {
  80330. /** A */
  80331. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80332. /** B */
  80333. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80334. /** X */
  80335. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80336. /** Y */
  80337. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80338. /** Start */
  80339. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80340. /** Back */
  80341. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80342. /** Left button */
  80343. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80344. /** Right button */
  80345. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80346. /** Left stick */
  80347. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80348. /** Right stick */
  80349. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80350. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80351. /** Defines values for XBox360 DPad */
  80352. var Xbox360Dpad;
  80353. (function (Xbox360Dpad) {
  80354. /** Up */
  80355. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80356. /** Down */
  80357. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80358. /** Left */
  80359. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80360. /** Right */
  80361. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80362. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80363. /**
  80364. * Defines a XBox360 gamepad
  80365. */
  80366. var Xbox360Pad = /** @class */ (function (_super) {
  80367. __extends(Xbox360Pad, _super);
  80368. /**
  80369. * Creates a new XBox360 gamepad object
  80370. * @param id defines the id of this gamepad
  80371. * @param index defines its index
  80372. * @param gamepad defines the internal HTML gamepad object
  80373. * @param xboxOne defines if it is a XBox One gamepad
  80374. */
  80375. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80376. if (xboxOne === void 0) { xboxOne = false; }
  80377. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80378. _this._leftTrigger = 0;
  80379. _this._rightTrigger = 0;
  80380. /** Observable raised when a button is pressed */
  80381. _this.onButtonDownObservable = new BABYLON.Observable();
  80382. /** Observable raised when a button is released */
  80383. _this.onButtonUpObservable = new BABYLON.Observable();
  80384. /** Observable raised when a pad is pressed */
  80385. _this.onPadDownObservable = new BABYLON.Observable();
  80386. /** Observable raised when a pad is released */
  80387. _this.onPadUpObservable = new BABYLON.Observable();
  80388. _this._buttonA = 0;
  80389. _this._buttonB = 0;
  80390. _this._buttonX = 0;
  80391. _this._buttonY = 0;
  80392. _this._buttonBack = 0;
  80393. _this._buttonStart = 0;
  80394. _this._buttonLB = 0;
  80395. _this._buttonRB = 0;
  80396. _this._buttonLeftStick = 0;
  80397. _this._buttonRightStick = 0;
  80398. _this._dPadUp = 0;
  80399. _this._dPadDown = 0;
  80400. _this._dPadLeft = 0;
  80401. _this._dPadRight = 0;
  80402. _this._isXboxOnePad = false;
  80403. _this.type = BABYLON.Gamepad.XBOX;
  80404. _this._isXboxOnePad = xboxOne;
  80405. return _this;
  80406. }
  80407. /**
  80408. * Defines the callback to call when left trigger is pressed
  80409. * @param callback defines the callback to use
  80410. */
  80411. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80412. this._onlefttriggerchanged = callback;
  80413. };
  80414. /**
  80415. * Defines the callback to call when right trigger is pressed
  80416. * @param callback defines the callback to use
  80417. */
  80418. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80419. this._onrighttriggerchanged = callback;
  80420. };
  80421. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80422. /**
  80423. * Gets the left trigger value
  80424. */
  80425. get: function () {
  80426. return this._leftTrigger;
  80427. },
  80428. /**
  80429. * Sets the left trigger value
  80430. */
  80431. set: function (newValue) {
  80432. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80433. this._onlefttriggerchanged(newValue);
  80434. }
  80435. this._leftTrigger = newValue;
  80436. },
  80437. enumerable: true,
  80438. configurable: true
  80439. });
  80440. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80441. /**
  80442. * Gets the right trigger value
  80443. */
  80444. get: function () {
  80445. return this._rightTrigger;
  80446. },
  80447. /**
  80448. * Sets the right trigger value
  80449. */
  80450. set: function (newValue) {
  80451. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80452. this._onrighttriggerchanged(newValue);
  80453. }
  80454. this._rightTrigger = newValue;
  80455. },
  80456. enumerable: true,
  80457. configurable: true
  80458. });
  80459. /**
  80460. * Defines the callback to call when a button is pressed
  80461. * @param callback defines the callback to use
  80462. */
  80463. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80464. this._onbuttondown = callback;
  80465. };
  80466. /**
  80467. * Defines the callback to call when a button is released
  80468. * @param callback defines the callback to use
  80469. */
  80470. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80471. this._onbuttonup = callback;
  80472. };
  80473. /**
  80474. * Defines the callback to call when a pad is pressed
  80475. * @param callback defines the callback to use
  80476. */
  80477. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80478. this._ondpaddown = callback;
  80479. };
  80480. /**
  80481. * Defines the callback to call when a pad is released
  80482. * @param callback defines the callback to use
  80483. */
  80484. Xbox360Pad.prototype.ondpadup = function (callback) {
  80485. this._ondpadup = callback;
  80486. };
  80487. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80488. if (newValue !== currentValue) {
  80489. if (newValue === 1) {
  80490. if (this._onbuttondown) {
  80491. this._onbuttondown(buttonType);
  80492. }
  80493. this.onButtonDownObservable.notifyObservers(buttonType);
  80494. }
  80495. if (newValue === 0) {
  80496. if (this._onbuttonup) {
  80497. this._onbuttonup(buttonType);
  80498. }
  80499. this.onButtonUpObservable.notifyObservers(buttonType);
  80500. }
  80501. }
  80502. return newValue;
  80503. };
  80504. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80505. if (newValue !== currentValue) {
  80506. if (newValue === 1) {
  80507. if (this._ondpaddown) {
  80508. this._ondpaddown(buttonType);
  80509. }
  80510. this.onPadDownObservable.notifyObservers(buttonType);
  80511. }
  80512. if (newValue === 0) {
  80513. if (this._ondpadup) {
  80514. this._ondpadup(buttonType);
  80515. }
  80516. this.onPadUpObservable.notifyObservers(buttonType);
  80517. }
  80518. }
  80519. return newValue;
  80520. };
  80521. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80522. /**
  80523. * Gets the value of the `A` button
  80524. */
  80525. get: function () {
  80526. return this._buttonA;
  80527. },
  80528. /**
  80529. * Sets the value of the `A` button
  80530. */
  80531. set: function (value) {
  80532. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80533. },
  80534. enumerable: true,
  80535. configurable: true
  80536. });
  80537. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80538. /**
  80539. * Gets the value of the `B` button
  80540. */
  80541. get: function () {
  80542. return this._buttonB;
  80543. },
  80544. /**
  80545. * Sets the value of the `B` button
  80546. */
  80547. set: function (value) {
  80548. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80549. },
  80550. enumerable: true,
  80551. configurable: true
  80552. });
  80553. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80554. /**
  80555. * Gets the value of the `X` button
  80556. */
  80557. get: function () {
  80558. return this._buttonX;
  80559. },
  80560. /**
  80561. * Sets the value of the `X` button
  80562. */
  80563. set: function (value) {
  80564. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80565. },
  80566. enumerable: true,
  80567. configurable: true
  80568. });
  80569. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80570. /**
  80571. * Gets the value of the `Y` button
  80572. */
  80573. get: function () {
  80574. return this._buttonY;
  80575. },
  80576. /**
  80577. * Sets the value of the `Y` button
  80578. */
  80579. set: function (value) {
  80580. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80581. },
  80582. enumerable: true,
  80583. configurable: true
  80584. });
  80585. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80586. /**
  80587. * Gets the value of the `Start` button
  80588. */
  80589. get: function () {
  80590. return this._buttonStart;
  80591. },
  80592. /**
  80593. * Sets the value of the `Start` button
  80594. */
  80595. set: function (value) {
  80596. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80597. },
  80598. enumerable: true,
  80599. configurable: true
  80600. });
  80601. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80602. /**
  80603. * Gets the value of the `Back` button
  80604. */
  80605. get: function () {
  80606. return this._buttonBack;
  80607. },
  80608. /**
  80609. * Sets the value of the `Back` button
  80610. */
  80611. set: function (value) {
  80612. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80613. },
  80614. enumerable: true,
  80615. configurable: true
  80616. });
  80617. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80618. /**
  80619. * Gets the value of the `Left` button
  80620. */
  80621. get: function () {
  80622. return this._buttonLB;
  80623. },
  80624. /**
  80625. * Sets the value of the `Left` button
  80626. */
  80627. set: function (value) {
  80628. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80629. },
  80630. enumerable: true,
  80631. configurable: true
  80632. });
  80633. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80634. /**
  80635. * Gets the value of the `Right` button
  80636. */
  80637. get: function () {
  80638. return this._buttonRB;
  80639. },
  80640. /**
  80641. * Sets the value of the `Right` button
  80642. */
  80643. set: function (value) {
  80644. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80645. },
  80646. enumerable: true,
  80647. configurable: true
  80648. });
  80649. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80650. /**
  80651. * Gets the value of the Left joystick
  80652. */
  80653. get: function () {
  80654. return this._buttonLeftStick;
  80655. },
  80656. /**
  80657. * Sets the value of the Left joystick
  80658. */
  80659. set: function (value) {
  80660. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80661. },
  80662. enumerable: true,
  80663. configurable: true
  80664. });
  80665. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80666. /**
  80667. * Gets the value of the Right joystick
  80668. */
  80669. get: function () {
  80670. return this._buttonRightStick;
  80671. },
  80672. /**
  80673. * Sets the value of the Right joystick
  80674. */
  80675. set: function (value) {
  80676. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80677. },
  80678. enumerable: true,
  80679. configurable: true
  80680. });
  80681. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80682. /**
  80683. * Gets the value of D-pad up
  80684. */
  80685. get: function () {
  80686. return this._dPadUp;
  80687. },
  80688. /**
  80689. * Sets the value of D-pad up
  80690. */
  80691. set: function (value) {
  80692. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  80693. },
  80694. enumerable: true,
  80695. configurable: true
  80696. });
  80697. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  80698. /**
  80699. * Gets the value of D-pad down
  80700. */
  80701. get: function () {
  80702. return this._dPadDown;
  80703. },
  80704. /**
  80705. * Sets the value of D-pad down
  80706. */
  80707. set: function (value) {
  80708. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  80709. },
  80710. enumerable: true,
  80711. configurable: true
  80712. });
  80713. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  80714. /**
  80715. * Gets the value of D-pad left
  80716. */
  80717. get: function () {
  80718. return this._dPadLeft;
  80719. },
  80720. /**
  80721. * Sets the value of D-pad left
  80722. */
  80723. set: function (value) {
  80724. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  80725. },
  80726. enumerable: true,
  80727. configurable: true
  80728. });
  80729. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  80730. /**
  80731. * Gets the value of D-pad right
  80732. */
  80733. get: function () {
  80734. return this._dPadRight;
  80735. },
  80736. /**
  80737. * Sets the value of D-pad right
  80738. */
  80739. set: function (value) {
  80740. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  80741. },
  80742. enumerable: true,
  80743. configurable: true
  80744. });
  80745. /**
  80746. * Force the gamepad to synchronize with device values
  80747. */
  80748. Xbox360Pad.prototype.update = function () {
  80749. _super.prototype.update.call(this);
  80750. if (this._isXboxOnePad) {
  80751. this.buttonA = this.browserGamepad.buttons[0].value;
  80752. this.buttonB = this.browserGamepad.buttons[1].value;
  80753. this.buttonX = this.browserGamepad.buttons[2].value;
  80754. this.buttonY = this.browserGamepad.buttons[3].value;
  80755. this.buttonLB = this.browserGamepad.buttons[4].value;
  80756. this.buttonRB = this.browserGamepad.buttons[5].value;
  80757. this.leftTrigger = this.browserGamepad.axes[2];
  80758. this.rightTrigger = this.browserGamepad.axes[5];
  80759. this.buttonBack = this.browserGamepad.buttons[9].value;
  80760. this.buttonStart = this.browserGamepad.buttons[8].value;
  80761. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  80762. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  80763. this.dPadUp = this.browserGamepad.buttons[11].value;
  80764. this.dPadDown = this.browserGamepad.buttons[12].value;
  80765. this.dPadLeft = this.browserGamepad.buttons[13].value;
  80766. this.dPadRight = this.browserGamepad.buttons[14].value;
  80767. }
  80768. else {
  80769. this.buttonA = this.browserGamepad.buttons[0].value;
  80770. this.buttonB = this.browserGamepad.buttons[1].value;
  80771. this.buttonX = this.browserGamepad.buttons[2].value;
  80772. this.buttonY = this.browserGamepad.buttons[3].value;
  80773. this.buttonLB = this.browserGamepad.buttons[4].value;
  80774. this.buttonRB = this.browserGamepad.buttons[5].value;
  80775. this.leftTrigger = this.browserGamepad.buttons[6].value;
  80776. this.rightTrigger = this.browserGamepad.buttons[7].value;
  80777. this.buttonBack = this.browserGamepad.buttons[8].value;
  80778. this.buttonStart = this.browserGamepad.buttons[9].value;
  80779. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  80780. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  80781. this.dPadUp = this.browserGamepad.buttons[12].value;
  80782. this.dPadDown = this.browserGamepad.buttons[13].value;
  80783. this.dPadLeft = this.browserGamepad.buttons[14].value;
  80784. this.dPadRight = this.browserGamepad.buttons[15].value;
  80785. }
  80786. };
  80787. /**
  80788. * Disposes the gamepad
  80789. */
  80790. Xbox360Pad.prototype.dispose = function () {
  80791. _super.prototype.dispose.call(this);
  80792. this.onButtonDownObservable.clear();
  80793. this.onButtonUpObservable.clear();
  80794. this.onPadDownObservable.clear();
  80795. this.onPadUpObservable.clear();
  80796. };
  80797. return Xbox360Pad;
  80798. }(BABYLON.Gamepad));
  80799. BABYLON.Xbox360Pad = Xbox360Pad;
  80800. })(BABYLON || (BABYLON = {}));
  80801. //# sourceMappingURL=babylon.xboxGamepad.js.map
  80802. var BABYLON;
  80803. (function (BABYLON) {
  80804. /**
  80805. * Defines the types of pose enabled controllers that are supported
  80806. */
  80807. var PoseEnabledControllerType;
  80808. (function (PoseEnabledControllerType) {
  80809. /**
  80810. * HTC Vive
  80811. */
  80812. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  80813. /**
  80814. * Oculus Rift
  80815. */
  80816. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  80817. /**
  80818. * Windows mixed reality
  80819. */
  80820. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  80821. /**
  80822. * Samsung gear VR
  80823. */
  80824. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  80825. /**
  80826. * Google Daydream
  80827. */
  80828. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  80829. /**
  80830. * Generic
  80831. */
  80832. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  80833. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  80834. /**
  80835. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80836. */
  80837. var PoseEnabledControllerHelper = /** @class */ (function () {
  80838. function PoseEnabledControllerHelper() {
  80839. }
  80840. /**
  80841. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80842. * @param vrGamepad the gamepad to initialized
  80843. * @returns a vr controller of the type the gamepad identified as
  80844. */
  80845. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  80846. // Oculus Touch
  80847. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  80848. return new BABYLON.OculusTouchController(vrGamepad);
  80849. }
  80850. // Windows Mixed Reality controllers
  80851. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  80852. return new BABYLON.WindowsMotionController(vrGamepad);
  80853. }
  80854. // HTC Vive
  80855. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  80856. return new BABYLON.ViveController(vrGamepad);
  80857. }
  80858. // Samsung/Oculus Gear VR or Oculus Go
  80859. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  80860. return new BABYLON.GearVRController(vrGamepad);
  80861. }
  80862. // Google Daydream
  80863. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  80864. return new BABYLON.DaydreamController(vrGamepad);
  80865. }
  80866. // Generic
  80867. else {
  80868. return new BABYLON.GenericController(vrGamepad);
  80869. }
  80870. };
  80871. return PoseEnabledControllerHelper;
  80872. }());
  80873. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  80874. /**
  80875. * Defines the PoseEnabledController object that contains state of a vr capable controller
  80876. */
  80877. var PoseEnabledController = /** @class */ (function (_super) {
  80878. __extends(PoseEnabledController, _super);
  80879. /**
  80880. * Creates a new PoseEnabledController from a gamepad
  80881. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  80882. */
  80883. function PoseEnabledController(browserGamepad) {
  80884. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  80885. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80886. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80887. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  80888. /**
  80889. * The device position in babylon space
  80890. */
  80891. _this.devicePosition = BABYLON.Vector3.Zero();
  80892. /**
  80893. * The device rotation in babylon space
  80894. */
  80895. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  80896. /**
  80897. * The scale factor of the device in babylon space
  80898. */
  80899. _this.deviceScaleFactor = 1;
  80900. // Used to convert 6dof controllers to 3dof
  80901. _this._trackPosition = true;
  80902. _this._maxRotationDistFromHeadset = Math.PI / 5;
  80903. _this._draggedRoomRotation = 0;
  80904. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  80905. /**
  80906. * Internal, matrix used to convert room space to babylon space
  80907. * @hidden
  80908. */
  80909. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80910. /**
  80911. * Node to be used when casting a ray from the controller
  80912. * @hidden
  80913. */
  80914. _this._pointingPoseNode = null;
  80915. _this._workingMatrix = BABYLON.Matrix.Identity();
  80916. /**
  80917. * @hidden
  80918. */
  80919. _this._meshAttachedObservable = new BABYLON.Observable();
  80920. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80921. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80922. _this.position = BABYLON.Vector3.Zero();
  80923. _this.rotationQuaternion = new BABYLON.Quaternion();
  80924. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80925. _this._calculatedRotation = new BABYLON.Quaternion();
  80926. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80927. return _this;
  80928. }
  80929. /**
  80930. * @hidden
  80931. */
  80932. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80933. if (this._trackPosition) {
  80934. this._calculatedPosition.copyFrom(fixedPosition);
  80935. this._trackPosition = false;
  80936. }
  80937. };
  80938. /**
  80939. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80940. */
  80941. PoseEnabledController.prototype.update = function () {
  80942. _super.prototype.update.call(this);
  80943. this._updatePoseAndMesh();
  80944. };
  80945. /**
  80946. * Updates only the pose device and mesh without doing any button event checking
  80947. */
  80948. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80949. var pose = this.browserGamepad.pose;
  80950. this.updateFromDevice(pose);
  80951. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80952. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80953. camera._computeDevicePosition();
  80954. this._deviceToWorld.setTranslation(camera.devicePosition);
  80955. if (camera.deviceRotationQuaternion) {
  80956. var camera = camera;
  80957. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80958. // Find the radian distance away that the headset is from the controllers rotation
  80959. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80960. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80961. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80962. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80963. this._draggedRoomRotation += rotationAmount;
  80964. // Rotate controller around headset
  80965. var sin = Math.sin(-rotationAmount);
  80966. var cos = Math.cos(-rotationAmount);
  80967. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80968. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80969. }
  80970. }
  80971. }
  80972. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  80973. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  80974. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  80975. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  80976. if (this._mesh) {
  80977. this._mesh.position.copyFrom(this.devicePosition);
  80978. if (this._mesh.rotationQuaternion) {
  80979. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  80980. }
  80981. }
  80982. };
  80983. /**
  80984. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  80985. * @param poseData raw pose fromthe device
  80986. */
  80987. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  80988. if (poseData) {
  80989. this.rawPose = poseData;
  80990. if (poseData.position) {
  80991. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  80992. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  80993. this._deviceRoomPosition.z *= -1;
  80994. }
  80995. if (this._trackPosition) {
  80996. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  80997. }
  80998. this._calculatedPosition.addInPlace(this.position);
  80999. }
  81000. var pose = this.rawPose;
  81001. if (poseData.orientation && pose.orientation) {
  81002. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  81003. if (this._mesh) {
  81004. if (this._mesh.getScene().useRightHandedSystem) {
  81005. this._deviceRoomRotationQuaternion.z *= -1;
  81006. this._deviceRoomRotationQuaternion.w *= -1;
  81007. }
  81008. else {
  81009. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  81010. }
  81011. }
  81012. // if the camera is set, rotate to the camera's rotation
  81013. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  81014. }
  81015. }
  81016. };
  81017. /**
  81018. * Attaches a mesh to the controller
  81019. * @param mesh the mesh to be attached
  81020. */
  81021. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81022. if (this._mesh) {
  81023. this._mesh.parent = null;
  81024. }
  81025. this._mesh = mesh;
  81026. if (this._poseControlledCamera) {
  81027. this._mesh.parent = this._poseControlledCamera;
  81028. }
  81029. if (!this._mesh.rotationQuaternion) {
  81030. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81031. }
  81032. // 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
  81033. this._updatePoseAndMesh();
  81034. if (this._pointingPoseNode) {
  81035. var parents = [];
  81036. var obj = this._pointingPoseNode;
  81037. while (obj.parent) {
  81038. parents.push(obj.parent);
  81039. obj = obj.parent;
  81040. }
  81041. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81042. }
  81043. this._meshAttachedObservable.notifyObservers(mesh);
  81044. };
  81045. /**
  81046. * Attaches the controllers mesh to a camera
  81047. * @param camera the camera the mesh should be attached to
  81048. */
  81049. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81050. this._poseControlledCamera = camera;
  81051. if (this._mesh) {
  81052. this._mesh.parent = this._poseControlledCamera;
  81053. }
  81054. };
  81055. /**
  81056. * Disposes of the controller
  81057. */
  81058. PoseEnabledController.prototype.dispose = function () {
  81059. if (this._mesh) {
  81060. this._mesh.dispose();
  81061. }
  81062. this._mesh = null;
  81063. _super.prototype.dispose.call(this);
  81064. };
  81065. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81066. /**
  81067. * The mesh that is attached to the controller
  81068. */
  81069. get: function () {
  81070. return this._mesh;
  81071. },
  81072. enumerable: true,
  81073. configurable: true
  81074. });
  81075. /**
  81076. * Gets the ray of the controller in the direction the controller is pointing
  81077. * @param length the length the resulting ray should be
  81078. * @returns a ray in the direction the controller is pointing
  81079. */
  81080. PoseEnabledController.prototype.getForwardRay = function (length) {
  81081. if (length === void 0) { length = 100; }
  81082. if (!this.mesh) {
  81083. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81084. }
  81085. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81086. var origin = m.getTranslation();
  81087. var forward = new BABYLON.Vector3(0, 0, -1);
  81088. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81089. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81090. return new BABYLON.Ray(origin, direction, length);
  81091. };
  81092. /**
  81093. * Name of the child mesh that can be used to cast a ray from the controller
  81094. */
  81095. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81096. return PoseEnabledController;
  81097. }(BABYLON.Gamepad));
  81098. BABYLON.PoseEnabledController = PoseEnabledController;
  81099. })(BABYLON || (BABYLON = {}));
  81100. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81101. var BABYLON;
  81102. (function (BABYLON) {
  81103. /**
  81104. * Defines the WebVRController object that represents controllers tracked in 3D space
  81105. */
  81106. var WebVRController = /** @class */ (function (_super) {
  81107. __extends(WebVRController, _super);
  81108. /**
  81109. * Creates a new WebVRController from a gamepad
  81110. * @param vrGamepad the gamepad that the WebVRController should be created from
  81111. */
  81112. function WebVRController(vrGamepad) {
  81113. var _this = _super.call(this, vrGamepad) || this;
  81114. // Observables
  81115. /**
  81116. * Fired when the trigger state has changed
  81117. */
  81118. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81119. /**
  81120. * Fired when the main button state has changed
  81121. */
  81122. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81123. /**
  81124. * Fired when the secondary button state has changed
  81125. */
  81126. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81127. /**
  81128. * Fired when the pad state has changed
  81129. */
  81130. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81131. /**
  81132. * Fired when controllers stick values have changed
  81133. */
  81134. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81135. /**
  81136. * X and Y axis corrisponding to the controllers joystick
  81137. */
  81138. _this.pad = { x: 0, y: 0 };
  81139. // avoid GC, store state in a tmp object
  81140. _this._changes = {
  81141. pressChanged: false,
  81142. touchChanged: false,
  81143. valueChanged: false,
  81144. changed: false
  81145. };
  81146. _this._buttons = new Array(vrGamepad.buttons.length);
  81147. _this.hand = vrGamepad.hand;
  81148. return _this;
  81149. }
  81150. /**
  81151. * Fired when a controller button's state has changed
  81152. * @param callback the callback containing the button that was modified
  81153. */
  81154. WebVRController.prototype.onButtonStateChange = function (callback) {
  81155. this._onButtonStateChange = callback;
  81156. };
  81157. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81158. /**
  81159. * The default controller model for the controller
  81160. */
  81161. get: function () {
  81162. return this._defaultModel;
  81163. },
  81164. enumerable: true,
  81165. configurable: true
  81166. });
  81167. /**
  81168. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81169. */
  81170. WebVRController.prototype.update = function () {
  81171. _super.prototype.update.call(this);
  81172. for (var index = 0; index < this._buttons.length; index++) {
  81173. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81174. }
  81175. ;
  81176. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81177. this.pad.x = this.leftStick.x;
  81178. this.pad.y = this.leftStick.y;
  81179. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81180. }
  81181. };
  81182. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81183. if (!newState) {
  81184. newState = {
  81185. pressed: false,
  81186. touched: false,
  81187. value: 0
  81188. };
  81189. }
  81190. if (!currentState) {
  81191. this._buttons[buttonIndex] = {
  81192. pressed: newState.pressed,
  81193. touched: newState.touched,
  81194. value: newState.value
  81195. };
  81196. return;
  81197. }
  81198. this._checkChanges(newState, currentState);
  81199. if (this._changes.changed) {
  81200. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81201. this._handleButtonChange(buttonIndex, newState, this._changes);
  81202. }
  81203. this._buttons[buttonIndex].pressed = newState.pressed;
  81204. this._buttons[buttonIndex].touched = newState.touched;
  81205. // oculus triggers are never 0, thou not touched.
  81206. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81207. };
  81208. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81209. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81210. this._changes.touchChanged = newState.touched !== currentState.touched;
  81211. this._changes.valueChanged = newState.value !== currentState.value;
  81212. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81213. return this._changes;
  81214. };
  81215. /**
  81216. * Disposes of th webVRCOntroller
  81217. */
  81218. WebVRController.prototype.dispose = function () {
  81219. _super.prototype.dispose.call(this);
  81220. this.onTriggerStateChangedObservable.clear();
  81221. this.onMainButtonStateChangedObservable.clear();
  81222. this.onSecondaryButtonStateChangedObservable.clear();
  81223. this.onPadStateChangedObservable.clear();
  81224. this.onPadValuesChangedObservable.clear();
  81225. };
  81226. return WebVRController;
  81227. }(BABYLON.PoseEnabledController));
  81228. BABYLON.WebVRController = WebVRController;
  81229. })(BABYLON || (BABYLON = {}));
  81230. //# sourceMappingURL=babylon.webVRController.js.map
  81231. var BABYLON;
  81232. (function (BABYLON) {
  81233. /**
  81234. * Oculus Touch Controller
  81235. */
  81236. var OculusTouchController = /** @class */ (function (_super) {
  81237. __extends(OculusTouchController, _super);
  81238. /**
  81239. * Creates a new OculusTouchController from a gamepad
  81240. * @param vrGamepad the gamepad that the controller should be created from
  81241. */
  81242. function OculusTouchController(vrGamepad) {
  81243. var _this = _super.call(this, vrGamepad) || this;
  81244. /**
  81245. * Fired when the secondary trigger on this controller is modified
  81246. */
  81247. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81248. /**
  81249. * Fired when the thumb rest on this controller is modified
  81250. */
  81251. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81252. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81253. return _this;
  81254. }
  81255. /**
  81256. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81257. * @param scene scene in which to add meshes
  81258. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81259. */
  81260. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81261. var _this = this;
  81262. var meshName;
  81263. // Hand
  81264. if (this.hand === 'left') {
  81265. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81266. }
  81267. else { // Right is the default if no hand is specified
  81268. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81269. }
  81270. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81271. /*
  81272. Parent Mesh name: oculus_touch_left
  81273. - body
  81274. - trigger
  81275. - thumbstick
  81276. - grip
  81277. - button_y
  81278. - button_x
  81279. - button_enter
  81280. */
  81281. _this._defaultModel = newMeshes[1];
  81282. _this.attachToMesh(_this._defaultModel);
  81283. if (meshLoaded) {
  81284. meshLoaded(_this._defaultModel);
  81285. }
  81286. });
  81287. };
  81288. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81289. /**
  81290. * Fired when the A button on this controller is modified
  81291. */
  81292. get: function () {
  81293. if (this.hand === 'right') {
  81294. return this.onMainButtonStateChangedObservable;
  81295. }
  81296. else {
  81297. throw new Error('No A button on left hand');
  81298. }
  81299. },
  81300. enumerable: true,
  81301. configurable: true
  81302. });
  81303. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81304. /**
  81305. * Fired when the B button on this controller is modified
  81306. */
  81307. get: function () {
  81308. if (this.hand === 'right') {
  81309. return this.onSecondaryButtonStateChangedObservable;
  81310. }
  81311. else {
  81312. throw new Error('No B button on left hand');
  81313. }
  81314. },
  81315. enumerable: true,
  81316. configurable: true
  81317. });
  81318. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81319. /**
  81320. * Fired when the X button on this controller is modified
  81321. */
  81322. get: function () {
  81323. if (this.hand === 'left') {
  81324. return this.onMainButtonStateChangedObservable;
  81325. }
  81326. else {
  81327. throw new Error('No X button on right hand');
  81328. }
  81329. },
  81330. enumerable: true,
  81331. configurable: true
  81332. });
  81333. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81334. /**
  81335. * Fired when the Y button on this controller is modified
  81336. */
  81337. get: function () {
  81338. if (this.hand === 'left') {
  81339. return this.onSecondaryButtonStateChangedObservable;
  81340. }
  81341. else {
  81342. throw new Error('No Y button on right hand');
  81343. }
  81344. },
  81345. enumerable: true,
  81346. configurable: true
  81347. });
  81348. /**
  81349. * Called once for each button that changed state since the last frame
  81350. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81351. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81352. * 2) secondary trigger (same)
  81353. * 3) A (right) X (left), touch, pressed = value
  81354. * 4) B / Y
  81355. * 5) thumb rest
  81356. * @param buttonIdx Which button index changed
  81357. * @param state New state of the button
  81358. * @param changes Which properties on the state changed since last frame
  81359. */
  81360. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81361. var notifyObject = state; //{ state: state, changes: changes };
  81362. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81363. switch (buttonIdx) {
  81364. case 0:
  81365. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81366. return;
  81367. case 1: // index trigger
  81368. if (this._defaultModel) {
  81369. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81370. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81371. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81372. }
  81373. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81374. return;
  81375. case 2: // secondary trigger
  81376. if (this._defaultModel) {
  81377. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81378. }
  81379. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81380. return;
  81381. case 3:
  81382. if (this._defaultModel) {
  81383. if (notifyObject.pressed) {
  81384. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81385. }
  81386. else {
  81387. (this._defaultModel.getChildren()[1]).position.y = 0;
  81388. }
  81389. }
  81390. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81391. return;
  81392. case 4:
  81393. if (this._defaultModel) {
  81394. if (notifyObject.pressed) {
  81395. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81396. }
  81397. else {
  81398. (this._defaultModel.getChildren()[2]).position.y = 0;
  81399. }
  81400. }
  81401. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81402. return;
  81403. case 5:
  81404. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81405. return;
  81406. }
  81407. };
  81408. /**
  81409. * Base Url for the controller model.
  81410. */
  81411. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81412. /**
  81413. * File name for the left controller model.
  81414. */
  81415. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81416. /**
  81417. * File name for the right controller model.
  81418. */
  81419. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81420. return OculusTouchController;
  81421. }(BABYLON.WebVRController));
  81422. BABYLON.OculusTouchController = OculusTouchController;
  81423. })(BABYLON || (BABYLON = {}));
  81424. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81425. var BABYLON;
  81426. (function (BABYLON) {
  81427. /**
  81428. * Vive Controller
  81429. */
  81430. var ViveController = /** @class */ (function (_super) {
  81431. __extends(ViveController, _super);
  81432. /**
  81433. * Creates a new ViveController from a gamepad
  81434. * @param vrGamepad the gamepad that the controller should be created from
  81435. */
  81436. function ViveController(vrGamepad) {
  81437. var _this = _super.call(this, vrGamepad) || this;
  81438. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81439. _this._invertLeftStickY = true;
  81440. return _this;
  81441. }
  81442. /**
  81443. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81444. * @param scene scene in which to add meshes
  81445. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81446. */
  81447. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81448. var _this = this;
  81449. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81450. /*
  81451. Parent Mesh name: ViveWand
  81452. - body
  81453. - r_gripper
  81454. - l_gripper
  81455. - menu_button
  81456. - system_button
  81457. - trackpad
  81458. - trigger
  81459. - LED
  81460. */
  81461. _this._defaultModel = newMeshes[1];
  81462. _this.attachToMesh(_this._defaultModel);
  81463. if (meshLoaded) {
  81464. meshLoaded(_this._defaultModel);
  81465. }
  81466. });
  81467. };
  81468. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81469. /**
  81470. * Fired when the left button on this controller is modified
  81471. */
  81472. get: function () {
  81473. return this.onMainButtonStateChangedObservable;
  81474. },
  81475. enumerable: true,
  81476. configurable: true
  81477. });
  81478. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81479. /**
  81480. * Fired when the right button on this controller is modified
  81481. */
  81482. get: function () {
  81483. return this.onMainButtonStateChangedObservable;
  81484. },
  81485. enumerable: true,
  81486. configurable: true
  81487. });
  81488. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81489. /**
  81490. * Fired when the menu button on this controller is modified
  81491. */
  81492. get: function () {
  81493. return this.onSecondaryButtonStateChangedObservable;
  81494. },
  81495. enumerable: true,
  81496. configurable: true
  81497. });
  81498. /**
  81499. * Called once for each button that changed state since the last frame
  81500. * Vive mapping:
  81501. * 0: touchpad
  81502. * 1: trigger
  81503. * 2: left AND right buttons
  81504. * 3: menu button
  81505. * @param buttonIdx Which button index changed
  81506. * @param state New state of the button
  81507. * @param changes Which properties on the state changed since last frame
  81508. */
  81509. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81510. var notifyObject = state; //{ state: state, changes: changes };
  81511. switch (buttonIdx) {
  81512. case 0:
  81513. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81514. return;
  81515. case 1: // index trigger
  81516. if (this._defaultModel) {
  81517. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81518. }
  81519. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81520. return;
  81521. case 2: // left AND right button
  81522. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81523. return;
  81524. case 3:
  81525. if (this._defaultModel) {
  81526. if (notifyObject.pressed) {
  81527. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81528. }
  81529. else {
  81530. (this._defaultModel.getChildren()[2]).position.y = 0;
  81531. }
  81532. }
  81533. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81534. return;
  81535. }
  81536. };
  81537. /**
  81538. * Base Url for the controller model.
  81539. */
  81540. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81541. /**
  81542. * File name for the controller model.
  81543. */
  81544. ViveController.MODEL_FILENAME = 'wand.babylon';
  81545. return ViveController;
  81546. }(BABYLON.WebVRController));
  81547. BABYLON.ViveController = ViveController;
  81548. })(BABYLON || (BABYLON = {}));
  81549. //# sourceMappingURL=babylon.viveController.js.map
  81550. var BABYLON;
  81551. (function (BABYLON) {
  81552. /**
  81553. * Generic Controller
  81554. */
  81555. var GenericController = /** @class */ (function (_super) {
  81556. __extends(GenericController, _super);
  81557. /**
  81558. * Creates a new GenericController from a gamepad
  81559. * @param vrGamepad the gamepad that the controller should be created from
  81560. */
  81561. function GenericController(vrGamepad) {
  81562. return _super.call(this, vrGamepad) || this;
  81563. }
  81564. /**
  81565. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81566. * @param scene scene in which to add meshes
  81567. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81568. */
  81569. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81570. var _this = this;
  81571. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81572. _this._defaultModel = newMeshes[1];
  81573. _this.attachToMesh(_this._defaultModel);
  81574. if (meshLoaded) {
  81575. meshLoaded(_this._defaultModel);
  81576. }
  81577. });
  81578. };
  81579. /**
  81580. * Called once for each button that changed state since the last frame
  81581. * @param buttonIdx Which button index changed
  81582. * @param state New state of the button
  81583. * @param changes Which properties on the state changed since last frame
  81584. */
  81585. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81586. console.log("Button id: " + buttonIdx + "state: ");
  81587. console.dir(state);
  81588. };
  81589. /**
  81590. * Base Url for the controller model.
  81591. */
  81592. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81593. /**
  81594. * File name for the controller model.
  81595. */
  81596. GenericController.MODEL_FILENAME = 'generic.babylon';
  81597. return GenericController;
  81598. }(BABYLON.WebVRController));
  81599. BABYLON.GenericController = GenericController;
  81600. })(BABYLON || (BABYLON = {}));
  81601. //# sourceMappingURL=babylon.genericController.js.map
  81602. var BABYLON;
  81603. (function (BABYLON) {
  81604. /**
  81605. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81606. */
  81607. var LoadedMeshInfo = /** @class */ (function () {
  81608. function LoadedMeshInfo() {
  81609. /**
  81610. * Map of the button meshes contained in the controller
  81611. */
  81612. this.buttonMeshes = {};
  81613. /**
  81614. * Map of the axis meshes contained in the controller
  81615. */
  81616. this.axisMeshes = {};
  81617. }
  81618. return LoadedMeshInfo;
  81619. }());
  81620. /**
  81621. * Defines the WindowsMotionController object that the state of the windows motion controller
  81622. */
  81623. var WindowsMotionController = /** @class */ (function (_super) {
  81624. __extends(WindowsMotionController, _super);
  81625. /**
  81626. * Creates a new WindowsMotionController from a gamepad
  81627. * @param vrGamepad the gamepad that the controller should be created from
  81628. */
  81629. function WindowsMotionController(vrGamepad) {
  81630. var _this = _super.call(this, vrGamepad) || this;
  81631. _this._mapping = {
  81632. // Semantic button names
  81633. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81634. // A mapping of the button name to glTF model node name
  81635. // that should be transformed by button value.
  81636. buttonMeshNames: {
  81637. 'trigger': 'SELECT',
  81638. 'menu': 'MENU',
  81639. 'grip': 'GRASP',
  81640. 'thumbstick': 'THUMBSTICK_PRESS',
  81641. 'trackpad': 'TOUCHPAD_PRESS'
  81642. },
  81643. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81644. buttonObservableNames: {
  81645. 'trigger': 'onTriggerStateChangedObservable',
  81646. 'menu': 'onSecondaryButtonStateChangedObservable',
  81647. 'grip': 'onMainButtonStateChangedObservable',
  81648. 'thumbstick': 'onPadStateChangedObservable',
  81649. 'trackpad': 'onTrackpadChangedObservable'
  81650. },
  81651. // A mapping of the axis name to glTF model node name
  81652. // that should be transformed by axis value.
  81653. // This array mirrors the browserGamepad.axes array, such that
  81654. // the mesh corresponding to axis 0 is in this array index 0.
  81655. axisMeshNames: [
  81656. 'THUMBSTICK_X',
  81657. 'THUMBSTICK_Y',
  81658. 'TOUCHPAD_TOUCH_X',
  81659. 'TOUCHPAD_TOUCH_Y'
  81660. ],
  81661. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81662. };
  81663. /**
  81664. * Fired when the trackpad on this controller is clicked
  81665. */
  81666. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81667. /**
  81668. * Fired when the trackpad on this controller is modified
  81669. */
  81670. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81671. /**
  81672. * The current x and y values of this controller's trackpad
  81673. */
  81674. _this.trackpad = { x: 0, y: 0 };
  81675. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81676. _this._loadedMeshInfo = null;
  81677. return _this;
  81678. }
  81679. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81680. /**
  81681. * Fired when the trigger on this controller is modified
  81682. */
  81683. get: function () {
  81684. return this.onTriggerStateChangedObservable;
  81685. },
  81686. enumerable: true,
  81687. configurable: true
  81688. });
  81689. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  81690. /**
  81691. * Fired when the menu button on this controller is modified
  81692. */
  81693. get: function () {
  81694. return this.onSecondaryButtonStateChangedObservable;
  81695. },
  81696. enumerable: true,
  81697. configurable: true
  81698. });
  81699. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  81700. /**
  81701. * Fired when the grip button on this controller is modified
  81702. */
  81703. get: function () {
  81704. return this.onMainButtonStateChangedObservable;
  81705. },
  81706. enumerable: true,
  81707. configurable: true
  81708. });
  81709. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  81710. /**
  81711. * Fired when the thumbstick button on this controller is modified
  81712. */
  81713. get: function () {
  81714. return this.onPadStateChangedObservable;
  81715. },
  81716. enumerable: true,
  81717. configurable: true
  81718. });
  81719. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  81720. /**
  81721. * Fired when the touchpad button on this controller is modified
  81722. */
  81723. get: function () {
  81724. return this.onTrackpadChangedObservable;
  81725. },
  81726. enumerable: true,
  81727. configurable: true
  81728. });
  81729. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  81730. /**
  81731. * Fired when the touchpad values on this controller are modified
  81732. */
  81733. get: function () {
  81734. return this.onTrackpadValuesChangedObservable;
  81735. },
  81736. enumerable: true,
  81737. configurable: true
  81738. });
  81739. WindowsMotionController.prototype._updateTrackpad = function () {
  81740. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  81741. this.trackpad.x = this.browserGamepad["axes"][2];
  81742. this.trackpad.y = this.browserGamepad["axes"][3];
  81743. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  81744. }
  81745. };
  81746. /**
  81747. * Called once per frame by the engine.
  81748. */
  81749. WindowsMotionController.prototype.update = function () {
  81750. _super.prototype.update.call(this);
  81751. if (this.browserGamepad.axes) {
  81752. this._updateTrackpad();
  81753. // Only need to animate axes if there is a loaded mesh
  81754. if (this._loadedMeshInfo) {
  81755. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  81756. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  81757. }
  81758. }
  81759. }
  81760. };
  81761. /**
  81762. * Called once for each button that changed state since the last frame
  81763. * @param buttonIdx Which button index changed
  81764. * @param state New state of the button
  81765. * @param changes Which properties on the state changed since last frame
  81766. */
  81767. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81768. var buttonName = this._mapping.buttons[buttonIdx];
  81769. if (!buttonName) {
  81770. return;
  81771. }
  81772. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  81773. this._updateTrackpad();
  81774. // Only emit events for buttons that we know how to map from index to name
  81775. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  81776. if (observable) {
  81777. observable.notifyObservers(state);
  81778. }
  81779. this._lerpButtonTransform(buttonName, state.value);
  81780. };
  81781. /**
  81782. * Moves the buttons on the controller mesh based on their current state
  81783. * @param buttonName the name of the button to move
  81784. * @param buttonValue the value of the button which determines the buttons new position
  81785. */
  81786. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  81787. // If there is no loaded mesh, there is nothing to transform.
  81788. if (!this._loadedMeshInfo) {
  81789. return;
  81790. }
  81791. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  81792. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  81793. return;
  81794. }
  81795. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  81796. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  81797. };
  81798. /**
  81799. * Moves the axis on the controller mesh based on its current state
  81800. * @param axis the index of the axis
  81801. * @param axisValue the value of the axis which determines the meshes new position
  81802. * @hidden
  81803. */
  81804. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  81805. if (!this._loadedMeshInfo) {
  81806. return;
  81807. }
  81808. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  81809. if (!meshInfo) {
  81810. return;
  81811. }
  81812. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  81813. return;
  81814. }
  81815. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  81816. var lerpValue = axisValue * 0.5 + 0.5;
  81817. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  81818. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  81819. };
  81820. /**
  81821. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81822. * @param scene scene in which to add meshes
  81823. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81824. */
  81825. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  81826. var _this = this;
  81827. if (forceDefault === void 0) { forceDefault = false; }
  81828. var path;
  81829. var filename;
  81830. // Checking if GLB loader is present
  81831. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  81832. // Determine the device specific folder based on the ID suffix
  81833. var device = 'default';
  81834. if (this.id && !forceDefault) {
  81835. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  81836. device = ((match && match[0]) || device);
  81837. }
  81838. // Hand
  81839. if (this.hand === 'left') {
  81840. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  81841. }
  81842. else { // Right is the default if no hand is specified
  81843. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  81844. }
  81845. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  81846. }
  81847. else {
  81848. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  81849. path = BABYLON.GenericController.MODEL_BASE_URL;
  81850. filename = BABYLON.GenericController.MODEL_FILENAME;
  81851. }
  81852. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  81853. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  81854. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  81855. if (!_this._loadedMeshInfo) {
  81856. return;
  81857. }
  81858. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  81859. _this.attachToMesh(_this._defaultModel);
  81860. if (meshLoaded) {
  81861. meshLoaded(_this._defaultModel);
  81862. }
  81863. }, null, function (scene, message) {
  81864. BABYLON.Tools.Log(message);
  81865. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  81866. if (!forceDefault) {
  81867. _this.initControllerMesh(scene, meshLoaded, true);
  81868. }
  81869. });
  81870. };
  81871. /**
  81872. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  81873. * can be transformed by button presses and axes values, based on this._mapping.
  81874. *
  81875. * @param scene scene in which the meshes exist
  81876. * @param meshes list of meshes that make up the controller model to process
  81877. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  81878. */
  81879. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  81880. var loadedMeshInfo = null;
  81881. // Create a new mesh to contain the glTF hierarchy
  81882. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  81883. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  81884. var childMesh = null;
  81885. for (var i = 0; i < meshes.length; i++) {
  81886. var mesh = meshes[i];
  81887. if (!mesh.parent) {
  81888. // Exclude controller meshes from picking results
  81889. mesh.isPickable = false;
  81890. // Handle root node, attach to the new parentMesh
  81891. childMesh = mesh;
  81892. break;
  81893. }
  81894. }
  81895. if (childMesh) {
  81896. childMesh.setParent(parentMesh);
  81897. // Create our mesh info. Note that this method will always return non-null.
  81898. loadedMeshInfo = this.createMeshInfo(parentMesh);
  81899. }
  81900. else {
  81901. BABYLON.Tools.Warn('Could not find root node in model file.');
  81902. }
  81903. return loadedMeshInfo;
  81904. };
  81905. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  81906. var loadedMeshInfo = new LoadedMeshInfo();
  81907. var i;
  81908. loadedMeshInfo.rootNode = rootNode;
  81909. // Reset the caches
  81910. loadedMeshInfo.buttonMeshes = {};
  81911. loadedMeshInfo.axisMeshes = {};
  81912. // Button Meshes
  81913. for (i = 0; i < this._mapping.buttons.length; i++) {
  81914. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81915. if (!buttonMeshName) {
  81916. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81917. continue;
  81918. }
  81919. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81920. if (!buttonMesh) {
  81921. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81922. continue;
  81923. }
  81924. var buttonMeshInfo = {
  81925. index: i,
  81926. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81927. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81928. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81929. };
  81930. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81931. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81932. }
  81933. else {
  81934. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81935. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81936. '(VALUE: ' + !!buttonMeshInfo.value +
  81937. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81938. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81939. ')');
  81940. }
  81941. }
  81942. // Axis Meshes
  81943. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81944. var axisMeshName = this._mapping.axisMeshNames[i];
  81945. if (!axisMeshName) {
  81946. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81947. continue;
  81948. }
  81949. var axisMesh = getChildByName(rootNode, axisMeshName);
  81950. if (!axisMesh) {
  81951. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81952. continue;
  81953. }
  81954. var axisMeshInfo = {
  81955. index: i,
  81956. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81957. min: getImmediateChildByName(axisMesh, 'MIN'),
  81958. max: getImmediateChildByName(axisMesh, 'MAX')
  81959. };
  81960. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81961. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81962. }
  81963. else {
  81964. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81965. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81966. '(VALUE: ' + !!axisMeshInfo.value +
  81967. ', MIN: ' + !!axisMeshInfo.min +
  81968. ', MAX:' + !!axisMeshInfo.max +
  81969. ')');
  81970. }
  81971. }
  81972. // Pointing Ray
  81973. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  81974. if (!loadedMeshInfo.pointingPoseNode) {
  81975. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  81976. }
  81977. else {
  81978. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  81979. }
  81980. return loadedMeshInfo;
  81981. // Look through all children recursively. This will return null if no mesh exists with the given name.
  81982. function getChildByName(node, name) {
  81983. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  81984. }
  81985. // Look through only immediate children. This will return null if no mesh exists with the given name.
  81986. function getImmediateChildByName(node, name) {
  81987. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  81988. }
  81989. };
  81990. /**
  81991. * Gets the ray of the controller in the direction the controller is pointing
  81992. * @param length the length the resulting ray should be
  81993. * @returns a ray in the direction the controller is pointing
  81994. */
  81995. WindowsMotionController.prototype.getForwardRay = function (length) {
  81996. if (length === void 0) { length = 100; }
  81997. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  81998. return _super.prototype.getForwardRay.call(this, length);
  81999. }
  82000. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  82001. var origin = m.getTranslation();
  82002. var forward = new BABYLON.Vector3(0, 0, -1);
  82003. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82004. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82005. return new BABYLON.Ray(origin, direction, length);
  82006. };
  82007. /**
  82008. * Disposes of the controller
  82009. */
  82010. WindowsMotionController.prototype.dispose = function () {
  82011. _super.prototype.dispose.call(this);
  82012. this.onTrackpadChangedObservable.clear();
  82013. };
  82014. /**
  82015. * The base url used to load the left and right controller models
  82016. */
  82017. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82018. /**
  82019. * The name of the left controller model file
  82020. */
  82021. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82022. /**
  82023. * The name of the right controller model file
  82024. */
  82025. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82026. /**
  82027. * The controller name prefix for this controller type
  82028. */
  82029. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82030. /**
  82031. * The controller id pattern for this controller type
  82032. */
  82033. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82034. return WindowsMotionController;
  82035. }(BABYLON.WebVRController));
  82036. BABYLON.WindowsMotionController = WindowsMotionController;
  82037. })(BABYLON || (BABYLON = {}));
  82038. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82039. var BABYLON;
  82040. (function (BABYLON) {
  82041. /**
  82042. * Gear VR Controller
  82043. */
  82044. var GearVRController = /** @class */ (function (_super) {
  82045. __extends(GearVRController, _super);
  82046. /**
  82047. * Creates a new GearVRController from a gamepad
  82048. * @param vrGamepad the gamepad that the controller should be created from
  82049. */
  82050. function GearVRController(vrGamepad) {
  82051. var _this = _super.call(this, vrGamepad) || this;
  82052. _this._buttonIndexToObservableNameMap = [
  82053. 'onTrackpadChangedObservable',
  82054. 'onTriggerStateChangedObservable' // Trigger
  82055. ];
  82056. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82057. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82058. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82059. _this._disableTrackPosition(_this._calculatedPosition);
  82060. return _this;
  82061. }
  82062. /**
  82063. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82064. * @param scene scene in which to add meshes
  82065. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82066. */
  82067. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82068. var _this = this;
  82069. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82070. // Offset the controller so it will rotate around the users wrist
  82071. var mesh = new BABYLON.Mesh("", scene);
  82072. newMeshes[1].parent = mesh;
  82073. newMeshes[1].position.z = -0.15;
  82074. _this._defaultModel = mesh;
  82075. _this.attachToMesh(_this._defaultModel);
  82076. if (meshLoaded) {
  82077. meshLoaded(_this._defaultModel);
  82078. }
  82079. });
  82080. };
  82081. /**
  82082. * Called once for each button that changed state since the last frame
  82083. * @param buttonIdx Which button index changed
  82084. * @param state New state of the button
  82085. * @param changes Which properties on the state changed since last frame
  82086. */
  82087. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82088. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82089. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82090. // Only emit events for buttons that we know how to map from index to observable
  82091. var observable = this[observableName];
  82092. if (observable) {
  82093. observable.notifyObservers(state);
  82094. }
  82095. }
  82096. };
  82097. /**
  82098. * Base Url for the controller model.
  82099. */
  82100. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82101. /**
  82102. * File name for the controller model.
  82103. */
  82104. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82105. /**
  82106. * Gamepad Id prefix used to identify this controller.
  82107. */
  82108. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82109. return GearVRController;
  82110. }(BABYLON.WebVRController));
  82111. BABYLON.GearVRController = GearVRController;
  82112. })(BABYLON || (BABYLON = {}));
  82113. //# sourceMappingURL=babylon.gearVRController.js.map
  82114. var BABYLON;
  82115. (function (BABYLON) {
  82116. /**
  82117. * Google Daydream controller
  82118. */
  82119. var DaydreamController = /** @class */ (function (_super) {
  82120. __extends(DaydreamController, _super);
  82121. /**
  82122. * Creates a new DaydreamController from a gamepad
  82123. * @param vrGamepad the gamepad that the controller should be created from
  82124. */
  82125. function DaydreamController(vrGamepad) {
  82126. var _this = _super.call(this, vrGamepad) || this;
  82127. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82128. return _this;
  82129. }
  82130. /**
  82131. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82132. * @param scene scene in which to add meshes
  82133. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82134. */
  82135. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82136. var _this = this;
  82137. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82138. _this._defaultModel = newMeshes[1];
  82139. _this.attachToMesh(_this._defaultModel);
  82140. if (meshLoaded) {
  82141. meshLoaded(_this._defaultModel);
  82142. }
  82143. });
  82144. };
  82145. /**
  82146. * Called once for each button that changed state since the last frame
  82147. * @param buttonIdx Which button index changed
  82148. * @param state New state of the button
  82149. * @param changes Which properties on the state changed since last frame
  82150. */
  82151. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82152. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82153. if (buttonIdx === 0) {
  82154. var observable = this.onTriggerStateChangedObservable;
  82155. if (observable) {
  82156. observable.notifyObservers(state);
  82157. }
  82158. }
  82159. else {
  82160. // If the app or home buttons are ever made available
  82161. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82162. }
  82163. };
  82164. /**
  82165. * Base Url for the controller model.
  82166. */
  82167. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82168. /**
  82169. * File name for the controller model.
  82170. */
  82171. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82172. /**
  82173. * Gamepad Id prefix used to identify Daydream Controller.
  82174. */
  82175. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82176. return DaydreamController;
  82177. }(BABYLON.WebVRController));
  82178. BABYLON.DaydreamController = DaydreamController;
  82179. })(BABYLON || (BABYLON = {}));
  82180. //# sourceMappingURL=babylon.daydreamController.js.map
  82181. var BABYLON;
  82182. (function (BABYLON) {
  82183. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82184. get: function () {
  82185. if (!this._gamepadManager) {
  82186. this._gamepadManager = new BABYLON.GamepadManager(this);
  82187. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82188. if (!component) {
  82189. component = new GamepadSystemSceneComponent(this);
  82190. this._addComponent(component);
  82191. }
  82192. }
  82193. return this._gamepadManager;
  82194. },
  82195. enumerable: true,
  82196. configurable: true
  82197. });
  82198. /**
  82199. * Adds a gamepad to the free camera inputs manager
  82200. */
  82201. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82202. this.add(new BABYLON.FreeCameraGamepadInput());
  82203. return this;
  82204. };
  82205. /**
  82206. * Adds a gamepad to the arc rotate camera inputs manager
  82207. */
  82208. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82209. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82210. return this;
  82211. };
  82212. /**
  82213. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82214. */
  82215. var GamepadSystemSceneComponent = /** @class */ (function () {
  82216. /**
  82217. * Creates a new instance of the component for the given scene
  82218. * @param scene Defines the scene to register the component in
  82219. */
  82220. function GamepadSystemSceneComponent(scene) {
  82221. /**
  82222. * The component name helpfull to identify the component in the list of scene components.
  82223. */
  82224. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82225. this.scene = scene;
  82226. }
  82227. /**
  82228. * Registers the component in a given scene
  82229. */
  82230. GamepadSystemSceneComponent.prototype.register = function () {
  82231. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82232. };
  82233. /**
  82234. * Rebuilds the elements related to this component in case of
  82235. * context lost for instance.
  82236. */
  82237. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82238. // Nothing to do for gamepads
  82239. };
  82240. /**
  82241. * Disposes the component and the associated ressources
  82242. */
  82243. GamepadSystemSceneComponent.prototype.dispose = function () {
  82244. var gamepadManager = this.scene._gamepadManager;
  82245. if (gamepadManager) {
  82246. gamepadManager.dispose();
  82247. this.scene._gamepadManager = null;
  82248. }
  82249. };
  82250. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82251. var gamepadManager = this.scene._gamepadManager;
  82252. if (gamepadManager && gamepadManager._isMonitoring) {
  82253. gamepadManager._checkGamepadsStatus();
  82254. }
  82255. };
  82256. return GamepadSystemSceneComponent;
  82257. }());
  82258. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82259. })(BABYLON || (BABYLON = {}));
  82260. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82261. var BABYLON;
  82262. (function (BABYLON) {
  82263. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82264. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82265. });
  82266. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82267. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82268. });
  82269. /**
  82270. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82271. * an arc rotate version arcFollowCamera are available.
  82272. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82273. */
  82274. var FollowCamera = /** @class */ (function (_super) {
  82275. __extends(FollowCamera, _super);
  82276. /**
  82277. * Instantiates the follow camera.
  82278. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82279. * @param name Define the name of the camera in the scene
  82280. * @param position Define the position of the camera
  82281. * @param scene Define the scene the camera belong to
  82282. * @param lockedTarget Define the target of the camera
  82283. */
  82284. function FollowCamera(name, position, scene, lockedTarget) {
  82285. if (lockedTarget === void 0) { lockedTarget = null; }
  82286. var _this = _super.call(this, name, position, scene) || this;
  82287. /**
  82288. * Distance the follow camera should follow an object at
  82289. */
  82290. _this.radius = 12;
  82291. /**
  82292. * Define a rotation offset between the camera and the object it follows
  82293. */
  82294. _this.rotationOffset = 0;
  82295. /**
  82296. * Define a height offset between the camera and the object it follows.
  82297. * It can help following an object from the top (like a car chaing a plane)
  82298. */
  82299. _this.heightOffset = 4;
  82300. /**
  82301. * Define how fast the camera can accelerate to follow it s target.
  82302. */
  82303. _this.cameraAcceleration = 0.05;
  82304. /**
  82305. * Define the speed limit of the camera following an object.
  82306. */
  82307. _this.maxCameraSpeed = 20;
  82308. _this.lockedTarget = lockedTarget;
  82309. return _this;
  82310. }
  82311. FollowCamera.prototype._follow = function (cameraTarget) {
  82312. if (!cameraTarget)
  82313. return;
  82314. var yRotation;
  82315. if (cameraTarget.rotationQuaternion) {
  82316. var rotMatrix = new BABYLON.Matrix();
  82317. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82318. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82319. }
  82320. else {
  82321. yRotation = cameraTarget.rotation.y;
  82322. }
  82323. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82324. var targetPosition = cameraTarget.getAbsolutePosition();
  82325. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82326. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82327. var dx = targetX - this.position.x;
  82328. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82329. var dz = (targetZ) - this.position.z;
  82330. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82331. var vy = dy * this.cameraAcceleration;
  82332. var vz = dz * this.cameraAcceleration * 2;
  82333. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82334. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82335. }
  82336. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82337. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82338. }
  82339. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82340. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82341. }
  82342. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82343. this.setTarget(targetPosition);
  82344. };
  82345. /** @hidden */
  82346. FollowCamera.prototype._checkInputs = function () {
  82347. _super.prototype._checkInputs.call(this);
  82348. if (this.lockedTarget) {
  82349. this._follow(this.lockedTarget);
  82350. }
  82351. };
  82352. /**
  82353. * Gets the camera class name.
  82354. * @returns the class name
  82355. */
  82356. FollowCamera.prototype.getClassName = function () {
  82357. return "FollowCamera";
  82358. };
  82359. __decorate([
  82360. BABYLON.serialize()
  82361. ], FollowCamera.prototype, "radius", void 0);
  82362. __decorate([
  82363. BABYLON.serialize()
  82364. ], FollowCamera.prototype, "rotationOffset", void 0);
  82365. __decorate([
  82366. BABYLON.serialize()
  82367. ], FollowCamera.prototype, "heightOffset", void 0);
  82368. __decorate([
  82369. BABYLON.serialize()
  82370. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82371. __decorate([
  82372. BABYLON.serialize()
  82373. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82374. __decorate([
  82375. BABYLON.serializeAsMeshReference("lockedTargetId")
  82376. ], FollowCamera.prototype, "lockedTarget", void 0);
  82377. return FollowCamera;
  82378. }(BABYLON.TargetCamera));
  82379. BABYLON.FollowCamera = FollowCamera;
  82380. /**
  82381. * Arc Rotate version of the follow camera.
  82382. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82383. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82384. */
  82385. var ArcFollowCamera = /** @class */ (function (_super) {
  82386. __extends(ArcFollowCamera, _super);
  82387. /**
  82388. * Instantiates a new ArcFollowCamera
  82389. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82390. * @param name Define the name of the camera
  82391. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82392. * @param beta Define the rotation angle of the camera around the elevation axis
  82393. * @param radius Define the radius of the camera from its target point
  82394. * @param target Define the target of the camera
  82395. * @param scene Define the scene the camera belongs to
  82396. */
  82397. function ArcFollowCamera(name,
  82398. /** The longitudinal angle of the camera */
  82399. alpha,
  82400. /** The latitudinal angle of the camera */
  82401. beta,
  82402. /** The radius of the camera from its target */
  82403. radius,
  82404. /** Define the camera target (the messh it should follow) */
  82405. target, scene) {
  82406. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82407. _this.alpha = alpha;
  82408. _this.beta = beta;
  82409. _this.radius = radius;
  82410. _this.target = target;
  82411. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82412. _this._follow();
  82413. return _this;
  82414. }
  82415. ArcFollowCamera.prototype._follow = function () {
  82416. if (!this.target) {
  82417. return;
  82418. }
  82419. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82420. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82421. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82422. var targetPosition = this.target.getAbsolutePosition();
  82423. this.position = targetPosition.add(this._cartesianCoordinates);
  82424. this.setTarget(targetPosition);
  82425. };
  82426. /** @hidden */
  82427. ArcFollowCamera.prototype._checkInputs = function () {
  82428. _super.prototype._checkInputs.call(this);
  82429. this._follow();
  82430. };
  82431. /**
  82432. * Returns the class name of the object.
  82433. * It is mostly used internally for serialization purposes.
  82434. */
  82435. ArcFollowCamera.prototype.getClassName = function () {
  82436. return "ArcFollowCamera";
  82437. };
  82438. return ArcFollowCamera;
  82439. }(BABYLON.TargetCamera));
  82440. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82441. })(BABYLON || (BABYLON = {}));
  82442. //# sourceMappingURL=babylon.followCamera.js.map
  82443. var BABYLON;
  82444. (function (BABYLON) {
  82445. /**
  82446. * 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,
  82447. * which still works and will still be found in many Playgrounds.
  82448. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82449. */
  82450. var UniversalCamera = /** @class */ (function (_super) {
  82451. __extends(UniversalCamera, _super);
  82452. /**
  82453. * 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,
  82454. * which still works and will still be found in many Playgrounds.
  82455. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82456. * @param name Define the name of the camera in the scene
  82457. * @param position Define the start position of the camera in the scene
  82458. * @param scene Define the scene the camera belongs to
  82459. */
  82460. function UniversalCamera(name, position, scene) {
  82461. var _this = _super.call(this, name, position, scene) || this;
  82462. _this.inputs.addGamepad();
  82463. return _this;
  82464. }
  82465. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82466. /**
  82467. * Defines the gamepad rotation sensiblity.
  82468. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82469. */
  82470. get: function () {
  82471. var gamepad = this.inputs.attached["gamepad"];
  82472. if (gamepad)
  82473. return gamepad.gamepadAngularSensibility;
  82474. return 0;
  82475. },
  82476. set: function (value) {
  82477. var gamepad = this.inputs.attached["gamepad"];
  82478. if (gamepad)
  82479. gamepad.gamepadAngularSensibility = value;
  82480. },
  82481. enumerable: true,
  82482. configurable: true
  82483. });
  82484. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82485. /**
  82486. * Defines the gamepad move sensiblity.
  82487. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82488. */
  82489. get: function () {
  82490. var gamepad = this.inputs.attached["gamepad"];
  82491. if (gamepad)
  82492. return gamepad.gamepadMoveSensibility;
  82493. return 0;
  82494. },
  82495. set: function (value) {
  82496. var gamepad = this.inputs.attached["gamepad"];
  82497. if (gamepad)
  82498. gamepad.gamepadMoveSensibility = value;
  82499. },
  82500. enumerable: true,
  82501. configurable: true
  82502. });
  82503. /**
  82504. * Gets the current object class name.
  82505. * @return the class name
  82506. */
  82507. UniversalCamera.prototype.getClassName = function () {
  82508. return "UniversalCamera";
  82509. };
  82510. return UniversalCamera;
  82511. }(BABYLON.TouchCamera));
  82512. BABYLON.UniversalCamera = UniversalCamera;
  82513. })(BABYLON || (BABYLON = {}));
  82514. //# sourceMappingURL=babylon.universalCamera.js.map
  82515. var BABYLON;
  82516. (function (BABYLON) {
  82517. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82518. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82519. });
  82520. /**
  82521. * This represents a FPS type of camera. This is only here for back compat purpose.
  82522. * Please use the UniversalCamera instead as both are identical.
  82523. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82524. */
  82525. var GamepadCamera = /** @class */ (function (_super) {
  82526. __extends(GamepadCamera, _super);
  82527. /**
  82528. * Instantiates a new Gamepad Camera
  82529. * This represents a FPS type of camera. This is only here for back compat purpose.
  82530. * Please use the UniversalCamera instead as both are identical.
  82531. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82532. * @param name Define the name of the camera in the scene
  82533. * @param position Define the start position of the camera in the scene
  82534. * @param scene Define the scene the camera belongs to
  82535. */
  82536. function GamepadCamera(name, position, scene) {
  82537. return _super.call(this, name, position, scene) || this;
  82538. }
  82539. /**
  82540. * Gets the current object class name.
  82541. * @return the class name
  82542. */
  82543. GamepadCamera.prototype.getClassName = function () {
  82544. return "GamepadCamera";
  82545. };
  82546. return GamepadCamera;
  82547. }(BABYLON.UniversalCamera));
  82548. BABYLON.GamepadCamera = GamepadCamera;
  82549. })(BABYLON || (BABYLON = {}));
  82550. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82551. var BABYLON;
  82552. (function (BABYLON) {
  82553. /**
  82554. * PostProcessRenderPipelineManager class
  82555. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82556. */
  82557. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82558. /**
  82559. * Initializes a PostProcessRenderPipelineManager
  82560. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82561. */
  82562. function PostProcessRenderPipelineManager() {
  82563. this._renderPipelines = {};
  82564. }
  82565. /**
  82566. * Adds a pipeline to the manager
  82567. * @param renderPipeline The pipeline to add
  82568. */
  82569. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82570. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82571. };
  82572. /**
  82573. * Attaches a camera to the pipeline
  82574. * @param renderPipelineName The name of the pipeline to attach to
  82575. * @param cameras the camera to attach
  82576. * @param unique if the camera can be attached multiple times to the pipeline
  82577. */
  82578. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82579. if (unique === void 0) { unique = false; }
  82580. var renderPipeline = this._renderPipelines[renderPipelineName];
  82581. if (!renderPipeline) {
  82582. return;
  82583. }
  82584. renderPipeline._attachCameras(cameras, unique);
  82585. };
  82586. /**
  82587. * Detaches a camera from the pipeline
  82588. * @param renderPipelineName The name of the pipeline to detach from
  82589. * @param cameras the camera to detach
  82590. */
  82591. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82592. var renderPipeline = this._renderPipelines[renderPipelineName];
  82593. if (!renderPipeline) {
  82594. return;
  82595. }
  82596. renderPipeline._detachCameras(cameras);
  82597. };
  82598. /**
  82599. * Enables an effect by name on a pipeline
  82600. * @param renderPipelineName the name of the pipeline to enable the effect in
  82601. * @param renderEffectName the name of the effect to enable
  82602. * @param cameras the cameras that the effect should be enabled on
  82603. */
  82604. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82605. var renderPipeline = this._renderPipelines[renderPipelineName];
  82606. if (!renderPipeline) {
  82607. return;
  82608. }
  82609. renderPipeline._enableEffect(renderEffectName, cameras);
  82610. };
  82611. /**
  82612. * Disables an effect by name on a pipeline
  82613. * @param renderPipelineName the name of the pipeline to disable the effect in
  82614. * @param renderEffectName the name of the effect to disable
  82615. * @param cameras the cameras that the effect should be disabled on
  82616. */
  82617. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82618. var renderPipeline = this._renderPipelines[renderPipelineName];
  82619. if (!renderPipeline) {
  82620. return;
  82621. }
  82622. renderPipeline._disableEffect(renderEffectName, cameras);
  82623. };
  82624. /**
  82625. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82626. */
  82627. PostProcessRenderPipelineManager.prototype.update = function () {
  82628. for (var renderPipelineName in this._renderPipelines) {
  82629. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82630. var pipeline = this._renderPipelines[renderPipelineName];
  82631. if (!pipeline.isSupported) {
  82632. pipeline.dispose();
  82633. delete this._renderPipelines[renderPipelineName];
  82634. }
  82635. else {
  82636. pipeline._update();
  82637. }
  82638. }
  82639. }
  82640. };
  82641. /** @hidden */
  82642. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82643. for (var renderPipelineName in this._renderPipelines) {
  82644. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82645. var pipeline = this._renderPipelines[renderPipelineName];
  82646. pipeline._rebuild();
  82647. }
  82648. }
  82649. };
  82650. /**
  82651. * Disposes of the manager and pipelines
  82652. */
  82653. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82654. for (var renderPipelineName in this._renderPipelines) {
  82655. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82656. var pipeline = this._renderPipelines[renderPipelineName];
  82657. pipeline.dispose();
  82658. }
  82659. }
  82660. };
  82661. return PostProcessRenderPipelineManager;
  82662. }());
  82663. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82664. })(BABYLON || (BABYLON = {}));
  82665. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82666. var BABYLON;
  82667. (function (BABYLON) {
  82668. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82669. get: function () {
  82670. if (!this._postProcessRenderPipelineManager) {
  82671. // Register the G Buffer component to the scene.
  82672. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82673. if (!component) {
  82674. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82675. this._addComponent(component);
  82676. }
  82677. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82678. }
  82679. return this._postProcessRenderPipelineManager;
  82680. },
  82681. enumerable: true,
  82682. configurable: true
  82683. });
  82684. /**
  82685. * Defines the Render Pipeline scene component responsible to rendering pipelines
  82686. */
  82687. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  82688. /**
  82689. * Creates a new instance of the component for the given scene
  82690. * @param scene Defines the scene to register the component in
  82691. */
  82692. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  82693. /**
  82694. * The component name helpfull to identify the component in the list of scene components.
  82695. */
  82696. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  82697. this.scene = scene;
  82698. }
  82699. /**
  82700. * Registers the component in a given scene
  82701. */
  82702. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  82703. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  82704. };
  82705. /**
  82706. * Rebuilds the elements related to this component in case of
  82707. * context lost for instance.
  82708. */
  82709. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  82710. if (this.scene._postProcessRenderPipelineManager) {
  82711. this.scene._postProcessRenderPipelineManager._rebuild();
  82712. }
  82713. };
  82714. /**
  82715. * Disposes the component and the associated ressources
  82716. */
  82717. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  82718. if (this.scene._postProcessRenderPipelineManager) {
  82719. this.scene._postProcessRenderPipelineManager.dispose();
  82720. }
  82721. };
  82722. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82723. if (this.scene._postProcessRenderPipelineManager) {
  82724. this.scene._postProcessRenderPipelineManager.update();
  82725. }
  82726. };
  82727. return PostProcessRenderPipelineManagerSceneComponent;
  82728. }());
  82729. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  82730. })(BABYLON || (BABYLON = {}));
  82731. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  82732. var BABYLON;
  82733. (function (BABYLON) {
  82734. /**
  82735. * This represents a set of one or more post processes in Babylon.
  82736. * A post process can be used to apply a shader to a texture after it is rendered.
  82737. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82738. */
  82739. var PostProcessRenderEffect = /** @class */ (function () {
  82740. /**
  82741. * Instantiates a post process render effect.
  82742. * A post process can be used to apply a shader to a texture after it is rendered.
  82743. * @param engine The engine the effect is tied to
  82744. * @param name The name of the effect
  82745. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  82746. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  82747. */
  82748. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  82749. this._name = name;
  82750. this._singleInstance = singleInstance || true;
  82751. this._getPostProcesses = getPostProcesses;
  82752. this._cameras = {};
  82753. this._indicesForCamera = {};
  82754. this._postProcesses = {};
  82755. }
  82756. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  82757. /**
  82758. * Checks if all the post processes in the effect are supported.
  82759. */
  82760. get: function () {
  82761. for (var index in this._postProcesses) {
  82762. if (this._postProcesses.hasOwnProperty(index)) {
  82763. var pps = this._postProcesses[index];
  82764. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  82765. if (!pps[ppIndex].isSupported) {
  82766. return false;
  82767. }
  82768. }
  82769. }
  82770. }
  82771. return true;
  82772. },
  82773. enumerable: true,
  82774. configurable: true
  82775. });
  82776. /**
  82777. * Updates the current state of the effect
  82778. * @hidden
  82779. */
  82780. PostProcessRenderEffect.prototype._update = function () {
  82781. };
  82782. /**
  82783. * Attaches the effect on cameras
  82784. * @param cameras The camera to attach to.
  82785. * @hidden
  82786. */
  82787. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  82788. var _this = this;
  82789. var cameraKey;
  82790. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82791. if (!cams) {
  82792. return;
  82793. }
  82794. for (var i = 0; i < cams.length; i++) {
  82795. var camera = cams[i];
  82796. var cameraName = camera.name;
  82797. if (this._singleInstance) {
  82798. cameraKey = 0;
  82799. }
  82800. else {
  82801. cameraKey = cameraName;
  82802. }
  82803. if (!this._postProcesses[cameraKey]) {
  82804. var postProcess = this._getPostProcesses();
  82805. if (postProcess) {
  82806. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  82807. }
  82808. }
  82809. if (!this._indicesForCamera[cameraName]) {
  82810. this._indicesForCamera[cameraName] = [];
  82811. }
  82812. this._postProcesses[cameraKey].forEach(function (postProcess) {
  82813. var index = camera.attachPostProcess(postProcess);
  82814. _this._indicesForCamera[cameraName].push(index);
  82815. });
  82816. if (!this._cameras[cameraName]) {
  82817. this._cameras[cameraName] = camera;
  82818. }
  82819. }
  82820. };
  82821. /**
  82822. * Detatches the effect on cameras
  82823. * @param cameras The camera to detatch from.
  82824. * @hidden
  82825. */
  82826. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  82827. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82828. if (!cams) {
  82829. return;
  82830. }
  82831. for (var i = 0; i < cams.length; i++) {
  82832. var camera = cams[i];
  82833. var cameraName = camera.name;
  82834. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82835. camera.detachPostProcess(postProcess);
  82836. });
  82837. if (this._cameras[cameraName]) {
  82838. //this._indicesForCamera.splice(index, 1);
  82839. this._cameras[cameraName] = null;
  82840. }
  82841. }
  82842. };
  82843. /**
  82844. * Enables the effect on given cameras
  82845. * @param cameras The camera to enable.
  82846. * @hidden
  82847. */
  82848. PostProcessRenderEffect.prototype._enable = function (cameras) {
  82849. var _this = this;
  82850. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82851. if (!cams) {
  82852. return;
  82853. }
  82854. for (var i = 0; i < cams.length; i++) {
  82855. var camera = cams[i];
  82856. var cameraName = camera.name;
  82857. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  82858. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  82859. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82860. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  82861. });
  82862. }
  82863. }
  82864. }
  82865. };
  82866. /**
  82867. * Disables the effect on the given cameras
  82868. * @param cameras The camera to disable.
  82869. * @hidden
  82870. */
  82871. PostProcessRenderEffect.prototype._disable = function (cameras) {
  82872. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82873. if (!cams) {
  82874. return;
  82875. }
  82876. for (var i = 0; i < cams.length; i++) {
  82877. var camera = cams[i];
  82878. var cameraName = camera.name;
  82879. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82880. camera.detachPostProcess(postProcess);
  82881. });
  82882. }
  82883. };
  82884. /**
  82885. * Gets a list of the post processes contained in the effect.
  82886. * @param camera The camera to get the post processes on.
  82887. * @returns The list of the post processes in the effect.
  82888. */
  82889. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  82890. if (this._singleInstance) {
  82891. return this._postProcesses[0];
  82892. }
  82893. else {
  82894. if (!camera) {
  82895. return null;
  82896. }
  82897. return this._postProcesses[camera.name];
  82898. }
  82899. };
  82900. return PostProcessRenderEffect;
  82901. }());
  82902. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  82903. })(BABYLON || (BABYLON = {}));
  82904. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  82905. var BABYLON;
  82906. (function (BABYLON) {
  82907. /**
  82908. * PostProcessRenderPipeline
  82909. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82910. */
  82911. var PostProcessRenderPipeline = /** @class */ (function () {
  82912. /**
  82913. * Initializes a PostProcessRenderPipeline
  82914. * @param engine engine to add the pipeline to
  82915. * @param name name of the pipeline
  82916. */
  82917. function PostProcessRenderPipeline(engine, name) {
  82918. this.engine = engine;
  82919. this._name = name;
  82920. this._renderEffects = {};
  82921. this._renderEffectsForIsolatedPass = new Array();
  82922. this._cameras = [];
  82923. }
  82924. /**
  82925. * "PostProcessRenderPipeline"
  82926. * @returns "PostProcessRenderPipeline"
  82927. */
  82928. PostProcessRenderPipeline.prototype.getClassName = function () {
  82929. return "PostProcessRenderPipeline";
  82930. };
  82931. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82932. /**
  82933. * If all the render effects in the pipeline are support
  82934. */
  82935. get: function () {
  82936. for (var renderEffectName in this._renderEffects) {
  82937. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82938. if (!this._renderEffects[renderEffectName].isSupported) {
  82939. return false;
  82940. }
  82941. }
  82942. }
  82943. return true;
  82944. },
  82945. enumerable: true,
  82946. configurable: true
  82947. });
  82948. /**
  82949. * Adds an effect to the pipeline
  82950. * @param renderEffect the effect to add
  82951. */
  82952. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82953. this._renderEffects[renderEffect._name] = renderEffect;
  82954. };
  82955. // private
  82956. /** @hidden */
  82957. PostProcessRenderPipeline.prototype._rebuild = function () {
  82958. };
  82959. /** @hidden */
  82960. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82961. var renderEffects = this._renderEffects[renderEffectName];
  82962. if (!renderEffects) {
  82963. return;
  82964. }
  82965. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82966. };
  82967. /** @hidden */
  82968. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82969. var renderEffects = this._renderEffects[renderEffectName];
  82970. if (!renderEffects) {
  82971. return;
  82972. }
  82973. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82974. };
  82975. /** @hidden */
  82976. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  82977. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82978. if (!cams) {
  82979. return;
  82980. }
  82981. var indicesToDelete = [];
  82982. var i;
  82983. for (i = 0; i < cams.length; i++) {
  82984. var camera = cams[i];
  82985. var cameraName = camera.name;
  82986. if (this._cameras.indexOf(camera) === -1) {
  82987. this._cameras[cameraName] = camera;
  82988. }
  82989. else if (unique) {
  82990. indicesToDelete.push(i);
  82991. }
  82992. }
  82993. for (i = 0; i < indicesToDelete.length; i++) {
  82994. cameras.splice(indicesToDelete[i], 1);
  82995. }
  82996. for (var renderEffectName in this._renderEffects) {
  82997. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82998. this._renderEffects[renderEffectName]._attachCameras(cams);
  82999. }
  83000. }
  83001. };
  83002. /** @hidden */
  83003. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  83004. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83005. if (!cams) {
  83006. return;
  83007. }
  83008. for (var renderEffectName in this._renderEffects) {
  83009. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83010. this._renderEffects[renderEffectName]._detachCameras(cams);
  83011. }
  83012. }
  83013. for (var i = 0; i < cams.length; i++) {
  83014. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  83015. }
  83016. };
  83017. /** @hidden */
  83018. PostProcessRenderPipeline.prototype._update = function () {
  83019. for (var renderEffectName in this._renderEffects) {
  83020. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83021. this._renderEffects[renderEffectName]._update();
  83022. }
  83023. }
  83024. for (var i = 0; i < this._cameras.length; i++) {
  83025. var cameraName = this._cameras[i].name;
  83026. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83027. this._renderEffectsForIsolatedPass[cameraName]._update();
  83028. }
  83029. }
  83030. };
  83031. /** @hidden */
  83032. PostProcessRenderPipeline.prototype._reset = function () {
  83033. this._renderEffects = {};
  83034. this._renderEffectsForIsolatedPass = new Array();
  83035. };
  83036. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83037. // 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)
  83038. var effectKeys = Object.keys(this._renderEffects);
  83039. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83040. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83041. if (postProcesses) {
  83042. postProcesses[0].samples = sampleCount;
  83043. return true;
  83044. }
  83045. }
  83046. return false;
  83047. };
  83048. /**
  83049. * Disposes of the pipeline
  83050. */
  83051. PostProcessRenderPipeline.prototype.dispose = function () {
  83052. // Must be implemented by children
  83053. };
  83054. __decorate([
  83055. BABYLON.serialize()
  83056. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83057. return PostProcessRenderPipeline;
  83058. }());
  83059. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83060. })(BABYLON || (BABYLON = {}));
  83061. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83062. var BABYLON;
  83063. (function (BABYLON) {
  83064. /**
  83065. * This represents a depth renderer in Babylon.
  83066. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83067. */
  83068. var DepthRenderer = /** @class */ (function () {
  83069. /**
  83070. * Instantiates a depth renderer
  83071. * @param scene The scene the renderer belongs to
  83072. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83073. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83074. */
  83075. function DepthRenderer(scene, type, camera) {
  83076. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83077. if (camera === void 0) { camera = null; }
  83078. var _this = this;
  83079. /**
  83080. * Specifiess that the depth renderer will only be used within
  83081. * the camera it is created for.
  83082. * This can help forcing its rendering during the camera processing.
  83083. */
  83084. this.useOnlyInActiveCamera = false;
  83085. this._scene = scene;
  83086. // Register the G Buffer component to the scene.
  83087. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83088. if (!component) {
  83089. component = new BABYLON.DepthRendererSceneComponent(scene);
  83090. scene._addComponent(component);
  83091. }
  83092. this._camera = camera;
  83093. var engine = scene.getEngine();
  83094. // Render target
  83095. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83096. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83097. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83098. this._depthMap.refreshRate = 1;
  83099. this._depthMap.renderParticles = false;
  83100. this._depthMap.renderList = null;
  83101. // Camera to get depth map from to support multiple concurrent cameras
  83102. this._depthMap.activeCamera = this._camera;
  83103. this._depthMap.ignoreCameraViewport = true;
  83104. this._depthMap.useCameraPostProcesses = false;
  83105. // set default depth value to 1.0 (far away)
  83106. this._depthMap.onClearObservable.add(function (engine) {
  83107. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83108. });
  83109. // Custom render function
  83110. var renderSubMesh = function (subMesh) {
  83111. var mesh = subMesh.getRenderingMesh();
  83112. var scene = _this._scene;
  83113. var engine = scene.getEngine();
  83114. var material = subMesh.getMaterial();
  83115. if (!material) {
  83116. return;
  83117. }
  83118. // Culling and reverse (right handed system)
  83119. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83120. // Managing instances
  83121. var batch = mesh._getInstancesRenderList(subMesh._id);
  83122. if (batch.mustReturn) {
  83123. return;
  83124. }
  83125. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83126. var camera = _this._camera || scene.activeCamera;
  83127. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83128. engine.enableEffect(_this._effect);
  83129. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83130. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83131. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83132. // Alpha test
  83133. if (material && material.needAlphaTesting()) {
  83134. var alphaTexture = material.getAlphaTestTexture();
  83135. if (alphaTexture) {
  83136. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83137. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83138. }
  83139. }
  83140. // Bones
  83141. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83142. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83143. }
  83144. // Draw
  83145. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83146. }
  83147. };
  83148. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83149. var index;
  83150. if (depthOnlySubMeshes.length) {
  83151. engine.setColorWrite(false);
  83152. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83153. renderSubMesh(depthOnlySubMeshes.data[index]);
  83154. }
  83155. engine.setColorWrite(true);
  83156. }
  83157. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83158. renderSubMesh(opaqueSubMeshes.data[index]);
  83159. }
  83160. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83161. renderSubMesh(alphaTestSubMeshes.data[index]);
  83162. }
  83163. };
  83164. }
  83165. /**
  83166. * Creates the depth rendering effect and checks if the effect is ready.
  83167. * @param subMesh The submesh to be used to render the depth map of
  83168. * @param useInstances If multiple world instances should be used
  83169. * @returns if the depth renderer is ready to render the depth map
  83170. */
  83171. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83172. var material = subMesh.getMaterial();
  83173. if (material.disableDepthWrite) {
  83174. return false;
  83175. }
  83176. var defines = [];
  83177. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83178. var mesh = subMesh.getMesh();
  83179. // Alpha test
  83180. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83181. defines.push("#define ALPHATEST");
  83182. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83183. attribs.push(BABYLON.VertexBuffer.UVKind);
  83184. defines.push("#define UV1");
  83185. }
  83186. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83187. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83188. defines.push("#define UV2");
  83189. }
  83190. }
  83191. // Bones
  83192. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83193. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83194. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83195. if (mesh.numBoneInfluencers > 4) {
  83196. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83197. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83198. }
  83199. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83200. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83201. }
  83202. else {
  83203. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83204. }
  83205. // Instances
  83206. if (useInstances) {
  83207. defines.push("#define INSTANCES");
  83208. attribs.push("world0");
  83209. attribs.push("world1");
  83210. attribs.push("world2");
  83211. attribs.push("world3");
  83212. }
  83213. // Get correct effect
  83214. var join = defines.join("\n");
  83215. if (this._cachedDefines !== join) {
  83216. this._cachedDefines = join;
  83217. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83218. }
  83219. return this._effect.isReady();
  83220. };
  83221. /**
  83222. * Gets the texture which the depth map will be written to.
  83223. * @returns The depth map texture
  83224. */
  83225. DepthRenderer.prototype.getDepthMap = function () {
  83226. return this._depthMap;
  83227. };
  83228. /**
  83229. * Disposes of the depth renderer.
  83230. */
  83231. DepthRenderer.prototype.dispose = function () {
  83232. this._depthMap.dispose();
  83233. };
  83234. return DepthRenderer;
  83235. }());
  83236. BABYLON.DepthRenderer = DepthRenderer;
  83237. })(BABYLON || (BABYLON = {}));
  83238. //# sourceMappingURL=babylon.depthRenderer.js.map
  83239. var BABYLON;
  83240. (function (BABYLON) {
  83241. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83242. camera = camera || this.activeCamera;
  83243. if (!camera) {
  83244. throw "No camera available to enable depth renderer";
  83245. }
  83246. if (!this._depthRenderer) {
  83247. this._depthRenderer = {};
  83248. }
  83249. if (!this._depthRenderer[camera.id]) {
  83250. var textureType = 0;
  83251. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83252. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83253. }
  83254. else if (this.getEngine().getCaps().textureFloatRender) {
  83255. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83256. }
  83257. else {
  83258. throw "Depth renderer does not support int texture type";
  83259. }
  83260. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83261. }
  83262. return this._depthRenderer[camera.id];
  83263. };
  83264. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83265. camera = camera || this.activeCamera;
  83266. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83267. return;
  83268. }
  83269. this._depthRenderer[camera.id].dispose();
  83270. delete this._depthRenderer[camera.id];
  83271. };
  83272. /**
  83273. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83274. * in several rendering techniques.
  83275. */
  83276. var DepthRendererSceneComponent = /** @class */ (function () {
  83277. /**
  83278. * Creates a new instance of the component for the given scene
  83279. * @param scene Defines the scene to register the component in
  83280. */
  83281. function DepthRendererSceneComponent(scene) {
  83282. /**
  83283. * The component name helpfull to identify the component in the list of scene components.
  83284. */
  83285. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83286. this.scene = scene;
  83287. }
  83288. /**
  83289. * Registers the component in a given scene
  83290. */
  83291. DepthRendererSceneComponent.prototype.register = function () {
  83292. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83293. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83294. };
  83295. /**
  83296. * Rebuilds the elements related to this component in case of
  83297. * context lost for instance.
  83298. */
  83299. DepthRendererSceneComponent.prototype.rebuild = function () {
  83300. // Nothing to do for this component
  83301. };
  83302. /**
  83303. * Disposes the component and the associated ressources
  83304. */
  83305. DepthRendererSceneComponent.prototype.dispose = function () {
  83306. for (var key in this.scene._depthRenderer) {
  83307. this.scene._depthRenderer[key].dispose();
  83308. }
  83309. };
  83310. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83311. if (this.scene._depthRenderer) {
  83312. for (var key in this.scene._depthRenderer) {
  83313. var depthRenderer = this.scene._depthRenderer[key];
  83314. if (!depthRenderer.useOnlyInActiveCamera) {
  83315. renderTargets.push(depthRenderer.getDepthMap());
  83316. }
  83317. }
  83318. }
  83319. };
  83320. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83321. if (this.scene._depthRenderer) {
  83322. for (var key in this.scene._depthRenderer) {
  83323. var depthRenderer = this.scene._depthRenderer[key];
  83324. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83325. renderTargets.push(depthRenderer.getDepthMap());
  83326. }
  83327. }
  83328. }
  83329. };
  83330. return DepthRendererSceneComponent;
  83331. }());
  83332. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83333. })(BABYLON || (BABYLON = {}));
  83334. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83335. var BABYLON;
  83336. (function (BABYLON) {
  83337. /**
  83338. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83339. */
  83340. var GeometryBufferRenderer = /** @class */ (function () {
  83341. /**
  83342. * Creates a new G Buffer for the scene
  83343. * @param scene The scene the buffer belongs to
  83344. * @param ratio How big is the buffer related to the main canvas.
  83345. */
  83346. function GeometryBufferRenderer(scene, ratio) {
  83347. if (ratio === void 0) { ratio = 1; }
  83348. this._enablePosition = false;
  83349. this._scene = scene;
  83350. this._ratio = ratio;
  83351. // Register the G Buffer component to the scene.
  83352. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83353. if (!component) {
  83354. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83355. scene._addComponent(component);
  83356. }
  83357. // Render target
  83358. this._createRenderTargets();
  83359. }
  83360. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83361. /**
  83362. * Set the render list (meshes to be rendered) used in the G buffer.
  83363. */
  83364. set: function (meshes) {
  83365. this._multiRenderTarget.renderList = meshes;
  83366. },
  83367. enumerable: true,
  83368. configurable: true
  83369. });
  83370. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83371. /**
  83372. * Gets wether or not G buffer are supported by the running hardware.
  83373. * This requires draw buffer supports
  83374. */
  83375. get: function () {
  83376. return this._multiRenderTarget.isSupported;
  83377. },
  83378. enumerable: true,
  83379. configurable: true
  83380. });
  83381. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83382. /**
  83383. * Gets wether or not position are enabled for the G buffer.
  83384. */
  83385. get: function () {
  83386. return this._enablePosition;
  83387. },
  83388. /**
  83389. * Sets wether or not position are enabled for the G buffer.
  83390. */
  83391. set: function (enable) {
  83392. this._enablePosition = enable;
  83393. this.dispose();
  83394. this._createRenderTargets();
  83395. },
  83396. enumerable: true,
  83397. configurable: true
  83398. });
  83399. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83400. /**
  83401. * Gets the scene associated with the buffer.
  83402. */
  83403. get: function () {
  83404. return this._scene;
  83405. },
  83406. enumerable: true,
  83407. configurable: true
  83408. });
  83409. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83410. /**
  83411. * Gets the ratio used by the buffer during its creation.
  83412. * How big is the buffer related to the main canvas.
  83413. */
  83414. get: function () {
  83415. return this._ratio;
  83416. },
  83417. enumerable: true,
  83418. configurable: true
  83419. });
  83420. /**
  83421. * Checks wether everything is ready to render a submesh to the G buffer.
  83422. * @param subMesh the submesh to check readiness for
  83423. * @param useInstances is the mesh drawn using instance or not
  83424. * @returns true if ready otherwise false
  83425. */
  83426. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83427. var material = subMesh.getMaterial();
  83428. if (material && material.disableDepthWrite) {
  83429. return false;
  83430. }
  83431. var defines = [];
  83432. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83433. var mesh = subMesh.getMesh();
  83434. // Alpha test
  83435. if (material && material.needAlphaTesting()) {
  83436. defines.push("#define ALPHATEST");
  83437. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83438. attribs.push(BABYLON.VertexBuffer.UVKind);
  83439. defines.push("#define UV1");
  83440. }
  83441. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83442. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83443. defines.push("#define UV2");
  83444. }
  83445. }
  83446. // Buffers
  83447. if (this._enablePosition) {
  83448. defines.push("#define POSITION");
  83449. }
  83450. // Bones
  83451. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83454. if (mesh.numBoneInfluencers > 4) {
  83455. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83456. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83457. }
  83458. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83459. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83460. }
  83461. else {
  83462. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83463. }
  83464. // Instances
  83465. if (useInstances) {
  83466. defines.push("#define INSTANCES");
  83467. attribs.push("world0");
  83468. attribs.push("world1");
  83469. attribs.push("world2");
  83470. attribs.push("world3");
  83471. }
  83472. // Get correct effect
  83473. var join = defines.join("\n");
  83474. if (this._cachedDefines !== join) {
  83475. this._cachedDefines = join;
  83476. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83477. }
  83478. return this._effect.isReady();
  83479. };
  83480. /**
  83481. * Gets the current underlying G Buffer.
  83482. * @returns the buffer
  83483. */
  83484. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83485. return this._multiRenderTarget;
  83486. };
  83487. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83488. /**
  83489. * Gets the number of samples used to render the buffer (anti aliasing).
  83490. */
  83491. get: function () {
  83492. return this._multiRenderTarget.samples;
  83493. },
  83494. /**
  83495. * Sets the number of samples used to render the buffer (anti aliasing).
  83496. */
  83497. set: function (value) {
  83498. this._multiRenderTarget.samples = value;
  83499. },
  83500. enumerable: true,
  83501. configurable: true
  83502. });
  83503. /**
  83504. * Disposes the renderer and frees up associated resources.
  83505. */
  83506. GeometryBufferRenderer.prototype.dispose = function () {
  83507. this.getGBuffer().dispose();
  83508. };
  83509. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83510. var _this = this;
  83511. var engine = this._scene.getEngine();
  83512. var count = this._enablePosition ? 3 : 2;
  83513. 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 });
  83514. if (!this.isSupported) {
  83515. return;
  83516. }
  83517. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83518. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83519. this._multiRenderTarget.refreshRate = 1;
  83520. this._multiRenderTarget.renderParticles = false;
  83521. this._multiRenderTarget.renderList = null;
  83522. // set default depth value to 1.0 (far away)
  83523. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83524. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83525. });
  83526. // Custom render function
  83527. var renderSubMesh = function (subMesh) {
  83528. var mesh = subMesh.getRenderingMesh();
  83529. var scene = _this._scene;
  83530. var engine = scene.getEngine();
  83531. var material = subMesh.getMaterial();
  83532. if (!material) {
  83533. return;
  83534. }
  83535. // Culling
  83536. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83537. // Managing instances
  83538. var batch = mesh._getInstancesRenderList(subMesh._id);
  83539. if (batch.mustReturn) {
  83540. return;
  83541. }
  83542. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83543. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83544. engine.enableEffect(_this._effect);
  83545. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83546. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83547. _this._effect.setMatrix("view", scene.getViewMatrix());
  83548. // Alpha test
  83549. if (material && material.needAlphaTesting()) {
  83550. var alphaTexture = material.getAlphaTestTexture();
  83551. if (alphaTexture) {
  83552. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83553. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83554. }
  83555. }
  83556. // Bones
  83557. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83558. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83559. }
  83560. // Draw
  83561. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83562. }
  83563. };
  83564. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83565. var index;
  83566. if (depthOnlySubMeshes.length) {
  83567. engine.setColorWrite(false);
  83568. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83569. renderSubMesh(depthOnlySubMeshes.data[index]);
  83570. }
  83571. engine.setColorWrite(true);
  83572. }
  83573. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83574. renderSubMesh(opaqueSubMeshes.data[index]);
  83575. }
  83576. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83577. renderSubMesh(alphaTestSubMeshes.data[index]);
  83578. }
  83579. };
  83580. };
  83581. return GeometryBufferRenderer;
  83582. }());
  83583. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83584. })(BABYLON || (BABYLON = {}));
  83585. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83586. var BABYLON;
  83587. (function (BABYLON) {
  83588. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83589. get: function () {
  83590. this._geometryBufferRenderer;
  83591. },
  83592. set: function (value) {
  83593. if (value && value.isSupported) {
  83594. this._geometryBufferRenderer = value;
  83595. }
  83596. ;
  83597. },
  83598. enumerable: true,
  83599. configurable: true
  83600. });
  83601. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83602. if (ratio === void 0) { ratio = 1; }
  83603. if (this._geometryBufferRenderer) {
  83604. return this._geometryBufferRenderer;
  83605. }
  83606. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83607. if (!this._geometryBufferRenderer.isSupported) {
  83608. this._geometryBufferRenderer = null;
  83609. }
  83610. return this._geometryBufferRenderer;
  83611. };
  83612. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83613. if (!this._geometryBufferRenderer) {
  83614. return;
  83615. }
  83616. this._geometryBufferRenderer.dispose();
  83617. this._geometryBufferRenderer = null;
  83618. };
  83619. /**
  83620. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83621. * in several rendering techniques.
  83622. */
  83623. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83624. /**
  83625. * Creates a new instance of the component for the given scene
  83626. * @param scene Defines the scene to register the component in
  83627. */
  83628. function GeometryBufferRendererSceneComponent(scene) {
  83629. /**
  83630. * The component name helpful to identify the component in the list of scene components.
  83631. */
  83632. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83633. this.scene = scene;
  83634. }
  83635. /**
  83636. * Registers the component in a given scene
  83637. */
  83638. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83639. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83640. };
  83641. /**
  83642. * Rebuilds the elements related to this component in case of
  83643. * context lost for instance.
  83644. */
  83645. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83646. // Nothing to do for this component
  83647. };
  83648. /**
  83649. * Disposes the component and the associated ressources
  83650. */
  83651. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83652. // Nothing to do for this component
  83653. };
  83654. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83655. if (this.scene._geometryBufferRenderer) {
  83656. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83657. }
  83658. };
  83659. return GeometryBufferRendererSceneComponent;
  83660. }());
  83661. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83662. })(BABYLON || (BABYLON = {}));
  83663. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83664. var BABYLON;
  83665. (function (BABYLON) {
  83666. /**
  83667. * Render pipeline to produce ssao effect
  83668. */
  83669. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83670. __extends(SSAORenderingPipeline, _super);
  83671. /**
  83672. * @constructor
  83673. * @param name - The rendering pipeline name
  83674. * @param scene - The scene linked to this pipeline
  83675. * @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 }
  83676. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  83677. */
  83678. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83679. var _this = _super.call(this, scene.getEngine(), name) || this;
  83680. // Members
  83681. /**
  83682. * @ignore
  83683. * The PassPostProcess id in the pipeline that contains the original scene color
  83684. */
  83685. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83686. /**
  83687. * @ignore
  83688. * The SSAO PostProcess id in the pipeline
  83689. */
  83690. _this.SSAORenderEffect = "SSAORenderEffect";
  83691. /**
  83692. * @ignore
  83693. * The horizontal blur PostProcess id in the pipeline
  83694. */
  83695. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83696. /**
  83697. * @ignore
  83698. * The vertical blur PostProcess id in the pipeline
  83699. */
  83700. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83701. /**
  83702. * @ignore
  83703. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83704. */
  83705. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83706. /**
  83707. * The output strength of the SSAO post-process. Default value is 1.0.
  83708. */
  83709. _this.totalStrength = 1.0;
  83710. /**
  83711. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  83712. */
  83713. _this.radius = 0.0001;
  83714. /**
  83715. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  83716. * Must not be equal to fallOff and superior to fallOff.
  83717. * Default value is 0.975
  83718. */
  83719. _this.area = 0.0075;
  83720. /**
  83721. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  83722. * Must not be equal to area and inferior to area.
  83723. * Default value is 0.0
  83724. */
  83725. _this.fallOff = 0.000001;
  83726. /**
  83727. * The base color of the SSAO post-process
  83728. * The final result is "base + ssao" between [0, 1]
  83729. */
  83730. _this.base = 0.5;
  83731. _this._firstUpdate = true;
  83732. _this._scene = scene;
  83733. // Set up assets
  83734. _this._createRandomTexture();
  83735. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83736. var ssaoRatio = ratio.ssaoRatio || ratio;
  83737. var combineRatio = ratio.combineRatio || ratio;
  83738. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83739. _this._createSSAOPostProcess(ssaoRatio);
  83740. _this._createBlurPostProcess(ssaoRatio);
  83741. _this._createSSAOCombinePostProcess(combineRatio);
  83742. // Set up pipeline
  83743. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83744. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83745. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83746. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83747. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83748. // Finish
  83749. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83750. if (cameras)
  83751. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83752. return _this;
  83753. }
  83754. // Public Methods
  83755. /**
  83756. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83757. */
  83758. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83759. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83760. for (var i = 0; i < this._scene.cameras.length; i++) {
  83761. var camera = this._scene.cameras[i];
  83762. this._originalColorPostProcess.dispose(camera);
  83763. this._ssaoPostProcess.dispose(camera);
  83764. this._blurHPostProcess.dispose(camera);
  83765. this._blurVPostProcess.dispose(camera);
  83766. this._ssaoCombinePostProcess.dispose(camera);
  83767. }
  83768. this._randomTexture.dispose();
  83769. if (disableDepthRender)
  83770. this._scene.disableDepthRenderer();
  83771. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83772. _super.prototype.dispose.call(this);
  83773. };
  83774. // Private Methods
  83775. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  83776. var _this = this;
  83777. var size = 16;
  83778. 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);
  83779. 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);
  83780. this._blurHPostProcess.onActivateObservable.add(function () {
  83781. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  83782. _this._blurHPostProcess.kernel = size * dw;
  83783. });
  83784. this._blurVPostProcess.onActivateObservable.add(function () {
  83785. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  83786. _this._blurVPostProcess.kernel = size * dw;
  83787. });
  83788. };
  83789. /** @hidden */
  83790. SSAORenderingPipeline.prototype._rebuild = function () {
  83791. this._firstUpdate = true;
  83792. _super.prototype._rebuild.call(this);
  83793. };
  83794. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83795. var _this = this;
  83796. var numSamples = 16;
  83797. var sampleSphere = [
  83798. 0.5381, 0.1856, -0.4319,
  83799. 0.1379, 0.2486, 0.4430,
  83800. 0.3371, 0.5679, -0.0057,
  83801. -0.6999, -0.0451, -0.0019,
  83802. 0.0689, -0.1598, -0.8547,
  83803. 0.0560, 0.0069, -0.1843,
  83804. -0.0146, 0.1402, 0.0762,
  83805. 0.0100, -0.1924, -0.0344,
  83806. -0.3577, -0.5301, -0.4358,
  83807. -0.3169, 0.1063, 0.0158,
  83808. 0.0103, -0.5869, 0.0046,
  83809. -0.0897, -0.4940, 0.3287,
  83810. 0.7119, -0.0154, -0.0918,
  83811. -0.0533, 0.0596, -0.5411,
  83812. 0.0352, -0.0631, 0.5460,
  83813. -0.4776, 0.2847, -0.0271
  83814. ];
  83815. var samplesFactor = 1.0 / numSamples;
  83816. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  83817. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83818. "area", "fallOff", "base", "range", "viewport"
  83819. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83820. this._ssaoPostProcess.onApply = function (effect) {
  83821. if (_this._firstUpdate) {
  83822. effect.setArray3("sampleSphere", sampleSphere);
  83823. effect.setFloat("samplesFactor", samplesFactor);
  83824. effect.setFloat("randTextureTiles", 4.0);
  83825. }
  83826. effect.setFloat("totalStrength", _this.totalStrength);
  83827. effect.setFloat("radius", _this.radius);
  83828. effect.setFloat("area", _this.area);
  83829. effect.setFloat("fallOff", _this.fallOff);
  83830. effect.setFloat("base", _this.base);
  83831. effect.setTexture("textureSampler", _this._depthTexture);
  83832. effect.setTexture("randomSampler", _this._randomTexture);
  83833. };
  83834. };
  83835. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83836. var _this = this;
  83837. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83838. this._ssaoCombinePostProcess.onApply = function (effect) {
  83839. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  83840. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83841. };
  83842. };
  83843. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  83844. var size = 512;
  83845. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83846. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83847. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83848. var context = this._randomTexture.getContext();
  83849. var rand = function (min, max) {
  83850. return Math.random() * (max - min) + min;
  83851. };
  83852. var randVector = BABYLON.Vector3.Zero();
  83853. for (var x = 0; x < size; x++) {
  83854. for (var y = 0; y < size; y++) {
  83855. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  83856. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  83857. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  83858. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83859. context.fillRect(x, y, 1, 1);
  83860. }
  83861. }
  83862. this._randomTexture.update(false);
  83863. };
  83864. __decorate([
  83865. BABYLON.serialize()
  83866. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  83867. __decorate([
  83868. BABYLON.serialize()
  83869. ], SSAORenderingPipeline.prototype, "radius", void 0);
  83870. __decorate([
  83871. BABYLON.serialize()
  83872. ], SSAORenderingPipeline.prototype, "area", void 0);
  83873. __decorate([
  83874. BABYLON.serialize()
  83875. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  83876. __decorate([
  83877. BABYLON.serialize()
  83878. ], SSAORenderingPipeline.prototype, "base", void 0);
  83879. return SSAORenderingPipeline;
  83880. }(BABYLON.PostProcessRenderPipeline));
  83881. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  83882. })(BABYLON || (BABYLON = {}));
  83883. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  83884. var BABYLON;
  83885. (function (BABYLON) {
  83886. /**
  83887. * Render pipeline to produce ssao effect
  83888. */
  83889. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  83890. __extends(SSAO2RenderingPipeline, _super);
  83891. /**
  83892. * @constructor
  83893. * @param name The rendering pipeline name
  83894. * @param scene The scene linked to this pipeline
  83895. * @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 }
  83896. * @param cameras The array of cameras that the rendering pipeline will be attached to
  83897. */
  83898. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  83899. var _this = _super.call(this, scene.getEngine(), name) || this;
  83900. // Members
  83901. /**
  83902. * @ignore
  83903. * The PassPostProcess id in the pipeline that contains the original scene color
  83904. */
  83905. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83906. /**
  83907. * @ignore
  83908. * The SSAO PostProcess id in the pipeline
  83909. */
  83910. _this.SSAORenderEffect = "SSAORenderEffect";
  83911. /**
  83912. * @ignore
  83913. * The horizontal blur PostProcess id in the pipeline
  83914. */
  83915. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83916. /**
  83917. * @ignore
  83918. * The vertical blur PostProcess id in the pipeline
  83919. */
  83920. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83921. /**
  83922. * @ignore
  83923. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83924. */
  83925. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83926. /**
  83927. * The output strength of the SSAO post-process. Default value is 1.0.
  83928. */
  83929. _this.totalStrength = 1.0;
  83930. /**
  83931. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83932. */
  83933. _this.maxZ = 100.0;
  83934. /**
  83935. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83936. */
  83937. _this.minZAspect = 0.2;
  83938. _this._samples = 8;
  83939. _this._textureSamples = 1;
  83940. _this._expensiveBlur = true;
  83941. /**
  83942. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83943. */
  83944. _this.radius = 2.0;
  83945. /**
  83946. * The base color of the SSAO post-process
  83947. * The final result is "base + ssao" between [0, 1]
  83948. */
  83949. _this.base = 0;
  83950. _this._firstUpdate = true;
  83951. _this._bits = new Uint32Array(1);
  83952. _this._scene = scene;
  83953. _this._ratio = ratio;
  83954. if (!_this.isSupported) {
  83955. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83956. return _this;
  83957. }
  83958. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83959. var blurRatio = _this._ratio.blurRatio || ratio;
  83960. // Set up assets
  83961. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83962. _this._createRandomTexture();
  83963. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83964. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83965. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83966. _this._originalColorPostProcess.samples = _this.textureSamples;
  83967. _this._createSSAOPostProcess(1.0);
  83968. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83969. _this._createSSAOCombinePostProcess(blurRatio);
  83970. // Set up pipeline
  83971. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83972. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83973. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83974. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83975. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83976. // Finish
  83977. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83978. if (cameras)
  83979. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83980. return _this;
  83981. }
  83982. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  83983. get: function () {
  83984. return this._samples;
  83985. },
  83986. /**
  83987. * Number of samples used for the SSAO calculations. Default value is 8
  83988. */
  83989. set: function (n) {
  83990. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  83991. this._samples = n;
  83992. this._sampleSphere = this._generateHemisphere();
  83993. this._firstUpdate = true;
  83994. },
  83995. enumerable: true,
  83996. configurable: true
  83997. });
  83998. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  83999. get: function () {
  84000. return this._textureSamples;
  84001. },
  84002. /**
  84003. * Number of samples to use for antialiasing
  84004. */
  84005. set: function (n) {
  84006. this._textureSamples = n;
  84007. this._originalColorPostProcess.samples = n;
  84008. this._blurHPostProcess.samples = n;
  84009. this._blurVPostProcess.samples = n;
  84010. this._ssaoPostProcess.samples = n;
  84011. this._ssaoCombinePostProcess.samples = n;
  84012. },
  84013. enumerable: true,
  84014. configurable: true
  84015. });
  84016. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84017. get: function () {
  84018. return this._expensiveBlur;
  84019. },
  84020. /**
  84021. * If bilateral blur should be used
  84022. */
  84023. set: function (b) {
  84024. 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"]);
  84025. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84026. this._expensiveBlur = b;
  84027. this._firstUpdate = true;
  84028. },
  84029. enumerable: true,
  84030. configurable: true
  84031. });
  84032. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84033. /**
  84034. * Support test.
  84035. */
  84036. get: function () {
  84037. var engine = BABYLON.Engine.LastCreatedEngine;
  84038. if (!engine) {
  84039. return false;
  84040. }
  84041. return engine.getCaps().drawBuffersExtension;
  84042. },
  84043. enumerable: true,
  84044. configurable: true
  84045. });
  84046. // Public Methods
  84047. /**
  84048. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84049. */
  84050. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84051. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84052. for (var i = 0; i < this._scene.cameras.length; i++) {
  84053. var camera = this._scene.cameras[i];
  84054. this._originalColorPostProcess.dispose(camera);
  84055. this._ssaoPostProcess.dispose(camera);
  84056. this._blurHPostProcess.dispose(camera);
  84057. this._blurVPostProcess.dispose(camera);
  84058. this._ssaoCombinePostProcess.dispose(camera);
  84059. }
  84060. this._randomTexture.dispose();
  84061. if (disableGeometryBufferRenderer)
  84062. this._scene.disableGeometryBufferRenderer();
  84063. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84064. _super.prototype.dispose.call(this);
  84065. };
  84066. // Private Methods
  84067. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84068. var _this = this;
  84069. this._samplerOffsets = [];
  84070. var expensive = this.expensiveBlur;
  84071. for (var i = -8; i < 8; i++) {
  84072. this._samplerOffsets.push(i * 2 + 0.5);
  84073. }
  84074. 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");
  84075. this._blurHPostProcess.onApply = function (effect) {
  84076. if (!_this._scene.activeCamera) {
  84077. return;
  84078. }
  84079. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84080. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84081. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84082. effect.setFloat("radius", _this.radius);
  84083. effect.setTexture("depthSampler", _this._depthTexture);
  84084. if (_this._firstUpdate) {
  84085. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84086. }
  84087. };
  84088. 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");
  84089. this._blurVPostProcess.onApply = function (effect) {
  84090. if (!_this._scene.activeCamera) {
  84091. return;
  84092. }
  84093. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84094. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84095. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84096. effect.setFloat("radius", _this.radius);
  84097. effect.setTexture("depthSampler", _this._depthTexture);
  84098. if (_this._firstUpdate) {
  84099. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84100. _this._firstUpdate = false;
  84101. }
  84102. };
  84103. this._blurHPostProcess.samples = this.textureSamples;
  84104. this._blurVPostProcess.samples = this.textureSamples;
  84105. };
  84106. /** @hidden */
  84107. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84108. this._firstUpdate = true;
  84109. _super.prototype._rebuild.call(this);
  84110. };
  84111. //Van der Corput radical inverse
  84112. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84113. this._bits[0] = i;
  84114. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84115. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84116. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84117. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84118. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84119. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84120. };
  84121. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84122. return [i / n, this._radicalInverse_VdC(i)];
  84123. };
  84124. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84125. var phi = v * 2.0 * Math.PI;
  84126. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84127. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84128. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84129. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84130. };
  84131. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84132. var numSamples = this.samples;
  84133. var result = [];
  84134. var vector;
  84135. var i = 0;
  84136. while (i < numSamples) {
  84137. if (numSamples < 16) {
  84138. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84139. }
  84140. else {
  84141. var rand = this._hammersley(i, numSamples);
  84142. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84143. }
  84144. result.push(vector.x, vector.y, vector.z);
  84145. i++;
  84146. }
  84147. return result;
  84148. };
  84149. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84150. var _this = this;
  84151. var numSamples = this.samples;
  84152. this._sampleSphere = this._generateHemisphere();
  84153. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84154. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84155. "base", "range", "projection", "near", "far", "texelSize",
  84156. "xViewport", "yViewport", "maxZ", "minZAspect"
  84157. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84158. this._ssaoPostProcess.onApply = function (effect) {
  84159. if (_this._firstUpdate) {
  84160. effect.setArray3("sampleSphere", _this._sampleSphere);
  84161. effect.setFloat("randTextureTiles", 32.0);
  84162. }
  84163. if (!_this._scene.activeCamera) {
  84164. return;
  84165. }
  84166. effect.setFloat("samplesFactor", 1 / _this.samples);
  84167. effect.setFloat("totalStrength", _this.totalStrength);
  84168. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84169. effect.setFloat("radius", _this.radius);
  84170. effect.setFloat("maxZ", _this.maxZ);
  84171. effect.setFloat("minZAspect", _this.minZAspect);
  84172. effect.setFloat("base", _this.base);
  84173. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84174. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84175. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84176. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84177. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84178. effect.setTexture("textureSampler", _this._depthTexture);
  84179. effect.setTexture("normalSampler", _this._normalTexture);
  84180. effect.setTexture("randomSampler", _this._randomTexture);
  84181. };
  84182. this._ssaoPostProcess.samples = this.textureSamples;
  84183. };
  84184. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84185. var _this = this;
  84186. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84187. this._ssaoCombinePostProcess.onApply = function (effect) {
  84188. var viewport = _this._scene.activeCamera.viewport;
  84189. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84190. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84191. };
  84192. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84193. };
  84194. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84195. var size = 128;
  84196. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84197. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84198. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84199. var context = this._randomTexture.getContext();
  84200. var rand = function (min, max) {
  84201. return Math.random() * (max - min) + min;
  84202. };
  84203. var randVector = BABYLON.Vector3.Zero();
  84204. for (var x = 0; x < size; x++) {
  84205. for (var y = 0; y < size; y++) {
  84206. randVector.x = rand(0.0, 1.0);
  84207. randVector.y = rand(0.0, 1.0);
  84208. randVector.z = 0.0;
  84209. randVector.normalize();
  84210. randVector.scaleInPlace(255);
  84211. randVector.x = Math.floor(randVector.x);
  84212. randVector.y = Math.floor(randVector.y);
  84213. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84214. context.fillRect(x, y, 1, 1);
  84215. }
  84216. }
  84217. this._randomTexture.update(false);
  84218. };
  84219. /**
  84220. * Serialize the rendering pipeline (Used when exporting)
  84221. * @returns the serialized object
  84222. */
  84223. SSAO2RenderingPipeline.prototype.serialize = function () {
  84224. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84225. serializationObject.customType = "SSAO2RenderingPipeline";
  84226. return serializationObject;
  84227. };
  84228. /**
  84229. * Parse the serialized pipeline
  84230. * @param source Source pipeline.
  84231. * @param scene The scene to load the pipeline to.
  84232. * @param rootUrl The URL of the serialized pipeline.
  84233. * @returns An instantiated pipeline from the serialized object.
  84234. */
  84235. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84236. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84237. };
  84238. __decorate([
  84239. BABYLON.serialize()
  84240. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84241. __decorate([
  84242. BABYLON.serialize()
  84243. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84244. __decorate([
  84245. BABYLON.serialize()
  84246. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84247. __decorate([
  84248. BABYLON.serialize("samples")
  84249. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84250. __decorate([
  84251. BABYLON.serialize("textureSamples")
  84252. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84253. __decorate([
  84254. BABYLON.serialize()
  84255. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84256. __decorate([
  84257. BABYLON.serialize("expensiveBlur")
  84258. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84259. __decorate([
  84260. BABYLON.serialize()
  84261. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84262. __decorate([
  84263. BABYLON.serialize()
  84264. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84265. return SSAO2RenderingPipeline;
  84266. }(BABYLON.PostProcessRenderPipeline));
  84267. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84268. })(BABYLON || (BABYLON = {}));
  84269. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84270. var BABYLON;
  84271. (function (BABYLON) {
  84272. /**
  84273. * BABYLON.JS Chromatic Aberration GLSL Shader
  84274. * Author: Olivier Guyot
  84275. * Separates very slightly R, G and B colors on the edges of the screen
  84276. * Inspired by Francois Tarlier & Martins Upitis
  84277. */
  84278. var LensRenderingPipeline = /** @class */ (function (_super) {
  84279. __extends(LensRenderingPipeline, _super);
  84280. /**
  84281. * @constructor
  84282. *
  84283. * Effect parameters are as follow:
  84284. * {
  84285. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84286. * edge_blur: number; // from 0 to x (1 for realism)
  84287. * distortion: number; // from 0 to x (1 for realism)
  84288. * grain_amount: number; // from 0 to 1
  84289. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84290. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84291. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84292. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84293. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84294. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84295. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84296. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84297. * }
  84298. * Note: if an effect parameter is unset, effect is disabled
  84299. *
  84300. * @param name The rendering pipeline name
  84301. * @param parameters - An object containing all parameters (see above)
  84302. * @param scene The scene linked to this pipeline
  84303. * @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)
  84304. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84305. */
  84306. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84307. if (ratio === void 0) { ratio = 1.0; }
  84308. var _this = _super.call(this, scene.getEngine(), name) || this;
  84309. // Lens effects can be of the following:
  84310. // - chromatic aberration (slight shift of RGB colors)
  84311. // - blur on the edge of the lens
  84312. // - lens distortion
  84313. // - depth-of-field blur & highlights enhancing
  84314. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84315. // - grain effect (noise or custom texture)
  84316. // Two additional texture samplers are needed:
  84317. // - depth map (for depth-of-field)
  84318. // - grain texture
  84319. /**
  84320. * @ignore
  84321. * The chromatic aberration PostProcess id in the pipeline
  84322. */
  84323. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84324. /**
  84325. * @ignore
  84326. * The highlights enhancing PostProcess id in the pipeline
  84327. */
  84328. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84329. /**
  84330. * @ignore
  84331. * The depth-of-field PostProcess id in the pipeline
  84332. */
  84333. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84334. _this._scene = scene;
  84335. // Fetch texture samplers
  84336. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84337. if (parameters.grain_texture) {
  84338. _this._grainTexture = parameters.grain_texture;
  84339. }
  84340. else {
  84341. _this._createGrainTexture();
  84342. }
  84343. // save parameters
  84344. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84345. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84346. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84347. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84348. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84349. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84350. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84351. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84352. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84353. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84354. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84355. // Create effects
  84356. _this._createChromaticAberrationPostProcess(ratio);
  84357. _this._createHighlightsPostProcess(ratio);
  84358. _this._createDepthOfFieldPostProcess(ratio / 4);
  84359. // Set up pipeline
  84360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84361. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84362. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84363. if (_this._highlightsGain === -1) {
  84364. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84365. }
  84366. // Finish
  84367. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84368. if (cameras) {
  84369. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84370. }
  84371. return _this;
  84372. }
  84373. // public methods (self explanatory)
  84374. /**
  84375. * Sets the amount of blur at the edges
  84376. * @param amount blur amount
  84377. */
  84378. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84379. /**
  84380. * Sets edge blur to 0
  84381. */
  84382. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84383. /**
  84384. * Sets the amout of grain
  84385. * @param amount Amount of grain
  84386. */
  84387. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84388. /**
  84389. * Set grain amount to 0
  84390. */
  84391. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84392. /**
  84393. * Sets the chromatic aberration amount
  84394. * @param amount amount of chromatic aberration
  84395. */
  84396. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84397. /**
  84398. * Sets chromatic aberration amount to 0
  84399. */
  84400. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84401. /**
  84402. * Sets the EdgeDistortion amount
  84403. * @param amount amount of EdgeDistortion
  84404. */
  84405. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84406. /**
  84407. * Sets edge distortion to 0
  84408. */
  84409. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84410. /**
  84411. * Sets the FocusDistance amount
  84412. * @param amount amount of FocusDistance
  84413. */
  84414. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84415. /**
  84416. * Disables depth of field
  84417. */
  84418. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84419. /**
  84420. * Sets the Aperture amount
  84421. * @param amount amount of Aperture
  84422. */
  84423. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84424. /**
  84425. * Sets the DarkenOutOfFocus amount
  84426. * @param amount amount of DarkenOutOfFocus
  84427. */
  84428. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84429. /**
  84430. * Creates a pentagon bokeh effect
  84431. */
  84432. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84433. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84434. };
  84435. /**
  84436. * Disables the pentagon bokeh effect
  84437. */
  84438. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84439. this._highlightsPostProcess.updateEffect();
  84440. };
  84441. /**
  84442. * Enables noise blur
  84443. */
  84444. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84445. /**
  84446. * Disables noise blur
  84447. */
  84448. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84449. /**
  84450. * Sets the HighlightsGain amount
  84451. * @param amount amount of HighlightsGain
  84452. */
  84453. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84454. this._highlightsGain = amount;
  84455. };
  84456. /**
  84457. * Sets the HighlightsThreshold amount
  84458. * @param amount amount of HighlightsThreshold
  84459. */
  84460. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84461. if (this._highlightsGain === -1) {
  84462. this._highlightsGain = 1.0;
  84463. }
  84464. this._highlightsThreshold = amount;
  84465. };
  84466. /**
  84467. * Disables highlights
  84468. */
  84469. LensRenderingPipeline.prototype.disableHighlights = function () {
  84470. this._highlightsGain = -1;
  84471. };
  84472. /**
  84473. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84474. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84475. */
  84476. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84477. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84478. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84479. this._chromaticAberrationPostProcess = null;
  84480. this._highlightsPostProcess = null;
  84481. this._depthOfFieldPostProcess = null;
  84482. this._grainTexture.dispose();
  84483. if (disableDepthRender)
  84484. this._scene.disableDepthRenderer();
  84485. };
  84486. // colors shifting and distortion
  84487. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84488. var _this = this;
  84489. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84490. [], // samplers
  84491. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84492. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84493. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84494. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84495. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84496. effect.setFloat('radialIntensity', 1);
  84497. effect.setFloat2('direction', 17, 17);
  84498. effect.setFloat2('centerPosition', 0.5, 0.5);
  84499. };
  84500. };
  84501. // highlights enhancing
  84502. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84503. var _this = this;
  84504. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84505. [], // samplers
  84506. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84507. this._highlightsPostProcess.onApply = function (effect) {
  84508. effect.setFloat('gain', _this._highlightsGain);
  84509. effect.setFloat('threshold', _this._highlightsThreshold);
  84510. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84511. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84512. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84513. };
  84514. };
  84515. // colors shifting and distortion
  84516. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84517. var _this = this;
  84518. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84519. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84520. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84521. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84522. this._depthOfFieldPostProcess.onApply = function (effect) {
  84523. effect.setTexture("depthSampler", _this._depthTexture);
  84524. effect.setTexture("grainSampler", _this._grainTexture);
  84525. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84526. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84527. effect.setFloat('grain_amount', _this._grainAmount);
  84528. effect.setBool('blur_noise', _this._blurNoise);
  84529. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84530. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84531. effect.setFloat('distortion', _this._distortion);
  84532. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84533. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84534. effect.setFloat('aperture', _this._dofAperture);
  84535. effect.setFloat('darken', _this._dofDarken);
  84536. effect.setFloat('edge_blur', _this._edgeBlur);
  84537. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84538. if (_this._scene.activeCamera) {
  84539. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84540. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84541. }
  84542. };
  84543. };
  84544. // creates a black and white random noise texture, 512x512
  84545. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84546. var size = 512;
  84547. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84548. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84549. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84550. var context = this._grainTexture.getContext();
  84551. var rand = function (min, max) {
  84552. return Math.random() * (max - min) + min;
  84553. };
  84554. var value;
  84555. for (var x = 0; x < size; x++) {
  84556. for (var y = 0; y < size; y++) {
  84557. value = Math.floor(rand(0.42, 0.58) * 255);
  84558. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84559. context.fillRect(x, y, 1, 1);
  84560. }
  84561. }
  84562. this._grainTexture.update(false);
  84563. };
  84564. return LensRenderingPipeline;
  84565. }(BABYLON.PostProcessRenderPipeline));
  84566. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84567. })(BABYLON || (BABYLON = {}));
  84568. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84569. var BABYLON;
  84570. (function (BABYLON) {
  84571. /**
  84572. * Standard rendering pipeline
  84573. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84574. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84575. */
  84576. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84577. __extends(StandardRenderingPipeline, _super);
  84578. /**
  84579. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84580. * @constructor
  84581. * @param name The rendering pipeline name
  84582. * @param scene The scene linked to this pipeline
  84583. * @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)
  84584. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  84585. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84586. */
  84587. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84588. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84589. var _this = _super.call(this, scene.getEngine(), name) || this;
  84590. /**
  84591. * Post-process used to down scale an image x4
  84592. */
  84593. _this.downSampleX4PostProcess = null;
  84594. /**
  84595. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84596. */
  84597. _this.brightPassPostProcess = null;
  84598. /**
  84599. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84600. */
  84601. _this.blurHPostProcesses = [];
  84602. /**
  84603. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84604. */
  84605. _this.blurVPostProcesses = [];
  84606. /**
  84607. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84608. */
  84609. _this.textureAdderPostProcess = null;
  84610. /**
  84611. * Post-process used to create volumetric lighting effect
  84612. */
  84613. _this.volumetricLightPostProcess = null;
  84614. /**
  84615. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84616. */
  84617. _this.volumetricLightSmoothXPostProcess = null;
  84618. /**
  84619. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84620. */
  84621. _this.volumetricLightSmoothYPostProcess = null;
  84622. /**
  84623. * Post-process used to merge the volumetric light effect and the real scene color
  84624. */
  84625. _this.volumetricLightMergePostProces = null;
  84626. /**
  84627. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84628. */
  84629. _this.volumetricLightFinalPostProcess = null;
  84630. /**
  84631. * Base post-process used to calculate the average luminance of the final image for HDR
  84632. */
  84633. _this.luminancePostProcess = null;
  84634. /**
  84635. * Post-processes used to create down sample post-processes in order to get
  84636. * the average luminance of the final image for HDR
  84637. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84638. */
  84639. _this.luminanceDownSamplePostProcesses = [];
  84640. /**
  84641. * Post-process used to create a HDR effect (light adaptation)
  84642. */
  84643. _this.hdrPostProcess = null;
  84644. /**
  84645. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84646. */
  84647. _this.textureAdderFinalPostProcess = null;
  84648. /**
  84649. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84650. */
  84651. _this.lensFlareFinalPostProcess = null;
  84652. /**
  84653. * Post-process used to merge the final HDR post-process and the real scene color
  84654. */
  84655. _this.hdrFinalPostProcess = null;
  84656. /**
  84657. * Post-process used to create a lens flare effect
  84658. */
  84659. _this.lensFlarePostProcess = null;
  84660. /**
  84661. * Post-process that merges the result of the lens flare post-process and the real scene color
  84662. */
  84663. _this.lensFlareComposePostProcess = null;
  84664. /**
  84665. * Post-process used to create a motion blur effect
  84666. */
  84667. _this.motionBlurPostProcess = null;
  84668. /**
  84669. * Post-process used to create a depth of field effect
  84670. */
  84671. _this.depthOfFieldPostProcess = null;
  84672. /**
  84673. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84674. */
  84675. _this.fxaaPostProcess = null;
  84676. // Values
  84677. /**
  84678. * Represents the brightness threshold in order to configure the illuminated surfaces
  84679. */
  84680. _this.brightThreshold = 1.0;
  84681. /**
  84682. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  84683. */
  84684. _this.blurWidth = 512.0;
  84685. /**
  84686. * Sets if the blur for highlighted surfaces must be only horizontal
  84687. */
  84688. _this.horizontalBlur = false;
  84689. /**
  84690. * Sets the overall exposure used by the pipeline
  84691. */
  84692. _this.exposure = 1.0;
  84693. /**
  84694. * Texture used typically to simulate "dirty" on camera lens
  84695. */
  84696. _this.lensTexture = null;
  84697. /**
  84698. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  84699. */
  84700. _this.volumetricLightCoefficient = 0.2;
  84701. /**
  84702. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  84703. */
  84704. _this.volumetricLightPower = 4.0;
  84705. /**
  84706. * Used the set the blur intensity to smooth the volumetric lights
  84707. */
  84708. _this.volumetricLightBlurScale = 64.0;
  84709. /**
  84710. * Light (spot or directional) used to generate the volumetric lights rays
  84711. * The source light must have a shadow generate so the pipeline can get its
  84712. * depth map
  84713. */
  84714. _this.sourceLight = null;
  84715. /**
  84716. * For eye adaptation, represents the minimum luminance the eye can see
  84717. */
  84718. _this.hdrMinimumLuminance = 1.0;
  84719. /**
  84720. * For eye adaptation, represents the decrease luminance speed
  84721. */
  84722. _this.hdrDecreaseRate = 0.5;
  84723. /**
  84724. * For eye adaptation, represents the increase luminance speed
  84725. */
  84726. _this.hdrIncreaseRate = 0.5;
  84727. /**
  84728. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  84729. */
  84730. _this.lensColorTexture = null;
  84731. /**
  84732. * The overall strengh for the lens flare effect
  84733. */
  84734. _this.lensFlareStrength = 20.0;
  84735. /**
  84736. * Dispersion coefficient for lens flare ghosts
  84737. */
  84738. _this.lensFlareGhostDispersal = 1.4;
  84739. /**
  84740. * Main lens flare halo width
  84741. */
  84742. _this.lensFlareHaloWidth = 0.7;
  84743. /**
  84744. * Based on the lens distortion effect, defines how much the lens flare result
  84745. * is distorted
  84746. */
  84747. _this.lensFlareDistortionStrength = 16.0;
  84748. /**
  84749. * Lens star texture must be used to simulate rays on the flares and is available
  84750. * in the documentation
  84751. */
  84752. _this.lensStarTexture = null;
  84753. /**
  84754. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  84755. * flare effect by taking account of the dirt texture
  84756. */
  84757. _this.lensFlareDirtTexture = null;
  84758. /**
  84759. * Represents the focal length for the depth of field effect
  84760. */
  84761. _this.depthOfFieldDistance = 10.0;
  84762. /**
  84763. * Represents the blur intensity for the blurred part of the depth of field effect
  84764. */
  84765. _this.depthOfFieldBlurWidth = 64.0;
  84766. /**
  84767. * For motion blur, defines how much the image is blurred by the movement
  84768. */
  84769. _this.motionStrength = 1.0;
  84770. /**
  84771. * List of animations for the pipeline (IAnimatable implementation)
  84772. */
  84773. _this.animations = [];
  84774. _this._currentDepthOfFieldSource = null;
  84775. _this._hdrCurrentLuminance = 1.0;
  84776. // Getters and setters
  84777. _this._bloomEnabled = false;
  84778. _this._depthOfFieldEnabled = false;
  84779. _this._vlsEnabled = false;
  84780. _this._lensFlareEnabled = false;
  84781. _this._hdrEnabled = false;
  84782. _this._motionBlurEnabled = false;
  84783. _this._fxaaEnabled = false;
  84784. _this._motionBlurSamples = 64.0;
  84785. _this._volumetricLightStepsCount = 50.0;
  84786. _this._samples = 1;
  84787. _this._cameras = cameras || [];
  84788. // Initialize
  84789. _this._scene = scene;
  84790. _this._basePostProcess = originalPostProcess;
  84791. _this._ratio = ratio;
  84792. // Misc
  84793. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84794. // Finish
  84795. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84796. _this._buildPipeline();
  84797. return _this;
  84798. }
  84799. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  84800. /**
  84801. * @ignore
  84802. * Specifies if the bloom pipeline is enabled
  84803. */
  84804. get: function () {
  84805. return this._bloomEnabled;
  84806. },
  84807. set: function (enabled) {
  84808. if (this._bloomEnabled === enabled) {
  84809. return;
  84810. }
  84811. this._bloomEnabled = enabled;
  84812. this._buildPipeline();
  84813. },
  84814. enumerable: true,
  84815. configurable: true
  84816. });
  84817. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  84818. /**
  84819. * @ignore
  84820. * Specifies if the depth of field pipeline is enabed
  84821. */
  84822. get: function () {
  84823. return this._depthOfFieldEnabled;
  84824. },
  84825. set: function (enabled) {
  84826. if (this._depthOfFieldEnabled === enabled) {
  84827. return;
  84828. }
  84829. this._depthOfFieldEnabled = enabled;
  84830. this._buildPipeline();
  84831. },
  84832. enumerable: true,
  84833. configurable: true
  84834. });
  84835. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  84836. /**
  84837. * @ignore
  84838. * Specifies if the lens flare pipeline is enabed
  84839. */
  84840. get: function () {
  84841. return this._lensFlareEnabled;
  84842. },
  84843. set: function (enabled) {
  84844. if (this._lensFlareEnabled === enabled) {
  84845. return;
  84846. }
  84847. this._lensFlareEnabled = enabled;
  84848. this._buildPipeline();
  84849. },
  84850. enumerable: true,
  84851. configurable: true
  84852. });
  84853. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  84854. /**
  84855. * @ignore
  84856. * Specifies if the HDR pipeline is enabled
  84857. */
  84858. get: function () {
  84859. return this._hdrEnabled;
  84860. },
  84861. set: function (enabled) {
  84862. if (this._hdrEnabled === enabled) {
  84863. return;
  84864. }
  84865. this._hdrEnabled = enabled;
  84866. this._buildPipeline();
  84867. },
  84868. enumerable: true,
  84869. configurable: true
  84870. });
  84871. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  84872. /**
  84873. * @ignore
  84874. * Specifies if the volumetric lights scattering effect is enabled
  84875. */
  84876. get: function () {
  84877. return this._vlsEnabled;
  84878. },
  84879. set: function (enabled) {
  84880. if (this._vlsEnabled === enabled) {
  84881. return;
  84882. }
  84883. if (enabled) {
  84884. var geometry = this._scene.enableGeometryBufferRenderer();
  84885. if (!geometry) {
  84886. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  84887. return;
  84888. }
  84889. }
  84890. this._vlsEnabled = enabled;
  84891. this._buildPipeline();
  84892. },
  84893. enumerable: true,
  84894. configurable: true
  84895. });
  84896. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  84897. /**
  84898. * @ignore
  84899. * Specifies if the motion blur effect is enabled
  84900. */
  84901. get: function () {
  84902. return this._motionBlurEnabled;
  84903. },
  84904. set: function (enabled) {
  84905. if (this._motionBlurEnabled === enabled) {
  84906. return;
  84907. }
  84908. this._motionBlurEnabled = enabled;
  84909. this._buildPipeline();
  84910. },
  84911. enumerable: true,
  84912. configurable: true
  84913. });
  84914. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  84915. /**
  84916. * Specifies if anti-aliasing is enabled
  84917. */
  84918. get: function () {
  84919. return this._fxaaEnabled;
  84920. },
  84921. set: function (enabled) {
  84922. if (this._fxaaEnabled === enabled) {
  84923. return;
  84924. }
  84925. this._fxaaEnabled = enabled;
  84926. this._buildPipeline();
  84927. },
  84928. enumerable: true,
  84929. configurable: true
  84930. });
  84931. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  84932. /**
  84933. * Specifies the number of steps used to calculate the volumetric lights
  84934. * Typically in interval [50, 200]
  84935. */
  84936. get: function () {
  84937. return this._volumetricLightStepsCount;
  84938. },
  84939. set: function (count) {
  84940. if (this.volumetricLightPostProcess) {
  84941. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  84942. }
  84943. this._volumetricLightStepsCount = count;
  84944. },
  84945. enumerable: true,
  84946. configurable: true
  84947. });
  84948. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  84949. /**
  84950. * Specifies the number of samples used for the motion blur effect
  84951. * Typically in interval [16, 64]
  84952. */
  84953. get: function () {
  84954. return this._motionBlurSamples;
  84955. },
  84956. set: function (samples) {
  84957. if (this.motionBlurPostProcess) {
  84958. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  84959. }
  84960. this._motionBlurSamples = samples;
  84961. },
  84962. enumerable: true,
  84963. configurable: true
  84964. });
  84965. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  84966. /**
  84967. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84968. */
  84969. get: function () {
  84970. return this._samples;
  84971. },
  84972. set: function (sampleCount) {
  84973. if (this._samples === sampleCount) {
  84974. return;
  84975. }
  84976. this._samples = sampleCount;
  84977. this._buildPipeline();
  84978. },
  84979. enumerable: true,
  84980. configurable: true
  84981. });
  84982. StandardRenderingPipeline.prototype._buildPipeline = function () {
  84983. var _this = this;
  84984. var ratio = this._ratio;
  84985. var scene = this._scene;
  84986. this._disposePostProcesses();
  84987. this._reset();
  84988. // Create pass post-process
  84989. if (!this._basePostProcess) {
  84990. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  84991. this.originalPostProcess.onApply = function (effect) {
  84992. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  84993. };
  84994. }
  84995. else {
  84996. this.originalPostProcess = this._basePostProcess;
  84997. }
  84998. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  84999. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  85000. }
  85001. this._currentDepthOfFieldSource = this.originalPostProcess;
  85002. if (this._bloomEnabled) {
  85003. // Create down sample X4 post-process
  85004. this._createDownSampleX4PostProcess(scene, ratio / 2);
  85005. // Create bright pass post-process
  85006. this._createBrightPassPostProcess(scene, ratio / 2);
  85007. // Create gaussian blur post-processes (down sampling blurs)
  85008. this._createBlurPostProcesses(scene, ratio / 4, 1);
  85009. // Create texture adder post-process
  85010. this._createTextureAdderPostProcess(scene, ratio);
  85011. // Create depth-of-field source post-process
  85012. 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);
  85013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  85014. }
  85015. if (this._vlsEnabled) {
  85016. // Create volumetric light
  85017. this._createVolumetricLightPostProcess(scene, ratio);
  85018. // Create volumetric light final post-process
  85019. 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);
  85020. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85021. }
  85022. if (this._lensFlareEnabled) {
  85023. // Create lens flare post-process
  85024. this._createLensFlarePostProcess(scene, ratio);
  85025. // Create depth-of-field source post-process post lens-flare and disable it now
  85026. 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);
  85027. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85028. }
  85029. if (this._hdrEnabled) {
  85030. // Create luminance
  85031. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85032. // Create HDR
  85033. this._createHdrPostProcess(scene, ratio);
  85034. // Create depth-of-field source post-process post hdr and disable it now
  85035. 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);
  85036. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85037. }
  85038. if (this._depthOfFieldEnabled) {
  85039. // Create gaussian blur used by depth-of-field
  85040. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85041. // Create depth-of-field post-process
  85042. this._createDepthOfFieldPostProcess(scene, ratio);
  85043. }
  85044. if (this._motionBlurEnabled) {
  85045. // Create motion blur post-process
  85046. this._createMotionBlurPostProcess(scene, ratio);
  85047. }
  85048. if (this._fxaaEnabled) {
  85049. // Create fxaa post-process
  85050. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85052. }
  85053. if (this._cameras !== null) {
  85054. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85055. }
  85056. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85057. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85058. }
  85059. };
  85060. // Down Sample X4 Post-Processs
  85061. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85062. var _this = this;
  85063. var downSampleX4Offsets = new Array(32);
  85064. 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);
  85065. this.downSampleX4PostProcess.onApply = function (effect) {
  85066. var id = 0;
  85067. var width = _this.downSampleX4PostProcess.width;
  85068. var height = _this.downSampleX4PostProcess.height;
  85069. for (var i = -2; i < 2; i++) {
  85070. for (var j = -2; j < 2; j++) {
  85071. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85072. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85073. id += 2;
  85074. }
  85075. }
  85076. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85077. };
  85078. // Add to pipeline
  85079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85080. };
  85081. // Brightpass Post-Process
  85082. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85083. var _this = this;
  85084. var brightOffsets = new Array(8);
  85085. 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);
  85086. this.brightPassPostProcess.onApply = function (effect) {
  85087. var sU = (1.0 / _this.brightPassPostProcess.width);
  85088. var sV = (1.0 / _this.brightPassPostProcess.height);
  85089. brightOffsets[0] = -0.5 * sU;
  85090. brightOffsets[1] = 0.5 * sV;
  85091. brightOffsets[2] = 0.5 * sU;
  85092. brightOffsets[3] = 0.5 * sV;
  85093. brightOffsets[4] = -0.5 * sU;
  85094. brightOffsets[5] = -0.5 * sV;
  85095. brightOffsets[6] = 0.5 * sU;
  85096. brightOffsets[7] = -0.5 * sV;
  85097. effect.setArray2("dsOffsets", brightOffsets);
  85098. effect.setFloat("brightThreshold", _this.brightThreshold);
  85099. };
  85100. // Add to pipeline
  85101. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85102. };
  85103. // Create blur H&V post-processes
  85104. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85105. var _this = this;
  85106. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85107. var engine = scene.getEngine();
  85108. 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);
  85109. 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);
  85110. blurX.onActivateObservable.add(function () {
  85111. var dw = blurX.width / engine.getRenderWidth();
  85112. blurX.kernel = _this[blurWidthKey] * dw;
  85113. });
  85114. blurY.onActivateObservable.add(function () {
  85115. var dw = blurY.height / engine.getRenderHeight();
  85116. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85117. });
  85118. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85120. this.blurHPostProcesses.push(blurX);
  85121. this.blurVPostProcesses.push(blurY);
  85122. };
  85123. // Create texture adder post-process
  85124. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85125. var _this = this;
  85126. 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);
  85127. this.textureAdderPostProcess.onApply = function (effect) {
  85128. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85129. effect.setTexture("lensSampler", _this.lensTexture);
  85130. effect.setFloat("exposure", _this.exposure);
  85131. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85132. };
  85133. // Add to pipeline
  85134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85135. };
  85136. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85137. var _this = this;
  85138. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85139. geometryRenderer.enablePosition = true;
  85140. var geometry = geometryRenderer.getGBuffer();
  85141. // Base post-process
  85142. 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));
  85143. var depthValues = BABYLON.Vector2.Zero();
  85144. this.volumetricLightPostProcess.onApply = function (effect) {
  85145. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85146. var generator = _this.sourceLight.getShadowGenerator();
  85147. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85148. effect.setTexture("positionSampler", geometry.textures[2]);
  85149. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85150. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85151. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85152. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85153. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85154. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85155. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85156. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85157. effect.setVector2("depthValues", depthValues);
  85158. }
  85159. };
  85160. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85161. // Smooth
  85162. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85163. // Merge
  85164. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85165. this.volumetricLightMergePostProces.onApply = function (effect) {
  85166. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85167. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85168. };
  85169. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85170. };
  85171. // Create luminance
  85172. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85173. var _this = this;
  85174. // Create luminance
  85175. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85176. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85177. var offsets = [];
  85178. this.luminancePostProcess.onApply = function (effect) {
  85179. var sU = (1.0 / _this.luminancePostProcess.width);
  85180. var sV = (1.0 / _this.luminancePostProcess.height);
  85181. offsets[0] = -0.5 * sU;
  85182. offsets[1] = 0.5 * sV;
  85183. offsets[2] = 0.5 * sU;
  85184. offsets[3] = 0.5 * sV;
  85185. offsets[4] = -0.5 * sU;
  85186. offsets[5] = -0.5 * sV;
  85187. offsets[6] = 0.5 * sU;
  85188. offsets[7] = -0.5 * sV;
  85189. effect.setArray2("lumOffsets", offsets);
  85190. };
  85191. // Add to pipeline
  85192. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85193. // Create down sample luminance
  85194. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85195. var size = Math.pow(3, i);
  85196. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85197. if (i === 0) {
  85198. defines += "#define FINAL_DOWN_SAMPLER";
  85199. }
  85200. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85201. this.luminanceDownSamplePostProcesses.push(postProcess);
  85202. }
  85203. // Create callbacks and add effects
  85204. var lastLuminance = this.luminancePostProcess;
  85205. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85206. var downSampleOffsets = new Array(18);
  85207. pp.onApply = function (effect) {
  85208. if (!lastLuminance) {
  85209. return;
  85210. }
  85211. var id = 0;
  85212. for (var x = -1; x < 2; x++) {
  85213. for (var y = -1; y < 2; y++) {
  85214. downSampleOffsets[id] = x / lastLuminance.width;
  85215. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85216. id += 2;
  85217. }
  85218. }
  85219. effect.setArray2("dsOffsets", downSampleOffsets);
  85220. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85221. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85222. lastLuminance = _this.luminancePostProcess;
  85223. }
  85224. else {
  85225. lastLuminance = pp;
  85226. }
  85227. };
  85228. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85229. pp.onAfterRender = function (effect) {
  85230. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85231. 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);
  85232. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85233. };
  85234. }
  85235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85236. });
  85237. };
  85238. // Create HDR post-process
  85239. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85240. var _this = this;
  85241. 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);
  85242. var outputLiminance = 1;
  85243. var time = 0;
  85244. var lastTime = 0;
  85245. this.hdrPostProcess.onApply = function (effect) {
  85246. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85247. time += scene.getEngine().getDeltaTime();
  85248. if (outputLiminance < 0) {
  85249. outputLiminance = _this._hdrCurrentLuminance;
  85250. }
  85251. else {
  85252. var dt = (lastTime - time) / 1000.0;
  85253. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85254. outputLiminance += _this.hdrDecreaseRate * dt;
  85255. }
  85256. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85257. outputLiminance -= _this.hdrIncreaseRate * dt;
  85258. }
  85259. else {
  85260. outputLiminance = _this._hdrCurrentLuminance;
  85261. }
  85262. }
  85263. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85264. effect.setFloat("averageLuminance", outputLiminance);
  85265. lastTime = time;
  85266. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85267. };
  85268. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85269. };
  85270. // Create lens flare post-process
  85271. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85272. var _this = this;
  85273. 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);
  85274. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85275. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85276. 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);
  85277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85278. var resolution = new BABYLON.Vector2(0, 0);
  85279. // Lens flare
  85280. this.lensFlarePostProcess.onApply = function (effect) {
  85281. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85282. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85283. effect.setFloat("strength", _this.lensFlareStrength);
  85284. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85285. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85286. // Shift
  85287. resolution.x = _this.lensFlarePostProcess.width;
  85288. resolution.y = _this.lensFlarePostProcess.height;
  85289. effect.setVector2("resolution", resolution);
  85290. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85291. };
  85292. // Compose
  85293. 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);
  85294. 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);
  85295. this.lensFlareComposePostProcess.onApply = function (effect) {
  85296. if (!_this._scene.activeCamera) {
  85297. return;
  85298. }
  85299. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85300. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85301. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85302. // Lens start rotation matrix
  85303. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85304. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85305. 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));
  85306. camRot *= 4.0;
  85307. 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);
  85308. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85309. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85310. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85311. };
  85312. };
  85313. // Create depth-of-field post-process
  85314. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85315. var _this = this;
  85316. 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);
  85317. this.depthOfFieldPostProcess.onApply = function (effect) {
  85318. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85319. effect.setTexture("depthSampler", _this._getDepthTexture());
  85320. effect.setFloat("distance", _this.depthOfFieldDistance);
  85321. };
  85322. // Add to pipeline
  85323. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85324. };
  85325. // Create motion blur post-process
  85326. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85327. var _this = this;
  85328. 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);
  85329. var motionScale = 0;
  85330. var prevViewProjection = BABYLON.Matrix.Identity();
  85331. var invViewProjection = BABYLON.Matrix.Identity();
  85332. var viewProjection = BABYLON.Matrix.Identity();
  85333. var screenSize = BABYLON.Vector2.Zero();
  85334. this.motionBlurPostProcess.onApply = function (effect) {
  85335. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85336. viewProjection.invertToRef(invViewProjection);
  85337. effect.setMatrix("inverseViewProjection", invViewProjection);
  85338. effect.setMatrix("prevViewProjection", prevViewProjection);
  85339. prevViewProjection = viewProjection;
  85340. screenSize.x = _this.motionBlurPostProcess.width;
  85341. screenSize.y = _this.motionBlurPostProcess.height;
  85342. effect.setVector2("screenSize", screenSize);
  85343. motionScale = scene.getEngine().getFps() / 60.0;
  85344. effect.setFloat("motionScale", motionScale);
  85345. effect.setFloat("motionStrength", _this.motionStrength);
  85346. effect.setTexture("depthSampler", _this._getDepthTexture());
  85347. };
  85348. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85349. };
  85350. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85351. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85352. var renderer = this._scene.enableGeometryBufferRenderer();
  85353. return renderer.getGBuffer().textures[0];
  85354. }
  85355. return this._scene.enableDepthRenderer().getDepthMap();
  85356. };
  85357. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85358. for (var i = 0; i < this._cameras.length; i++) {
  85359. var camera = this._cameras[i];
  85360. if (this.originalPostProcess) {
  85361. this.originalPostProcess.dispose(camera);
  85362. }
  85363. if (this.downSampleX4PostProcess) {
  85364. this.downSampleX4PostProcess.dispose(camera);
  85365. }
  85366. if (this.brightPassPostProcess) {
  85367. this.brightPassPostProcess.dispose(camera);
  85368. }
  85369. if (this.textureAdderPostProcess) {
  85370. this.textureAdderPostProcess.dispose(camera);
  85371. }
  85372. if (this.textureAdderFinalPostProcess) {
  85373. this.textureAdderFinalPostProcess.dispose(camera);
  85374. }
  85375. if (this.volumetricLightPostProcess) {
  85376. this.volumetricLightPostProcess.dispose(camera);
  85377. }
  85378. if (this.volumetricLightSmoothXPostProcess) {
  85379. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85380. }
  85381. if (this.volumetricLightSmoothYPostProcess) {
  85382. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85383. }
  85384. if (this.volumetricLightMergePostProces) {
  85385. this.volumetricLightMergePostProces.dispose(camera);
  85386. }
  85387. if (this.volumetricLightFinalPostProcess) {
  85388. this.volumetricLightFinalPostProcess.dispose(camera);
  85389. }
  85390. if (this.lensFlarePostProcess) {
  85391. this.lensFlarePostProcess.dispose(camera);
  85392. }
  85393. if (this.lensFlareComposePostProcess) {
  85394. this.lensFlareComposePostProcess.dispose(camera);
  85395. }
  85396. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85397. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85398. }
  85399. if (this.luminancePostProcess) {
  85400. this.luminancePostProcess.dispose(camera);
  85401. }
  85402. if (this.hdrPostProcess) {
  85403. this.hdrPostProcess.dispose(camera);
  85404. }
  85405. if (this.hdrFinalPostProcess) {
  85406. this.hdrFinalPostProcess.dispose(camera);
  85407. }
  85408. if (this.depthOfFieldPostProcess) {
  85409. this.depthOfFieldPostProcess.dispose(camera);
  85410. }
  85411. if (this.motionBlurPostProcess) {
  85412. this.motionBlurPostProcess.dispose(camera);
  85413. }
  85414. if (this.fxaaPostProcess) {
  85415. this.fxaaPostProcess.dispose(camera);
  85416. }
  85417. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85418. this.blurHPostProcesses[j].dispose(camera);
  85419. }
  85420. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85421. this.blurVPostProcesses[j].dispose(camera);
  85422. }
  85423. }
  85424. this.originalPostProcess = null;
  85425. this.downSampleX4PostProcess = null;
  85426. this.brightPassPostProcess = null;
  85427. this.textureAdderPostProcess = null;
  85428. this.textureAdderFinalPostProcess = null;
  85429. this.volumetricLightPostProcess = null;
  85430. this.volumetricLightSmoothXPostProcess = null;
  85431. this.volumetricLightSmoothYPostProcess = null;
  85432. this.volumetricLightMergePostProces = null;
  85433. this.volumetricLightFinalPostProcess = null;
  85434. this.lensFlarePostProcess = null;
  85435. this.lensFlareComposePostProcess = null;
  85436. this.luminancePostProcess = null;
  85437. this.hdrPostProcess = null;
  85438. this.hdrFinalPostProcess = null;
  85439. this.depthOfFieldPostProcess = null;
  85440. this.motionBlurPostProcess = null;
  85441. this.fxaaPostProcess = null;
  85442. this.luminanceDownSamplePostProcesses = [];
  85443. this.blurHPostProcesses = [];
  85444. this.blurVPostProcesses = [];
  85445. };
  85446. /**
  85447. * Dispose of the pipeline and stop all post processes
  85448. */
  85449. StandardRenderingPipeline.prototype.dispose = function () {
  85450. this._disposePostProcesses();
  85451. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85452. _super.prototype.dispose.call(this);
  85453. };
  85454. /**
  85455. * Serialize the rendering pipeline (Used when exporting)
  85456. * @returns the serialized object
  85457. */
  85458. StandardRenderingPipeline.prototype.serialize = function () {
  85459. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85460. if (this.sourceLight) {
  85461. serializationObject.sourceLightId = this.sourceLight.id;
  85462. }
  85463. serializationObject.customType = "StandardRenderingPipeline";
  85464. return serializationObject;
  85465. };
  85466. /**
  85467. * Parse the serialized pipeline
  85468. * @param source Source pipeline.
  85469. * @param scene The scene to load the pipeline to.
  85470. * @param rootUrl The URL of the serialized pipeline.
  85471. * @returns An instantiated pipeline from the serialized object.
  85472. */
  85473. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85474. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85475. if (source.sourceLightId) {
  85476. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85477. }
  85478. return p;
  85479. };
  85480. /**
  85481. * Luminance steps
  85482. */
  85483. StandardRenderingPipeline.LuminanceSteps = 6;
  85484. __decorate([
  85485. BABYLON.serialize()
  85486. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85487. __decorate([
  85488. BABYLON.serialize()
  85489. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85490. __decorate([
  85491. BABYLON.serialize()
  85492. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85493. __decorate([
  85494. BABYLON.serialize()
  85495. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85496. __decorate([
  85497. BABYLON.serializeAsTexture("lensTexture")
  85498. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85499. __decorate([
  85500. BABYLON.serialize()
  85501. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85502. __decorate([
  85503. BABYLON.serialize()
  85504. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85505. __decorate([
  85506. BABYLON.serialize()
  85507. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85508. __decorate([
  85509. BABYLON.serialize()
  85510. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85511. __decorate([
  85512. BABYLON.serialize()
  85513. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85514. __decorate([
  85515. BABYLON.serialize()
  85516. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85517. __decorate([
  85518. BABYLON.serializeAsTexture("lensColorTexture")
  85519. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85520. __decorate([
  85521. BABYLON.serialize()
  85522. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85523. __decorate([
  85524. BABYLON.serialize()
  85525. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85526. __decorate([
  85527. BABYLON.serialize()
  85528. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85529. __decorate([
  85530. BABYLON.serialize()
  85531. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85532. __decorate([
  85533. BABYLON.serializeAsTexture("lensStarTexture")
  85534. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85535. __decorate([
  85536. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85537. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85538. __decorate([
  85539. BABYLON.serialize()
  85540. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85541. __decorate([
  85542. BABYLON.serialize()
  85543. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85544. __decorate([
  85545. BABYLON.serialize()
  85546. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85547. __decorate([
  85548. BABYLON.serialize()
  85549. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85550. __decorate([
  85551. BABYLON.serialize()
  85552. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85553. __decorate([
  85554. BABYLON.serialize()
  85555. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85556. __decorate([
  85557. BABYLON.serialize()
  85558. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85559. __decorate([
  85560. BABYLON.serialize()
  85561. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85562. __decorate([
  85563. BABYLON.serialize()
  85564. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85565. __decorate([
  85566. BABYLON.serialize()
  85567. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85568. __decorate([
  85569. BABYLON.serialize()
  85570. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85571. __decorate([
  85572. BABYLON.serialize()
  85573. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85574. __decorate([
  85575. BABYLON.serialize()
  85576. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85577. __decorate([
  85578. BABYLON.serialize()
  85579. ], StandardRenderingPipeline.prototype, "samples", null);
  85580. return StandardRenderingPipeline;
  85581. }(BABYLON.PostProcessRenderPipeline));
  85582. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85583. })(BABYLON || (BABYLON = {}));
  85584. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85585. var BABYLON;
  85586. (function (BABYLON) {
  85587. /**
  85588. * Fxaa post process
  85589. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85590. */
  85591. var FxaaPostProcess = /** @class */ (function (_super) {
  85592. __extends(FxaaPostProcess, _super);
  85593. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85594. if (camera === void 0) { camera = null; }
  85595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85596. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85597. var defines = _this._getDefines();
  85598. _this.updateEffect(defines);
  85599. _this.onApplyObservable.add(function (effect) {
  85600. var texelSize = _this.texelSize;
  85601. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85602. });
  85603. return _this;
  85604. }
  85605. FxaaPostProcess.prototype._getDefines = function () {
  85606. var engine = this.getEngine();
  85607. if (!engine) {
  85608. return null;
  85609. }
  85610. var glInfo = engine.getGlInfo();
  85611. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85612. return "#define MALI 1\n";
  85613. }
  85614. return null;
  85615. };
  85616. return FxaaPostProcess;
  85617. }(BABYLON.PostProcess));
  85618. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85619. })(BABYLON || (BABYLON = {}));
  85620. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85621. var BABYLON;
  85622. (function (BABYLON) {
  85623. /**
  85624. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85625. */
  85626. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85627. __extends(ChromaticAberrationPostProcess, _super);
  85628. /**
  85629. * Creates a new instance ChromaticAberrationPostProcess
  85630. * @param name The name of the effect.
  85631. * @param screenWidth The width of the screen to apply the effect on.
  85632. * @param screenHeight The height of the screen to apply the effect on.
  85633. * @param options The required width/height ratio to downsize to before computing the render pass.
  85634. * @param camera The camera to apply the render pass to.
  85635. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85636. * @param engine The engine which the post process will be applied. (default: current engine)
  85637. * @param reusable If the post process can be reused on the same frame. (default: false)
  85638. * @param textureType Type of textures used when performing the post process. (default: 0)
  85639. * @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)
  85640. */
  85641. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85642. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85643. if (blockCompilation === void 0) { blockCompilation = false; }
  85644. 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;
  85645. /**
  85646. * The amount of seperation of rgb channels (default: 30)
  85647. */
  85648. _this.aberrationAmount = 30;
  85649. /**
  85650. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85651. */
  85652. _this.radialIntensity = 0;
  85653. /**
  85654. * 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))
  85655. */
  85656. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85657. /**
  85658. * 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))
  85659. */
  85660. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85661. _this.onApplyObservable.add(function (effect) {
  85662. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85663. effect.setFloat('screen_width', screenWidth);
  85664. effect.setFloat('screen_height', screenHeight);
  85665. effect.setFloat('radialIntensity', _this.radialIntensity);
  85666. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85667. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85668. });
  85669. return _this;
  85670. }
  85671. return ChromaticAberrationPostProcess;
  85672. }(BABYLON.PostProcess));
  85673. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85674. })(BABYLON || (BABYLON = {}));
  85675. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85676. var BABYLON;
  85677. (function (BABYLON) {
  85678. /**
  85679. * The GrainPostProcess adds noise to the image at mid luminance levels
  85680. */
  85681. var GrainPostProcess = /** @class */ (function (_super) {
  85682. __extends(GrainPostProcess, _super);
  85683. /**
  85684. * Creates a new instance of @see GrainPostProcess
  85685. * @param name The name of the effect.
  85686. * @param options The required width/height ratio to downsize to before computing the render pass.
  85687. * @param camera The camera to apply the render pass to.
  85688. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85689. * @param engine The engine which the post process will be applied. (default: current engine)
  85690. * @param reusable If the post process can be reused on the same frame. (default: false)
  85691. * @param textureType Type of textures used when performing the post process. (default: 0)
  85692. * @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)
  85693. */
  85694. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85695. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85696. if (blockCompilation === void 0) { blockCompilation = false; }
  85697. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85698. /**
  85699. * The intensity of the grain added (default: 30)
  85700. */
  85701. _this.intensity = 30;
  85702. /**
  85703. * If the grain should be randomized on every frame
  85704. */
  85705. _this.animated = false;
  85706. _this.onApplyObservable.add(function (effect) {
  85707. effect.setFloat('intensity', _this.intensity);
  85708. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  85709. });
  85710. return _this;
  85711. }
  85712. return GrainPostProcess;
  85713. }(BABYLON.PostProcess));
  85714. BABYLON.GrainPostProcess = GrainPostProcess;
  85715. })(BABYLON || (BABYLON = {}));
  85716. //# sourceMappingURL=babylon.grainPostProcess.js.map
  85717. var BABYLON;
  85718. (function (BABYLON) {
  85719. /**
  85720. * The SharpenPostProcess applies a sharpen kernel to every pixel
  85721. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85722. */
  85723. var SharpenPostProcess = /** @class */ (function (_super) {
  85724. __extends(SharpenPostProcess, _super);
  85725. /**
  85726. * Creates a new instance ConvolutionPostProcess
  85727. * @param name The name of the effect.
  85728. * @param options The required width/height ratio to downsize to before computing the render pass.
  85729. * @param camera The camera to apply the render pass to.
  85730. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85731. * @param engine The engine which the post process will be applied. (default: current engine)
  85732. * @param reusable If the post process can be reused on the same frame. (default: false)
  85733. * @param textureType Type of textures used when performing the post process. (default: 0)
  85734. * @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)
  85735. */
  85736. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85738. if (blockCompilation === void 0) { blockCompilation = false; }
  85739. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85740. /**
  85741. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  85742. */
  85743. _this.colorAmount = 1.0;
  85744. /**
  85745. * How much sharpness should be applied (default: 0.3)
  85746. */
  85747. _this.edgeAmount = 0.3;
  85748. _this.onApply = function (effect) {
  85749. effect.setFloat2("screenSize", _this.width, _this.height);
  85750. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  85751. };
  85752. return _this;
  85753. }
  85754. return SharpenPostProcess;
  85755. }(BABYLON.PostProcess));
  85756. BABYLON.SharpenPostProcess = SharpenPostProcess;
  85757. })(BABYLON || (BABYLON = {}));
  85758. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  85759. var BABYLON;
  85760. (function (BABYLON) {
  85761. /**
  85762. * The Blur Post Process which blurs an image based on a kernel and direction.
  85763. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  85764. */
  85765. var BlurPostProcess = /** @class */ (function (_super) {
  85766. __extends(BlurPostProcess, _super);
  85767. /**
  85768. * Creates a new instance BlurPostProcess
  85769. * @param name The name of the effect.
  85770. * @param direction The direction in which to blur the image.
  85771. * @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.
  85772. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  85773. * @param camera The camera to apply the render pass to.
  85774. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85775. * @param engine The engine which the post process will be applied. (default: current engine)
  85776. * @param reusable If the post process can be reused on the same frame. (default: false)
  85777. * @param textureType Type of textures used when performing the post process. (default: 0)
  85778. * @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)
  85779. */
  85780. function BlurPostProcess(name,
  85781. /** The direction in which to blur the image. */
  85782. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  85783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85785. if (defines === void 0) { defines = ""; }
  85786. if (blockCompilation === void 0) { blockCompilation = false; }
  85787. 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;
  85788. _this.direction = direction;
  85789. _this.blockCompilation = blockCompilation;
  85790. _this._packedFloat = false;
  85791. _this._staticDefines = "";
  85792. _this._staticDefines = defines;
  85793. _this.onApplyObservable.add(function (effect) {
  85794. if (_this._outputTexture) {
  85795. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  85796. }
  85797. else {
  85798. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  85799. }
  85800. });
  85801. _this.kernel = kernel;
  85802. return _this;
  85803. }
  85804. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  85805. /**
  85806. * Gets the length in pixels of the blur sample region
  85807. */
  85808. get: function () {
  85809. return this._idealKernel;
  85810. },
  85811. /**
  85812. * Sets the length in pixels of the blur sample region
  85813. */
  85814. set: function (v) {
  85815. if (this._idealKernel === v) {
  85816. return;
  85817. }
  85818. v = Math.max(v, 1);
  85819. this._idealKernel = v;
  85820. this._kernel = this._nearestBestKernel(v);
  85821. if (!this.blockCompilation) {
  85822. this._updateParameters();
  85823. }
  85824. },
  85825. enumerable: true,
  85826. configurable: true
  85827. });
  85828. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  85829. /**
  85830. * Gets wether or not the blur is unpacking/repacking floats
  85831. */
  85832. get: function () {
  85833. return this._packedFloat;
  85834. },
  85835. /**
  85836. * Sets wether or not the blur needs to unpack/repack floats
  85837. */
  85838. set: function (v) {
  85839. if (this._packedFloat === v) {
  85840. return;
  85841. }
  85842. this._packedFloat = v;
  85843. if (!this.blockCompilation) {
  85844. this._updateParameters();
  85845. }
  85846. },
  85847. enumerable: true,
  85848. configurable: true
  85849. });
  85850. /**
  85851. * Updates the effect with the current post process compile time values and recompiles the shader.
  85852. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85853. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85854. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85855. * @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
  85856. * @param onCompiled Called when the shader has been compiled.
  85857. * @param onError Called if there is an error when compiling a shader.
  85858. */
  85859. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85860. if (defines === void 0) { defines = null; }
  85861. if (uniforms === void 0) { uniforms = null; }
  85862. if (samplers === void 0) { samplers = null; }
  85863. this._updateParameters(onCompiled, onError);
  85864. };
  85865. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  85866. // Generate sampling offsets and weights
  85867. var N = this._kernel;
  85868. var centerIndex = (N - 1) / 2;
  85869. // Generate Gaussian sampling weights over kernel
  85870. var offsets = [];
  85871. var weights = [];
  85872. var totalWeight = 0;
  85873. for (var i = 0; i < N; i++) {
  85874. var u = i / (N - 1);
  85875. var w = this._gaussianWeight(u * 2.0 - 1);
  85876. offsets[i] = (i - centerIndex);
  85877. weights[i] = w;
  85878. totalWeight += w;
  85879. }
  85880. // Normalize weights
  85881. for (var i = 0; i < weights.length; i++) {
  85882. weights[i] /= totalWeight;
  85883. }
  85884. // Optimize: combine samples to take advantage of hardware linear sampling
  85885. // Walk from left to center, combining pairs (symmetrically)
  85886. var linearSamplingWeights = [];
  85887. var linearSamplingOffsets = [];
  85888. var linearSamplingMap = [];
  85889. for (var i = 0; i <= centerIndex; i += 2) {
  85890. var j = Math.min(i + 1, Math.floor(centerIndex));
  85891. var singleCenterSample = i === j;
  85892. if (singleCenterSample) {
  85893. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  85894. }
  85895. else {
  85896. var sharedCell = j === centerIndex;
  85897. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  85898. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  85899. if (offsetLinear === 0) {
  85900. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  85901. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  85902. }
  85903. else {
  85904. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  85905. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  85906. }
  85907. }
  85908. }
  85909. for (var i = 0; i < linearSamplingMap.length; i++) {
  85910. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  85911. linearSamplingWeights[i] = linearSamplingMap[i].w;
  85912. }
  85913. // Replace with optimized
  85914. offsets = linearSamplingOffsets;
  85915. weights = linearSamplingWeights;
  85916. // Generate shaders
  85917. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  85918. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  85919. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  85920. var defines = "";
  85921. defines += this._staticDefines;
  85922. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  85923. if (this._staticDefines.indexOf("DOF") != -1) {
  85924. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  85925. varyingCount--;
  85926. }
  85927. for (var i = 0; i < varyingCount; i++) {
  85928. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  85929. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  85930. }
  85931. var depCount = 0;
  85932. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  85933. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  85934. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  85935. depCount++;
  85936. }
  85937. if (this.packedFloat) {
  85938. defines += "#define PACKEDFLOAT 1";
  85939. }
  85940. this.blockCompilation = false;
  85941. _super.prototype.updateEffect.call(this, defines, null, null, {
  85942. varyingCount: varyingCount,
  85943. depCount: depCount
  85944. }, onCompiled, onError);
  85945. };
  85946. /**
  85947. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  85948. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  85949. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  85950. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  85951. * The gaps between physical kernels are compensated for in the weighting of the samples
  85952. * @param idealKernel Ideal blur kernel.
  85953. * @return Nearest best kernel.
  85954. */
  85955. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  85956. var v = Math.round(idealKernel);
  85957. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  85958. var k = _a[_i];
  85959. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  85960. return Math.max(k, 3);
  85961. }
  85962. }
  85963. return Math.max(v, 3);
  85964. };
  85965. /**
  85966. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  85967. * @param x The point on the Gaussian distribution to sample.
  85968. * @return the value of the Gaussian function at x.
  85969. */
  85970. BlurPostProcess.prototype._gaussianWeight = function (x) {
  85971. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  85972. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  85973. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  85974. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  85975. // truncated at around 1.3% of peak strength.
  85976. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  85977. var sigma = (1 / 3);
  85978. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  85979. var exponent = -((x * x) / (2.0 * sigma * sigma));
  85980. var weight = (1.0 / denominator) * Math.exp(exponent);
  85981. return weight;
  85982. };
  85983. /**
  85984. * Generates a string that can be used as a floating point number in GLSL.
  85985. * @param x Value to print.
  85986. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  85987. * @return GLSL float string.
  85988. */
  85989. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  85990. if (decimalFigures === void 0) { decimalFigures = 8; }
  85991. return x.toFixed(decimalFigures).replace(/0+$/, '');
  85992. };
  85993. return BlurPostProcess;
  85994. }(BABYLON.PostProcess));
  85995. BABYLON.BlurPostProcess = BlurPostProcess;
  85996. })(BABYLON || (BABYLON = {}));
  85997. //# sourceMappingURL=babylon.blurPostProcess.js.map
  85998. var BABYLON;
  85999. (function (BABYLON) {
  86000. /**
  86001. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  86002. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  86003. * based on samples that have a large difference in distance than the center pixel.
  86004. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86005. */
  86006. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  86007. __extends(DepthOfFieldBlurPostProcess, _super);
  86008. /**
  86009. * Creates a new instance CircleOfConfusionPostProcess
  86010. * @param name The name of the effect.
  86011. * @param scene The scene the effect belongs to.
  86012. * @param direction The direction the blur should be applied.
  86013. * @param kernel The size of the kernel used to blur.
  86014. * @param options The required width/height ratio to downsize to before computing the render pass.
  86015. * @param camera The camera to apply the render pass to.
  86016. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86017. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86018. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86019. * @param engine The engine which the post process will be applied. (default: current engine)
  86020. * @param reusable If the post process can be reused on the same frame. (default: false)
  86021. * @param textureType Type of textures used when performing the post process. (default: 0)
  86022. * @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)
  86023. */
  86024. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86025. if (imageToBlur === void 0) { imageToBlur = null; }
  86026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86027. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86028. if (blockCompilation === void 0) { blockCompilation = false; }
  86029. 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;
  86030. _this.direction = direction;
  86031. _this.onApplyObservable.add(function (effect) {
  86032. if (imageToBlur != null) {
  86033. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86034. }
  86035. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86036. if (scene.activeCamera) {
  86037. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86038. }
  86039. });
  86040. return _this;
  86041. }
  86042. return DepthOfFieldBlurPostProcess;
  86043. }(BABYLON.BlurPostProcess));
  86044. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86045. })(BABYLON || (BABYLON = {}));
  86046. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86047. var BABYLON;
  86048. (function (BABYLON) {
  86049. /**
  86050. * Options to be set when merging outputs from the default pipeline.
  86051. */
  86052. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86053. function DepthOfFieldMergePostProcessOptions() {
  86054. }
  86055. return DepthOfFieldMergePostProcessOptions;
  86056. }());
  86057. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86058. /**
  86059. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86060. */
  86061. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86062. __extends(DepthOfFieldMergePostProcess, _super);
  86063. /**
  86064. * Creates a new instance of DepthOfFieldMergePostProcess
  86065. * @param name The name of the effect.
  86066. * @param originalFromInput Post process which's input will be used for the merge.
  86067. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86068. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86069. * @param options The required width/height ratio to downsize to before computing the render pass.
  86070. * @param camera The camera to apply the render pass to.
  86071. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86072. * @param engine The engine which the post process will be applied. (default: current engine)
  86073. * @param reusable If the post process can be reused on the same frame. (default: false)
  86074. * @param textureType Type of textures used when performing the post process. (default: 0)
  86075. * @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)
  86076. */
  86077. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86078. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86079. if (blockCompilation === void 0) { blockCompilation = false; }
  86080. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86081. _this.blurSteps = blurSteps;
  86082. _this.onApplyObservable.add(function (effect) {
  86083. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86084. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86085. blurSteps.forEach(function (step, index) {
  86086. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86087. });
  86088. });
  86089. if (!blockCompilation) {
  86090. _this.updateEffect();
  86091. }
  86092. return _this;
  86093. }
  86094. /**
  86095. * Updates the effect with the current post process compile time values and recompiles the shader.
  86096. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86097. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86098. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86099. * @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
  86100. * @param onCompiled Called when the shader has been compiled.
  86101. * @param onError Called if there is an error when compiling a shader.
  86102. */
  86103. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86104. if (defines === void 0) { defines = null; }
  86105. if (uniforms === void 0) { uniforms = null; }
  86106. if (samplers === void 0) { samplers = null; }
  86107. if (!defines) {
  86108. defines = "";
  86109. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86110. }
  86111. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86112. };
  86113. return DepthOfFieldMergePostProcess;
  86114. }(BABYLON.PostProcess));
  86115. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86116. })(BABYLON || (BABYLON = {}));
  86117. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86118. var BABYLON;
  86119. (function (BABYLON) {
  86120. /**
  86121. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86122. */
  86123. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86124. __extends(CircleOfConfusionPostProcess, _super);
  86125. /**
  86126. * Creates a new instance CircleOfConfusionPostProcess
  86127. * @param name The name of the effect.
  86128. * @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.
  86129. * @param options The required width/height ratio to downsize to before computing the render pass.
  86130. * @param camera The camera to apply the render pass to.
  86131. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86132. * @param engine The engine which the post process will be applied. (default: current engine)
  86133. * @param reusable If the post process can be reused on the same frame. (default: false)
  86134. * @param textureType Type of textures used when performing the post process. (default: 0)
  86135. * @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)
  86136. */
  86137. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86138. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86139. if (blockCompilation === void 0) { blockCompilation = false; }
  86140. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86141. /**
  86142. * 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.
  86143. */
  86144. _this.lensSize = 50;
  86145. /**
  86146. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86147. */
  86148. _this.fStop = 1.4;
  86149. /**
  86150. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86151. */
  86152. _this.focusDistance = 2000;
  86153. /**
  86154. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86155. */
  86156. _this.focalLength = 50;
  86157. _this._depthTexture = null;
  86158. _this._depthTexture = depthTexture;
  86159. _this.onApplyObservable.add(function (effect) {
  86160. if (!_this._depthTexture) {
  86161. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86162. return;
  86163. }
  86164. effect.setTexture("depthSampler", _this._depthTexture);
  86165. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86166. var aperture = _this.lensSize / _this.fStop;
  86167. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86168. effect.setFloat('focusDistance', _this.focusDistance);
  86169. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86170. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86171. });
  86172. return _this;
  86173. }
  86174. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86175. /**
  86176. * 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.
  86177. */
  86178. set: function (value) {
  86179. this._depthTexture = value;
  86180. },
  86181. enumerable: true,
  86182. configurable: true
  86183. });
  86184. return CircleOfConfusionPostProcess;
  86185. }(BABYLON.PostProcess));
  86186. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86187. })(BABYLON || (BABYLON = {}));
  86188. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86189. var BABYLON;
  86190. (function (BABYLON) {
  86191. /**
  86192. * Specifies the level of max blur that should be applied when using the depth of field effect
  86193. */
  86194. var DepthOfFieldEffectBlurLevel;
  86195. (function (DepthOfFieldEffectBlurLevel) {
  86196. /**
  86197. * Subtle blur
  86198. */
  86199. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86200. /**
  86201. * Medium blur
  86202. */
  86203. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86204. /**
  86205. * Large blur
  86206. */
  86207. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86208. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86209. ;
  86210. /**
  86211. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86212. */
  86213. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86214. __extends(DepthOfFieldEffect, _super);
  86215. /**
  86216. * Creates a new instance DepthOfFieldEffect
  86217. * @param scene The scene the effect belongs to.
  86218. * @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.
  86219. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86220. * @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)
  86221. */
  86222. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86223. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86224. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86225. if (blockCompilation === void 0) { blockCompilation = false; }
  86226. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86227. return _this._effects;
  86228. }, true) || this;
  86229. /**
  86230. * @hidden Internal post processes in depth of field effect
  86231. */
  86232. _this._effects = [];
  86233. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86234. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86235. // 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)
  86236. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86237. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86238. _this._depthOfFieldBlurY = [];
  86239. _this._depthOfFieldBlurX = [];
  86240. var blurCount = 1;
  86241. var kernelSize = 15;
  86242. switch (blurLevel) {
  86243. case DepthOfFieldEffectBlurLevel.High: {
  86244. blurCount = 3;
  86245. kernelSize = 51;
  86246. break;
  86247. }
  86248. case DepthOfFieldEffectBlurLevel.Medium: {
  86249. blurCount = 2;
  86250. kernelSize = 31;
  86251. break;
  86252. }
  86253. default: {
  86254. kernelSize = 15;
  86255. blurCount = 1;
  86256. break;
  86257. }
  86258. }
  86259. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86260. var ratio = 1.0;
  86261. for (var i = 0; i < blurCount; i++) {
  86262. 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);
  86263. blurY.autoClear = false;
  86264. ratio = 0.75 / Math.pow(2, i);
  86265. 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);
  86266. blurX.autoClear = false;
  86267. _this._depthOfFieldBlurY.push(blurY);
  86268. _this._depthOfFieldBlurX.push(blurX);
  86269. }
  86270. // Set all post processes on the effect.
  86271. _this._effects = [_this._circleOfConfusion];
  86272. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86273. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86274. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86275. }
  86276. // Merge blurred images with original image based on circleOfConfusion
  86277. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86278. _this._dofMerge.autoClear = false;
  86279. _this._effects.push(_this._dofMerge);
  86280. return _this;
  86281. }
  86282. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86283. get: function () {
  86284. return this._circleOfConfusion.focalLength;
  86285. },
  86286. /**
  86287. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86288. */
  86289. set: function (value) {
  86290. this._circleOfConfusion.focalLength = value;
  86291. },
  86292. enumerable: true,
  86293. configurable: true
  86294. });
  86295. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86296. get: function () {
  86297. return this._circleOfConfusion.fStop;
  86298. },
  86299. /**
  86300. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86301. */
  86302. set: function (value) {
  86303. this._circleOfConfusion.fStop = value;
  86304. },
  86305. enumerable: true,
  86306. configurable: true
  86307. });
  86308. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86309. get: function () {
  86310. return this._circleOfConfusion.focusDistance;
  86311. },
  86312. /**
  86313. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86314. */
  86315. set: function (value) {
  86316. this._circleOfConfusion.focusDistance = value;
  86317. },
  86318. enumerable: true,
  86319. configurable: true
  86320. });
  86321. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86322. get: function () {
  86323. return this._circleOfConfusion.lensSize;
  86324. },
  86325. /**
  86326. * 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.
  86327. */
  86328. set: function (value) {
  86329. this._circleOfConfusion.lensSize = value;
  86330. },
  86331. enumerable: true,
  86332. configurable: true
  86333. });
  86334. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86335. /**
  86336. * 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.
  86337. */
  86338. set: function (value) {
  86339. this._circleOfConfusion.depthTexture = value;
  86340. },
  86341. enumerable: true,
  86342. configurable: true
  86343. });
  86344. /**
  86345. * Disposes each of the internal effects for a given camera.
  86346. * @param camera The camera to dispose the effect on.
  86347. */
  86348. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86349. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86350. this._effects[effectIndex].dispose(camera);
  86351. }
  86352. };
  86353. /**
  86354. * @hidden Internal
  86355. */
  86356. DepthOfFieldEffect.prototype._updateEffects = function () {
  86357. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86358. this._effects[effectIndex].updateEffect();
  86359. }
  86360. };
  86361. /**
  86362. * Internal
  86363. * @returns if all the contained post processes are ready.
  86364. * @hidden
  86365. */
  86366. DepthOfFieldEffect.prototype._isReady = function () {
  86367. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86368. if (!this._effects[effectIndex].isReady()) {
  86369. return false;
  86370. }
  86371. }
  86372. return true;
  86373. };
  86374. return DepthOfFieldEffect;
  86375. }(BABYLON.PostProcessRenderEffect));
  86376. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86377. })(BABYLON || (BABYLON = {}));
  86378. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86379. var BABYLON;
  86380. (function (BABYLON) {
  86381. /**
  86382. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86383. */
  86384. var BloomMergePostProcess = /** @class */ (function (_super) {
  86385. __extends(BloomMergePostProcess, _super);
  86386. /**
  86387. * Creates a new instance of @see BloomMergePostProcess
  86388. * @param name The name of the effect.
  86389. * @param originalFromInput Post process which's input will be used for the merge.
  86390. * @param blurred Blurred highlights post process which's output will be used.
  86391. * @param weight Weight of the bloom to be added to the original input.
  86392. * @param options The required width/height ratio to downsize to before computing the render pass.
  86393. * @param camera The camera to apply the render pass to.
  86394. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86395. * @param engine The engine which the post process will be applied. (default: current engine)
  86396. * @param reusable If the post process can be reused on the same frame. (default: false)
  86397. * @param textureType Type of textures used when performing the post process. (default: 0)
  86398. * @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)
  86399. */
  86400. function BloomMergePostProcess(name, originalFromInput, blurred,
  86401. /** Weight of the bloom to be added to the original input. */
  86402. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86403. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86404. if (blockCompilation === void 0) { blockCompilation = false; }
  86405. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86406. _this.weight = weight;
  86407. _this.onApplyObservable.add(function (effect) {
  86408. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86409. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86410. effect.setFloat("bloomWeight", _this.weight);
  86411. });
  86412. if (!blockCompilation) {
  86413. _this.updateEffect();
  86414. }
  86415. return _this;
  86416. }
  86417. return BloomMergePostProcess;
  86418. }(BABYLON.PostProcess));
  86419. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86420. })(BABYLON || (BABYLON = {}));
  86421. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86422. var BABYLON;
  86423. (function (BABYLON) {
  86424. /**
  86425. * 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.
  86426. */
  86427. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86428. __extends(ExtractHighlightsPostProcess, _super);
  86429. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86430. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86431. if (blockCompilation === void 0) { blockCompilation = false; }
  86432. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86433. /**
  86434. * The luminance threshold, pixels below this value will be set to black.
  86435. */
  86436. _this.threshold = 0.9;
  86437. /** @hidden */
  86438. _this._exposure = 1;
  86439. /**
  86440. * Post process which has the input texture to be used when performing highlight extraction
  86441. * @hidden
  86442. */
  86443. _this._inputPostProcess = null;
  86444. _this.onApplyObservable.add(function (effect) {
  86445. if (_this._inputPostProcess) {
  86446. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86447. }
  86448. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86449. effect.setFloat('exposure', _this._exposure);
  86450. });
  86451. return _this;
  86452. }
  86453. return ExtractHighlightsPostProcess;
  86454. }(BABYLON.PostProcess));
  86455. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86456. })(BABYLON || (BABYLON = {}));
  86457. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86458. var BABYLON;
  86459. (function (BABYLON) {
  86460. /**
  86461. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86462. */
  86463. var BloomEffect = /** @class */ (function (_super) {
  86464. __extends(BloomEffect, _super);
  86465. /**
  86466. * Creates a new instance of @see BloomEffect
  86467. * @param scene The scene the effect belongs to.
  86468. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86469. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86470. * @param bloomWeight The the strength of bloom.
  86471. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86472. * @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)
  86473. */
  86474. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86475. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86476. if (blockCompilation === void 0) { blockCompilation = false; }
  86477. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86478. return _this._effects;
  86479. }, true) || this;
  86480. _this.bloomScale = bloomScale;
  86481. /**
  86482. * @hidden Internal
  86483. */
  86484. _this._effects = [];
  86485. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86486. _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);
  86487. _this._blurX.alwaysForcePOT = true;
  86488. _this._blurX.autoClear = false;
  86489. _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);
  86490. _this._blurY.alwaysForcePOT = true;
  86491. _this._blurY.autoClear = false;
  86492. _this.kernel = bloomKernel;
  86493. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86494. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86495. _this._merge.autoClear = false;
  86496. _this._effects.push(_this._merge);
  86497. return _this;
  86498. }
  86499. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86500. /**
  86501. * The luminance threshold to find bright areas of the image to bloom.
  86502. */
  86503. get: function () {
  86504. return this._downscale.threshold;
  86505. },
  86506. set: function (value) {
  86507. this._downscale.threshold = value;
  86508. },
  86509. enumerable: true,
  86510. configurable: true
  86511. });
  86512. Object.defineProperty(BloomEffect.prototype, "weight", {
  86513. /**
  86514. * The strength of the bloom.
  86515. */
  86516. get: function () {
  86517. return this._merge.weight;
  86518. },
  86519. set: function (value) {
  86520. this._merge.weight = value;
  86521. },
  86522. enumerable: true,
  86523. configurable: true
  86524. });
  86525. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86526. /**
  86527. * Specifies the size of the bloom blur kernel, relative to the final output size
  86528. */
  86529. get: function () {
  86530. return this._blurX.kernel / this.bloomScale;
  86531. },
  86532. set: function (value) {
  86533. this._blurX.kernel = value * this.bloomScale;
  86534. this._blurY.kernel = value * this.bloomScale;
  86535. },
  86536. enumerable: true,
  86537. configurable: true
  86538. });
  86539. /**
  86540. * Disposes each of the internal effects for a given camera.
  86541. * @param camera The camera to dispose the effect on.
  86542. */
  86543. BloomEffect.prototype.disposeEffects = function (camera) {
  86544. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86545. this._effects[effectIndex].dispose(camera);
  86546. }
  86547. };
  86548. /**
  86549. * @hidden Internal
  86550. */
  86551. BloomEffect.prototype._updateEffects = function () {
  86552. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86553. this._effects[effectIndex].updateEffect();
  86554. }
  86555. };
  86556. /**
  86557. * Internal
  86558. * @returns if all the contained post processes are ready.
  86559. * @hidden
  86560. */
  86561. BloomEffect.prototype._isReady = function () {
  86562. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86563. if (!this._effects[effectIndex].isReady()) {
  86564. return false;
  86565. }
  86566. }
  86567. return true;
  86568. };
  86569. return BloomEffect;
  86570. }(BABYLON.PostProcessRenderEffect));
  86571. BABYLON.BloomEffect = BloomEffect;
  86572. })(BABYLON || (BABYLON = {}));
  86573. //# sourceMappingURL=babylon.bloomEffect.js.map
  86574. var BABYLON;
  86575. (function (BABYLON) {
  86576. /**
  86577. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86578. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86579. */
  86580. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86581. __extends(DefaultRenderingPipeline, _super);
  86582. /**
  86583. * @constructor
  86584. * @param name - The rendering pipeline name (default: "")
  86585. * @param hdr - If high dynamic range textures should be used (default: true)
  86586. * @param scene - The scene linked to this pipeline (default: the last created scene)
  86587. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86588. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86589. */
  86590. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86591. if (name === void 0) { name = ""; }
  86592. if (hdr === void 0) { hdr = true; }
  86593. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86594. if (automaticBuild === void 0) { automaticBuild = true; }
  86595. var _this = _super.call(this, scene.getEngine(), name) || this;
  86596. _this._camerasToBeAttached = [];
  86597. /**
  86598. * ID of the sharpen post process,
  86599. */
  86600. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86601. /**
  86602. * @ignore
  86603. * ID of the image processing post process;
  86604. */
  86605. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86606. /**
  86607. * @ignore
  86608. * ID of the Fast Approximate Anti-Aliasing post process;
  86609. */
  86610. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86611. /**
  86612. * ID of the chromatic aberration post process,
  86613. */
  86614. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86615. /**
  86616. * ID of the grain post process
  86617. */
  86618. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86619. /**
  86620. * Glow post process which adds a glow to emmisive areas of the image
  86621. */
  86622. _this._glowLayer = null;
  86623. /**
  86624. * Animations which can be used to tweak settings over a period of time
  86625. */
  86626. _this.animations = [];
  86627. _this._imageProcessingConfigurationObserver = null;
  86628. // Values
  86629. _this._sharpenEnabled = false;
  86630. _this._bloomEnabled = false;
  86631. _this._depthOfFieldEnabled = false;
  86632. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86633. _this._fxaaEnabled = false;
  86634. _this._imageProcessingEnabled = true;
  86635. _this._bloomScale = 0.5;
  86636. _this._chromaticAberrationEnabled = false;
  86637. _this._grainEnabled = false;
  86638. _this._buildAllowed = true;
  86639. _this._resizeObserver = null;
  86640. _this._hardwareScaleLevel = 1.0;
  86641. _this._bloomKernel = 64;
  86642. /**
  86643. * Specifies the weight of the bloom in the final rendering
  86644. */
  86645. _this._bloomWeight = 0.15;
  86646. /**
  86647. * Specifies the luma threshold for the area that will be blurred by the bloom
  86648. */
  86649. _this._bloomThreshold = 0.9;
  86650. _this._samples = 1;
  86651. _this._hasCleared = false;
  86652. _this._prevPostProcess = null;
  86653. _this._prevPrevPostProcess = null;
  86654. _this._depthOfFieldSceneObserver = null;
  86655. _this._cameras = cameras || scene.cameras;
  86656. _this._cameras = _this._cameras.slice();
  86657. _this._camerasToBeAttached = _this._cameras.slice();
  86658. _this._buildAllowed = automaticBuild;
  86659. // Initialize
  86660. _this._scene = scene;
  86661. var caps = _this._scene.getEngine().getCaps();
  86662. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86663. // Misc
  86664. if (_this._hdr) {
  86665. if (caps.textureHalfFloatRender) {
  86666. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86667. }
  86668. else if (caps.textureFloatRender) {
  86669. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86670. }
  86671. }
  86672. else {
  86673. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86674. }
  86675. // Attach
  86676. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86677. var engine = _this._scene.getEngine();
  86678. // Create post processes before hand so they can be modified before enabled.
  86679. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  86680. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86681. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  86682. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  86683. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  86684. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86685. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  86686. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86687. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  86688. _this._resizeObserver = engine.onResizeObservable.add(function () {
  86689. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  86690. _this.bloomKernel = _this.bloomKernel;
  86691. });
  86692. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  86693. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  86694. });
  86695. _this._buildPipeline();
  86696. return _this;
  86697. }
  86698. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  86699. get: function () {
  86700. return this._sharpenEnabled;
  86701. },
  86702. /**
  86703. * Enable or disable the sharpen process from the pipeline
  86704. */
  86705. set: function (enabled) {
  86706. if (this._sharpenEnabled === enabled) {
  86707. return;
  86708. }
  86709. this._sharpenEnabled = enabled;
  86710. this._buildPipeline();
  86711. },
  86712. enumerable: true,
  86713. configurable: true
  86714. });
  86715. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  86716. /**
  86717. * Specifies the size of the bloom blur kernel, relative to the final output size
  86718. */
  86719. get: function () {
  86720. return this._bloomKernel;
  86721. },
  86722. set: function (value) {
  86723. this._bloomKernel = value;
  86724. this.bloom.kernel = value / this._hardwareScaleLevel;
  86725. },
  86726. enumerable: true,
  86727. configurable: true
  86728. });
  86729. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  86730. get: function () {
  86731. return this._bloomWeight;
  86732. },
  86733. /**
  86734. * The strength of the bloom.
  86735. */
  86736. set: function (value) {
  86737. if (this._bloomWeight === value) {
  86738. return;
  86739. }
  86740. this.bloom.weight = value;
  86741. this._bloomWeight = value;
  86742. },
  86743. enumerable: true,
  86744. configurable: true
  86745. });
  86746. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  86747. get: function () {
  86748. return this._bloomThreshold;
  86749. },
  86750. /**
  86751. * The strength of the bloom.
  86752. */
  86753. set: function (value) {
  86754. if (this._bloomThreshold === value) {
  86755. return;
  86756. }
  86757. this.bloom.threshold = value;
  86758. this._bloomThreshold = value;
  86759. },
  86760. enumerable: true,
  86761. configurable: true
  86762. });
  86763. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  86764. get: function () {
  86765. return this._bloomScale;
  86766. },
  86767. /**
  86768. * The scale of the bloom, lower value will provide better performance.
  86769. */
  86770. set: function (value) {
  86771. if (this._bloomScale === value) {
  86772. return;
  86773. }
  86774. this._bloomScale = value;
  86775. // recreate bloom and dispose old as this setting is not dynamic
  86776. this._rebuildBloom();
  86777. this._buildPipeline();
  86778. },
  86779. enumerable: true,
  86780. configurable: true
  86781. });
  86782. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  86783. get: function () {
  86784. return this._bloomEnabled;
  86785. },
  86786. /**
  86787. * Enable or disable the bloom from the pipeline
  86788. */
  86789. set: function (enabled) {
  86790. if (this._bloomEnabled === enabled) {
  86791. return;
  86792. }
  86793. this._bloomEnabled = enabled;
  86794. this._buildPipeline();
  86795. },
  86796. enumerable: true,
  86797. configurable: true
  86798. });
  86799. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  86800. // recreate bloom and dispose old as this setting is not dynamic
  86801. var oldBloom = this.bloom;
  86802. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  86803. this.bloom.threshold = oldBloom.threshold;
  86804. for (var i = 0; i < this._cameras.length; i++) {
  86805. oldBloom.disposeEffects(this._cameras[i]);
  86806. }
  86807. };
  86808. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  86809. /**
  86810. * If the depth of field is enabled.
  86811. */
  86812. get: function () {
  86813. return this._depthOfFieldEnabled;
  86814. },
  86815. set: function (enabled) {
  86816. if (this._depthOfFieldEnabled === enabled) {
  86817. return;
  86818. }
  86819. this._depthOfFieldEnabled = enabled;
  86820. this._buildPipeline();
  86821. },
  86822. enumerable: true,
  86823. configurable: true
  86824. });
  86825. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  86826. /**
  86827. * Blur level of the depth of field effect. (Higher blur will effect performance)
  86828. */
  86829. get: function () {
  86830. return this._depthOfFieldBlurLevel;
  86831. },
  86832. set: function (value) {
  86833. if (this._depthOfFieldBlurLevel === value) {
  86834. return;
  86835. }
  86836. this._depthOfFieldBlurLevel = value;
  86837. // recreate dof and dispose old as this setting is not dynamic
  86838. var oldDof = this.depthOfField;
  86839. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  86840. this.depthOfField.focalLength = oldDof.focalLength;
  86841. this.depthOfField.focusDistance = oldDof.focusDistance;
  86842. this.depthOfField.fStop = oldDof.fStop;
  86843. this.depthOfField.lensSize = oldDof.lensSize;
  86844. for (var i = 0; i < this._cameras.length; i++) {
  86845. oldDof.disposeEffects(this._cameras[i]);
  86846. }
  86847. this._buildPipeline();
  86848. },
  86849. enumerable: true,
  86850. configurable: true
  86851. });
  86852. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  86853. get: function () {
  86854. return this._fxaaEnabled;
  86855. },
  86856. /**
  86857. * If the anti aliasing is enabled.
  86858. */
  86859. set: function (enabled) {
  86860. if (this._fxaaEnabled === enabled) {
  86861. return;
  86862. }
  86863. this._fxaaEnabled = enabled;
  86864. this._buildPipeline();
  86865. },
  86866. enumerable: true,
  86867. configurable: true
  86868. });
  86869. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  86870. get: function () {
  86871. return this._samples;
  86872. },
  86873. /**
  86874. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86875. */
  86876. set: function (sampleCount) {
  86877. if (this._samples === sampleCount) {
  86878. return;
  86879. }
  86880. this._samples = sampleCount;
  86881. this._buildPipeline();
  86882. },
  86883. enumerable: true,
  86884. configurable: true
  86885. });
  86886. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  86887. get: function () {
  86888. return this._imageProcessingEnabled;
  86889. },
  86890. /**
  86891. * If image processing is enabled.
  86892. */
  86893. set: function (enabled) {
  86894. if (this._imageProcessingEnabled === enabled) {
  86895. return;
  86896. }
  86897. this._imageProcessingEnabled = enabled;
  86898. this._buildPipeline();
  86899. },
  86900. enumerable: true,
  86901. configurable: true
  86902. });
  86903. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  86904. get: function () {
  86905. return this._glowLayer == null;
  86906. },
  86907. /**
  86908. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  86909. */
  86910. set: function (enabled) {
  86911. if (enabled && !this._glowLayer) {
  86912. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  86913. }
  86914. else if (!enabled && this._glowLayer) {
  86915. this._glowLayer.dispose();
  86916. this._glowLayer = null;
  86917. }
  86918. },
  86919. enumerable: true,
  86920. configurable: true
  86921. });
  86922. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  86923. get: function () {
  86924. return this._chromaticAberrationEnabled;
  86925. },
  86926. /**
  86927. * Enable or disable the chromaticAberration process from the pipeline
  86928. */
  86929. set: function (enabled) {
  86930. if (this._chromaticAberrationEnabled === enabled) {
  86931. return;
  86932. }
  86933. this._chromaticAberrationEnabled = enabled;
  86934. this._buildPipeline();
  86935. },
  86936. enumerable: true,
  86937. configurable: true
  86938. });
  86939. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  86940. get: function () {
  86941. return this._grainEnabled;
  86942. },
  86943. /**
  86944. * Enable or disable the grain process from the pipeline
  86945. */
  86946. set: function (enabled) {
  86947. if (this._grainEnabled === enabled) {
  86948. return;
  86949. }
  86950. this._grainEnabled = enabled;
  86951. this._buildPipeline();
  86952. },
  86953. enumerable: true,
  86954. configurable: true
  86955. });
  86956. /**
  86957. * Force the compilation of the entire pipeline.
  86958. */
  86959. DefaultRenderingPipeline.prototype.prepare = function () {
  86960. var previousState = this._buildAllowed;
  86961. this._buildAllowed = true;
  86962. this._buildPipeline();
  86963. this._buildAllowed = previousState;
  86964. };
  86965. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  86966. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  86967. if (this._hasCleared) {
  86968. postProcess.autoClear = false;
  86969. }
  86970. else {
  86971. postProcess.autoClear = true;
  86972. this._scene.autoClear = false;
  86973. this._hasCleared = true;
  86974. }
  86975. if (!skipTextureSharing) {
  86976. if (this._prevPrevPostProcess) {
  86977. postProcess.shareOutputWith(this._prevPrevPostProcess);
  86978. }
  86979. else {
  86980. postProcess.useOwnOutput();
  86981. }
  86982. if (this._prevPostProcess) {
  86983. this._prevPrevPostProcess = this._prevPostProcess;
  86984. }
  86985. this._prevPostProcess = postProcess;
  86986. }
  86987. };
  86988. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  86989. var _this = this;
  86990. if (!this._buildAllowed) {
  86991. return;
  86992. }
  86993. this._scene.autoClear = true;
  86994. var engine = this._scene.getEngine();
  86995. this._disposePostProcesses();
  86996. if (this._cameras !== null) {
  86997. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  86998. // get back cameras to be used to reattach pipeline
  86999. this._cameras = this._camerasToBeAttached.slice();
  87000. }
  87001. this._reset();
  87002. this._prevPostProcess = null;
  87003. this._prevPrevPostProcess = null;
  87004. this._hasCleared = false;
  87005. if (this.depthOfFieldEnabled) {
  87006. // Multi camera suport
  87007. if (this._cameras.length > 1) {
  87008. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  87009. var camera = _a[_i];
  87010. var depthRenderer = this._scene.enableDepthRenderer(camera);
  87011. depthRenderer.useOnlyInActiveCamera = true;
  87012. }
  87013. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  87014. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  87015. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87016. }
  87017. });
  87018. }
  87019. else {
  87020. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87021. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87022. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87023. }
  87024. if (!this.depthOfField._isReady()) {
  87025. this.depthOfField._updateEffects();
  87026. }
  87027. this.addEffect(this.depthOfField);
  87028. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87029. }
  87030. else {
  87031. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87032. }
  87033. if (this.bloomEnabled) {
  87034. if (!this.bloom._isReady()) {
  87035. this.bloom._updateEffects();
  87036. }
  87037. this.addEffect(this.bloom);
  87038. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87039. }
  87040. if (this._imageProcessingEnabled) {
  87041. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87042. if (this._hdr) {
  87043. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87044. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87045. }
  87046. else {
  87047. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87048. }
  87049. }
  87050. if (this.sharpenEnabled) {
  87051. if (!this.sharpen.isReady()) {
  87052. this.sharpen.updateEffect();
  87053. }
  87054. this.addEffect(this._sharpenEffect);
  87055. this._setAutoClearAndTextureSharing(this.sharpen);
  87056. }
  87057. if (this.grainEnabled) {
  87058. if (!this.grain.isReady()) {
  87059. this.grain.updateEffect();
  87060. }
  87061. this.addEffect(this._grainEffect);
  87062. this._setAutoClearAndTextureSharing(this.grain);
  87063. }
  87064. if (this.chromaticAberrationEnabled) {
  87065. if (!this.chromaticAberration.isReady()) {
  87066. this.chromaticAberration.updateEffect();
  87067. }
  87068. this.addEffect(this._chromaticAberrationEffect);
  87069. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87070. }
  87071. if (this.fxaaEnabled) {
  87072. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87073. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87074. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87075. }
  87076. if (this._cameras !== null) {
  87077. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87078. }
  87079. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87080. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87081. }
  87082. };
  87083. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87084. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87085. for (var i = 0; i < this._cameras.length; i++) {
  87086. var camera = this._cameras[i];
  87087. if (this.imageProcessing) {
  87088. this.imageProcessing.dispose(camera);
  87089. }
  87090. if (this.fxaa) {
  87091. this.fxaa.dispose(camera);
  87092. }
  87093. // These are created in the constructor and should not be disposed on every pipeline change
  87094. if (disposeNonRecreated) {
  87095. if (this.sharpen) {
  87096. this.sharpen.dispose(camera);
  87097. }
  87098. if (this.depthOfField) {
  87099. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87100. this.depthOfField.disposeEffects(camera);
  87101. }
  87102. if (this.bloom) {
  87103. this.bloom.disposeEffects(camera);
  87104. }
  87105. if (this.chromaticAberration) {
  87106. this.chromaticAberration.dispose(camera);
  87107. }
  87108. if (this.grain) {
  87109. this.grain.dispose(camera);
  87110. }
  87111. if (this._glowLayer) {
  87112. this._glowLayer.dispose();
  87113. }
  87114. }
  87115. }
  87116. this.imageProcessing = null;
  87117. this.fxaa = null;
  87118. if (disposeNonRecreated) {
  87119. this.sharpen = null;
  87120. this._sharpenEffect = null;
  87121. this.depthOfField = null;
  87122. this.bloom = null;
  87123. this.chromaticAberration = null;
  87124. this._chromaticAberrationEffect = null;
  87125. this.grain = null;
  87126. this._grainEffect = null;
  87127. this._glowLayer = null;
  87128. }
  87129. };
  87130. /**
  87131. * Adds a camera to the pipeline
  87132. * @param camera the camera to be added
  87133. */
  87134. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87135. this._camerasToBeAttached.push(camera);
  87136. this._buildPipeline();
  87137. };
  87138. /**
  87139. * Removes a camera from the pipeline
  87140. * @param camera the camera to remove
  87141. */
  87142. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87143. var index = this._camerasToBeAttached.indexOf(camera);
  87144. this._camerasToBeAttached.splice(index, 1);
  87145. this._buildPipeline();
  87146. };
  87147. /**
  87148. * Dispose of the pipeline and stop all post processes
  87149. */
  87150. DefaultRenderingPipeline.prototype.dispose = function () {
  87151. this._disposePostProcesses(true);
  87152. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87153. this._scene.autoClear = true;
  87154. if (this._resizeObserver) {
  87155. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87156. this._resizeObserver = null;
  87157. }
  87158. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87159. _super.prototype.dispose.call(this);
  87160. };
  87161. /**
  87162. * Serialize the rendering pipeline (Used when exporting)
  87163. * @returns the serialized object
  87164. */
  87165. DefaultRenderingPipeline.prototype.serialize = function () {
  87166. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87167. serializationObject.customType = "DefaultRenderingPipeline";
  87168. return serializationObject;
  87169. };
  87170. /**
  87171. * Parse the serialized pipeline
  87172. * @param source Source pipeline.
  87173. * @param scene The scene to load the pipeline to.
  87174. * @param rootUrl The URL of the serialized pipeline.
  87175. * @returns An instantiated pipeline from the serialized object.
  87176. */
  87177. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87178. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87179. };
  87180. __decorate([
  87181. BABYLON.serialize()
  87182. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87183. __decorate([
  87184. BABYLON.serialize()
  87185. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87186. __decorate([
  87187. BABYLON.serialize()
  87188. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87189. __decorate([
  87190. BABYLON.serialize()
  87191. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87192. __decorate([
  87193. BABYLON.serialize()
  87194. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87195. __decorate([
  87196. BABYLON.serialize()
  87197. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87198. __decorate([
  87199. BABYLON.serialize()
  87200. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87201. __decorate([
  87202. BABYLON.serialize()
  87203. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87204. __decorate([
  87205. BABYLON.serialize()
  87206. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87207. __decorate([
  87208. BABYLON.serialize()
  87209. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87210. __decorate([
  87211. BABYLON.serialize()
  87212. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87213. __decorate([
  87214. BABYLON.serialize()
  87215. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87216. __decorate([
  87217. BABYLON.serialize()
  87218. ], DefaultRenderingPipeline.prototype, "samples", null);
  87219. __decorate([
  87220. BABYLON.serialize()
  87221. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87222. __decorate([
  87223. BABYLON.serialize()
  87224. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87225. __decorate([
  87226. BABYLON.serialize()
  87227. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87228. __decorate([
  87229. BABYLON.serialize()
  87230. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87231. return DefaultRenderingPipeline;
  87232. }(BABYLON.PostProcessRenderPipeline));
  87233. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87234. })(BABYLON || (BABYLON = {}));
  87235. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87236. var BABYLON;
  87237. (function (BABYLON) {
  87238. /**
  87239. * @hidden
  87240. */
  87241. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87242. __extends(ImageProcessingConfigurationDefines, _super);
  87243. function ImageProcessingConfigurationDefines() {
  87244. var _this = _super.call(this) || this;
  87245. _this.IMAGEPROCESSING = false;
  87246. _this.VIGNETTE = false;
  87247. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87248. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87249. _this.TONEMAPPING = false;
  87250. _this.TONEMAPPING_ACES = false;
  87251. _this.CONTRAST = false;
  87252. _this.COLORCURVES = false;
  87253. _this.COLORGRADING = false;
  87254. _this.COLORGRADING3D = false;
  87255. _this.SAMPLER3DGREENDEPTH = false;
  87256. _this.SAMPLER3DBGRMAP = false;
  87257. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87258. _this.EXPOSURE = false;
  87259. _this.rebuild();
  87260. return _this;
  87261. }
  87262. return ImageProcessingConfigurationDefines;
  87263. }(BABYLON.MaterialDefines));
  87264. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87265. /**
  87266. * This groups together the common properties used for image processing either in direct forward pass
  87267. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87268. * or not.
  87269. */
  87270. var ImageProcessingConfiguration = /** @class */ (function () {
  87271. function ImageProcessingConfiguration() {
  87272. /**
  87273. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87274. */
  87275. this.colorCurves = new BABYLON.ColorCurves();
  87276. this._colorCurvesEnabled = false;
  87277. this._colorGradingEnabled = false;
  87278. this._colorGradingWithGreenDepth = true;
  87279. this._colorGradingBGR = true;
  87280. /** @hidden */
  87281. this._exposure = 1.0;
  87282. this._toneMappingEnabled = false;
  87283. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87284. this._contrast = 1.0;
  87285. /**
  87286. * Vignette stretch size.
  87287. */
  87288. this.vignetteStretch = 0;
  87289. /**
  87290. * Vignette centre X Offset.
  87291. */
  87292. this.vignetteCentreX = 0;
  87293. /**
  87294. * Vignette centre Y Offset.
  87295. */
  87296. this.vignetteCentreY = 0;
  87297. /**
  87298. * Vignette weight or intensity of the vignette effect.
  87299. */
  87300. this.vignetteWeight = 1.5;
  87301. /**
  87302. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87303. * if vignetteEnabled is set to true.
  87304. */
  87305. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87306. /**
  87307. * Camera field of view used by the Vignette effect.
  87308. */
  87309. this.vignetteCameraFov = 0.5;
  87310. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87311. this._vignetteEnabled = false;
  87312. this._applyByPostProcess = false;
  87313. this._isEnabled = true;
  87314. /**
  87315. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87316. */
  87317. this.onUpdateParameters = new BABYLON.Observable();
  87318. }
  87319. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87320. /**
  87321. * Gets wether the color curves effect is enabled.
  87322. */
  87323. get: function () {
  87324. return this._colorCurvesEnabled;
  87325. },
  87326. /**
  87327. * Sets wether the color curves effect is enabled.
  87328. */
  87329. set: function (value) {
  87330. if (this._colorCurvesEnabled === value) {
  87331. return;
  87332. }
  87333. this._colorCurvesEnabled = value;
  87334. this._updateParameters();
  87335. },
  87336. enumerable: true,
  87337. configurable: true
  87338. });
  87339. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87340. /**
  87341. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87342. */
  87343. get: function () {
  87344. return this._colorGradingTexture;
  87345. },
  87346. /**
  87347. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87348. */
  87349. set: function (value) {
  87350. if (this._colorGradingTexture === value) {
  87351. return;
  87352. }
  87353. this._colorGradingTexture = value;
  87354. this._updateParameters();
  87355. },
  87356. enumerable: true,
  87357. configurable: true
  87358. });
  87359. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87360. /**
  87361. * Gets wether the color grading effect is enabled.
  87362. */
  87363. get: function () {
  87364. return this._colorGradingEnabled;
  87365. },
  87366. /**
  87367. * Sets wether the color grading effect is enabled.
  87368. */
  87369. set: function (value) {
  87370. if (this._colorGradingEnabled === value) {
  87371. return;
  87372. }
  87373. this._colorGradingEnabled = value;
  87374. this._updateParameters();
  87375. },
  87376. enumerable: true,
  87377. configurable: true
  87378. });
  87379. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87380. /**
  87381. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87382. */
  87383. get: function () {
  87384. return this._colorGradingWithGreenDepth;
  87385. },
  87386. /**
  87387. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87388. */
  87389. set: function (value) {
  87390. if (this._colorGradingWithGreenDepth === value) {
  87391. return;
  87392. }
  87393. this._colorGradingWithGreenDepth = value;
  87394. this._updateParameters();
  87395. },
  87396. enumerable: true,
  87397. configurable: true
  87398. });
  87399. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87400. /**
  87401. * Gets wether the color grading texture contains BGR values.
  87402. */
  87403. get: function () {
  87404. return this._colorGradingBGR;
  87405. },
  87406. /**
  87407. * Sets wether the color grading texture contains BGR values.
  87408. */
  87409. set: function (value) {
  87410. if (this._colorGradingBGR === value) {
  87411. return;
  87412. }
  87413. this._colorGradingBGR = value;
  87414. this._updateParameters();
  87415. },
  87416. enumerable: true,
  87417. configurable: true
  87418. });
  87419. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87420. /**
  87421. * Gets the Exposure used in the effect.
  87422. */
  87423. get: function () {
  87424. return this._exposure;
  87425. },
  87426. /**
  87427. * Sets the Exposure used in the effect.
  87428. */
  87429. set: function (value) {
  87430. if (this._exposure === value) {
  87431. return;
  87432. }
  87433. this._exposure = value;
  87434. this._updateParameters();
  87435. },
  87436. enumerable: true,
  87437. configurable: true
  87438. });
  87439. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87440. /**
  87441. * Gets wether the tone mapping effect is enabled.
  87442. */
  87443. get: function () {
  87444. return this._toneMappingEnabled;
  87445. },
  87446. /**
  87447. * Sets wether the tone mapping effect is enabled.
  87448. */
  87449. set: function (value) {
  87450. if (this._toneMappingEnabled === value) {
  87451. return;
  87452. }
  87453. this._toneMappingEnabled = value;
  87454. this._updateParameters();
  87455. },
  87456. enumerable: true,
  87457. configurable: true
  87458. });
  87459. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87460. /**
  87461. * Gets the type of tone mapping effect.
  87462. */
  87463. get: function () {
  87464. return this._toneMappingType;
  87465. },
  87466. /**
  87467. * Sets the type of tone mapping effect used in BabylonJS.
  87468. */
  87469. set: function (value) {
  87470. if (this._toneMappingType === value) {
  87471. return;
  87472. }
  87473. this._toneMappingType = value;
  87474. this._updateParameters();
  87475. },
  87476. enumerable: true,
  87477. configurable: true
  87478. });
  87479. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87480. /**
  87481. * Gets the contrast used in the effect.
  87482. */
  87483. get: function () {
  87484. return this._contrast;
  87485. },
  87486. /**
  87487. * Sets the contrast used in the effect.
  87488. */
  87489. set: function (value) {
  87490. if (this._contrast === value) {
  87491. return;
  87492. }
  87493. this._contrast = value;
  87494. this._updateParameters();
  87495. },
  87496. enumerable: true,
  87497. configurable: true
  87498. });
  87499. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87500. /**
  87501. * Gets the vignette blend mode allowing different kind of effect.
  87502. */
  87503. get: function () {
  87504. return this._vignetteBlendMode;
  87505. },
  87506. /**
  87507. * Sets the vignette blend mode allowing different kind of effect.
  87508. */
  87509. set: function (value) {
  87510. if (this._vignetteBlendMode === value) {
  87511. return;
  87512. }
  87513. this._vignetteBlendMode = value;
  87514. this._updateParameters();
  87515. },
  87516. enumerable: true,
  87517. configurable: true
  87518. });
  87519. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87520. /**
  87521. * Gets wether the vignette effect is enabled.
  87522. */
  87523. get: function () {
  87524. return this._vignetteEnabled;
  87525. },
  87526. /**
  87527. * Sets wether the vignette effect is enabled.
  87528. */
  87529. set: function (value) {
  87530. if (this._vignetteEnabled === value) {
  87531. return;
  87532. }
  87533. this._vignetteEnabled = value;
  87534. this._updateParameters();
  87535. },
  87536. enumerable: true,
  87537. configurable: true
  87538. });
  87539. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87540. /**
  87541. * Gets wether the image processing is applied through a post process or not.
  87542. */
  87543. get: function () {
  87544. return this._applyByPostProcess;
  87545. },
  87546. /**
  87547. * Sets wether the image processing is applied through a post process or not.
  87548. */
  87549. set: function (value) {
  87550. if (this._applyByPostProcess === value) {
  87551. return;
  87552. }
  87553. this._applyByPostProcess = value;
  87554. this._updateParameters();
  87555. },
  87556. enumerable: true,
  87557. configurable: true
  87558. });
  87559. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87560. /**
  87561. * Gets wether the image processing is enabled or not.
  87562. */
  87563. get: function () {
  87564. return this._isEnabled;
  87565. },
  87566. /**
  87567. * Sets wether the image processing is enabled or not.
  87568. */
  87569. set: function (value) {
  87570. if (this._isEnabled === value) {
  87571. return;
  87572. }
  87573. this._isEnabled = value;
  87574. this._updateParameters();
  87575. },
  87576. enumerable: true,
  87577. configurable: true
  87578. });
  87579. /**
  87580. * Method called each time the image processing information changes requires to recompile the effect.
  87581. */
  87582. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87583. this.onUpdateParameters.notifyObservers(this);
  87584. };
  87585. /**
  87586. * Gets the current class name.
  87587. * @return "ImageProcessingConfiguration"
  87588. */
  87589. ImageProcessingConfiguration.prototype.getClassName = function () {
  87590. return "ImageProcessingConfiguration";
  87591. };
  87592. /**
  87593. * Prepare the list of uniforms associated with the Image Processing effects.
  87594. * @param uniforms The list of uniforms used in the effect
  87595. * @param defines the list of defines currently in use
  87596. */
  87597. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87598. if (defines.EXPOSURE) {
  87599. uniforms.push("exposureLinear");
  87600. }
  87601. if (defines.CONTRAST) {
  87602. uniforms.push("contrast");
  87603. }
  87604. if (defines.COLORGRADING) {
  87605. uniforms.push("colorTransformSettings");
  87606. }
  87607. if (defines.VIGNETTE) {
  87608. uniforms.push("vInverseScreenSize");
  87609. uniforms.push("vignetteSettings1");
  87610. uniforms.push("vignetteSettings2");
  87611. }
  87612. if (defines.COLORCURVES) {
  87613. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87614. }
  87615. };
  87616. /**
  87617. * Prepare the list of samplers associated with the Image Processing effects.
  87618. * @param samplersList The list of uniforms used in the effect
  87619. * @param defines the list of defines currently in use
  87620. */
  87621. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87622. if (defines.COLORGRADING) {
  87623. samplersList.push("txColorTransform");
  87624. }
  87625. };
  87626. /**
  87627. * Prepare the list of defines associated to the shader.
  87628. * @param defines the list of defines to complete
  87629. * @param forPostProcess Define if we are currently in post process mode or not
  87630. */
  87631. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87632. if (forPostProcess === void 0) { forPostProcess = false; }
  87633. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87634. defines.VIGNETTE = false;
  87635. defines.TONEMAPPING = false;
  87636. defines.TONEMAPPING_ACES = false;
  87637. defines.CONTRAST = false;
  87638. defines.EXPOSURE = false;
  87639. defines.COLORCURVES = false;
  87640. defines.COLORGRADING = false;
  87641. defines.COLORGRADING3D = false;
  87642. defines.IMAGEPROCESSING = false;
  87643. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87644. return;
  87645. }
  87646. defines.VIGNETTE = this.vignetteEnabled;
  87647. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87648. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87649. defines.TONEMAPPING = this.toneMappingEnabled;
  87650. switch (this._toneMappingType) {
  87651. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87652. defines.TONEMAPPING_ACES = true;
  87653. break;
  87654. }
  87655. defines.CONTRAST = (this.contrast !== 1.0);
  87656. defines.EXPOSURE = (this.exposure !== 1.0);
  87657. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87658. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87659. if (defines.COLORGRADING) {
  87660. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87661. }
  87662. else {
  87663. defines.COLORGRADING3D = false;
  87664. }
  87665. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87666. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87667. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87668. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87669. };
  87670. /**
  87671. * Returns true if all the image processing information are ready.
  87672. * @returns True if ready, otherwise, false
  87673. */
  87674. ImageProcessingConfiguration.prototype.isReady = function () {
  87675. // Color Grading texure can not be none blocking.
  87676. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87677. };
  87678. /**
  87679. * Binds the image processing to the shader.
  87680. * @param effect The effect to bind to
  87681. * @param aspectRatio Define the current aspect ratio of the effect
  87682. */
  87683. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  87684. if (aspectRatio === void 0) { aspectRatio = 1; }
  87685. // Color Curves
  87686. if (this._colorCurvesEnabled && this.colorCurves) {
  87687. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  87688. }
  87689. // Vignette
  87690. if (this._vignetteEnabled) {
  87691. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  87692. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  87693. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  87694. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  87695. var vignetteScaleX = vignetteScaleY * aspectRatio;
  87696. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  87697. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  87698. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  87699. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  87700. var vignettePower = -2.0 * this.vignetteWeight;
  87701. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  87702. }
  87703. // Exposure
  87704. effect.setFloat("exposureLinear", this.exposure);
  87705. // Contrast
  87706. effect.setFloat("contrast", this.contrast);
  87707. // Color transform settings
  87708. if (this.colorGradingTexture) {
  87709. effect.setTexture("txColorTransform", this.colorGradingTexture);
  87710. var textureSize = this.colorGradingTexture.getSize().height;
  87711. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  87712. 0.5 / textureSize, // textureOffset
  87713. textureSize, // textureSize
  87714. this.colorGradingTexture.level // weight
  87715. );
  87716. }
  87717. };
  87718. /**
  87719. * Clones the current image processing instance.
  87720. * @return The cloned image processing
  87721. */
  87722. ImageProcessingConfiguration.prototype.clone = function () {
  87723. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  87724. };
  87725. /**
  87726. * Serializes the current image processing instance to a json representation.
  87727. * @return a JSON representation
  87728. */
  87729. ImageProcessingConfiguration.prototype.serialize = function () {
  87730. return BABYLON.SerializationHelper.Serialize(this);
  87731. };
  87732. /**
  87733. * Parses the image processing from a json representation.
  87734. * @param source the JSON source to parse
  87735. * @return The parsed image processing
  87736. */
  87737. ImageProcessingConfiguration.Parse = function (source) {
  87738. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  87739. };
  87740. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  87741. /**
  87742. * Used to apply the vignette as a mix with the pixel color.
  87743. */
  87744. get: function () {
  87745. return this._VIGNETTEMODE_MULTIPLY;
  87746. },
  87747. enumerable: true,
  87748. configurable: true
  87749. });
  87750. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  87751. /**
  87752. * Used to apply the vignette as a replacement of the pixel color.
  87753. */
  87754. get: function () {
  87755. return this._VIGNETTEMODE_OPAQUE;
  87756. },
  87757. enumerable: true,
  87758. configurable: true
  87759. });
  87760. /**
  87761. * Default tone mapping applied in BabylonJS.
  87762. */
  87763. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  87764. /**
  87765. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  87766. * to other engines rendering to increase portability.
  87767. */
  87768. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  87769. // Static constants associated to the image processing.
  87770. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  87771. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  87772. __decorate([
  87773. BABYLON.serializeAsColorCurves()
  87774. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  87775. __decorate([
  87776. BABYLON.serialize()
  87777. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  87778. __decorate([
  87779. BABYLON.serializeAsTexture("colorGradingTexture")
  87780. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  87781. __decorate([
  87782. BABYLON.serialize()
  87783. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  87784. __decorate([
  87785. BABYLON.serialize()
  87786. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  87787. __decorate([
  87788. BABYLON.serialize()
  87789. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  87790. __decorate([
  87791. BABYLON.serialize()
  87792. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  87793. __decorate([
  87794. BABYLON.serialize()
  87795. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  87796. __decorate([
  87797. BABYLON.serialize()
  87798. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  87799. __decorate([
  87800. BABYLON.serialize()
  87801. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  87802. __decorate([
  87803. BABYLON.serialize()
  87804. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  87805. __decorate([
  87806. BABYLON.serialize()
  87807. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  87808. __decorate([
  87809. BABYLON.serialize()
  87810. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  87811. __decorate([
  87812. BABYLON.serialize()
  87813. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  87814. __decorate([
  87815. BABYLON.serializeAsColor4()
  87816. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  87817. __decorate([
  87818. BABYLON.serialize()
  87819. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  87820. __decorate([
  87821. BABYLON.serialize()
  87822. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  87823. __decorate([
  87824. BABYLON.serialize()
  87825. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  87826. __decorate([
  87827. BABYLON.serialize()
  87828. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  87829. __decorate([
  87830. BABYLON.serialize()
  87831. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  87832. return ImageProcessingConfiguration;
  87833. }());
  87834. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  87835. })(BABYLON || (BABYLON = {}));
  87836. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  87837. var BABYLON;
  87838. (function (BABYLON) {
  87839. /**
  87840. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  87841. * It can help converting any input color in a desired output one. This can then be used to create effects
  87842. * from sepia, black and white to sixties or futuristic rendering...
  87843. *
  87844. * The only supported format is currently 3dl.
  87845. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  87846. */
  87847. var ColorGradingTexture = /** @class */ (function (_super) {
  87848. __extends(ColorGradingTexture, _super);
  87849. /**
  87850. * Instantiates a ColorGradingTexture from the following parameters.
  87851. *
  87852. * @param url The location of the color gradind data (currently only supporting 3dl)
  87853. * @param scene The scene the texture will be used in
  87854. */
  87855. function ColorGradingTexture(url, scene) {
  87856. var _this = _super.call(this, scene) || this;
  87857. if (!url) {
  87858. return _this;
  87859. }
  87860. _this._engine = scene.getEngine();
  87861. _this._textureMatrix = BABYLON.Matrix.Identity();
  87862. _this.name = url;
  87863. _this.url = url;
  87864. _this.hasAlpha = false;
  87865. _this.isCube = false;
  87866. _this.is3D = _this._engine.webGLVersion > 1;
  87867. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87868. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87869. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87870. _this.anisotropicFilteringLevel = 1;
  87871. _this._texture = _this._getFromCache(url, true);
  87872. if (!_this._texture) {
  87873. if (!scene.useDelayedTextureLoading) {
  87874. _this.loadTexture();
  87875. }
  87876. else {
  87877. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  87878. }
  87879. }
  87880. return _this;
  87881. }
  87882. /**
  87883. * Returns the texture matrix used in most of the material.
  87884. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  87885. */
  87886. ColorGradingTexture.prototype.getTextureMatrix = function () {
  87887. return this._textureMatrix;
  87888. };
  87889. /**
  87890. * Occurs when the file being loaded is a .3dl LUT file.
  87891. */
  87892. ColorGradingTexture.prototype.load3dlTexture = function () {
  87893. var engine = this._engine;
  87894. var texture;
  87895. if (engine.webGLVersion === 1) {
  87896. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87897. }
  87898. else {
  87899. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87900. }
  87901. this._texture = texture;
  87902. var callback = function (text) {
  87903. if (typeof text !== "string") {
  87904. return;
  87905. }
  87906. var data = null;
  87907. var tempData = null;
  87908. var line;
  87909. var lines = text.split('\n');
  87910. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  87911. var maxColor = 0;
  87912. for (var i = 0; i < lines.length; i++) {
  87913. line = lines[i];
  87914. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  87915. continue;
  87916. if (line.indexOf('#') === 0)
  87917. continue;
  87918. var words = line.split(" ");
  87919. if (size === 0) {
  87920. // Number of space + one
  87921. size = words.length;
  87922. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  87923. tempData = new Float32Array(size * size * size * 4);
  87924. continue;
  87925. }
  87926. if (size != 0) {
  87927. var r = Math.max(parseInt(words[0]), 0);
  87928. var g = Math.max(parseInt(words[1]), 0);
  87929. var b = Math.max(parseInt(words[2]), 0);
  87930. maxColor = Math.max(r, maxColor);
  87931. maxColor = Math.max(g, maxColor);
  87932. maxColor = Math.max(b, maxColor);
  87933. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  87934. if (tempData) {
  87935. tempData[pixelStorageIndex + 0] = r;
  87936. tempData[pixelStorageIndex + 1] = g;
  87937. tempData[pixelStorageIndex + 2] = b;
  87938. }
  87939. // Keep for reference in case of back compat problems.
  87940. // pixelIndexSlice++;
  87941. // if (pixelIndexSlice % size == 0) {
  87942. // pixelIndexH++;
  87943. // pixelIndexSlice = 0;
  87944. // if (pixelIndexH % size == 0) {
  87945. // pixelIndexW++;
  87946. // pixelIndexH = 0;
  87947. // }
  87948. // }
  87949. pixelIndexH++;
  87950. if (pixelIndexH % size == 0) {
  87951. pixelIndexSlice++;
  87952. pixelIndexH = 0;
  87953. if (pixelIndexSlice % size == 0) {
  87954. pixelIndexW++;
  87955. pixelIndexSlice = 0;
  87956. }
  87957. }
  87958. }
  87959. }
  87960. if (tempData && data) {
  87961. for (var i = 0; i < tempData.length; i++) {
  87962. if (i > 0 && (i + 1) % 4 === 0) {
  87963. data[i] = 255;
  87964. }
  87965. else {
  87966. var value = tempData[i];
  87967. data[i] = (value / maxColor * 255);
  87968. }
  87969. }
  87970. }
  87971. if (texture.is3D) {
  87972. texture.updateSize(size, size, size);
  87973. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  87974. }
  87975. else {
  87976. texture.updateSize(size * size, size);
  87977. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  87978. }
  87979. };
  87980. var scene = this.getScene();
  87981. if (scene) {
  87982. scene._loadFile(this.url, callback);
  87983. }
  87984. else {
  87985. this._engine._loadFile(this.url, callback);
  87986. }
  87987. return this._texture;
  87988. };
  87989. /**
  87990. * Starts the loading process of the texture.
  87991. */
  87992. ColorGradingTexture.prototype.loadTexture = function () {
  87993. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  87994. this.load3dlTexture();
  87995. }
  87996. };
  87997. /**
  87998. * Clones the color gradind texture.
  87999. */
  88000. ColorGradingTexture.prototype.clone = function () {
  88001. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  88002. // Base texture
  88003. newTexture.level = this.level;
  88004. return newTexture;
  88005. };
  88006. /**
  88007. * Called during delayed load for textures.
  88008. */
  88009. ColorGradingTexture.prototype.delayLoad = function () {
  88010. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88011. return;
  88012. }
  88013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88014. this._texture = this._getFromCache(this.url, true);
  88015. if (!this._texture) {
  88016. this.loadTexture();
  88017. }
  88018. };
  88019. /**
  88020. * Parses a color grading texture serialized by Babylon.
  88021. * @param parsedTexture The texture information being parsedTexture
  88022. * @param scene The scene to load the texture in
  88023. * @param rootUrl The root url of the data assets to load
  88024. * @return A color gradind texture
  88025. */
  88026. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88027. var texture = null;
  88028. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88029. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88030. texture.name = parsedTexture.name;
  88031. texture.level = parsedTexture.level;
  88032. }
  88033. return texture;
  88034. };
  88035. /**
  88036. * Serializes the LUT texture to json format.
  88037. */
  88038. ColorGradingTexture.prototype.serialize = function () {
  88039. if (!this.name) {
  88040. return null;
  88041. }
  88042. var serializationObject = {};
  88043. serializationObject.name = this.name;
  88044. serializationObject.level = this.level;
  88045. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88046. return serializationObject;
  88047. };
  88048. /**
  88049. * Empty line regex stored for GC.
  88050. */
  88051. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88052. return ColorGradingTexture;
  88053. }(BABYLON.BaseTexture));
  88054. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88055. })(BABYLON || (BABYLON = {}));
  88056. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88057. var BABYLON;
  88058. (function (BABYLON) {
  88059. /**
  88060. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88061. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88062. * 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;
  88063. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88064. */
  88065. var ColorCurves = /** @class */ (function () {
  88066. function ColorCurves() {
  88067. this._dirty = true;
  88068. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88069. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88070. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88071. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88072. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88073. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88074. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88075. this._globalHue = 30;
  88076. this._globalDensity = 0;
  88077. this._globalSaturation = 0;
  88078. this._globalExposure = 0;
  88079. this._highlightsHue = 30;
  88080. this._highlightsDensity = 0;
  88081. this._highlightsSaturation = 0;
  88082. this._highlightsExposure = 0;
  88083. this._midtonesHue = 30;
  88084. this._midtonesDensity = 0;
  88085. this._midtonesSaturation = 0;
  88086. this._midtonesExposure = 0;
  88087. this._shadowsHue = 30;
  88088. this._shadowsDensity = 0;
  88089. this._shadowsSaturation = 0;
  88090. this._shadowsExposure = 0;
  88091. }
  88092. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88093. /**
  88094. * Gets the global Hue value.
  88095. * 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).
  88096. */
  88097. get: function () {
  88098. return this._globalHue;
  88099. },
  88100. /**
  88101. * Sets the global Hue value.
  88102. * 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).
  88103. */
  88104. set: function (value) {
  88105. this._globalHue = value;
  88106. this._dirty = true;
  88107. },
  88108. enumerable: true,
  88109. configurable: true
  88110. });
  88111. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88112. /**
  88113. * Gets the global Density value.
  88114. * 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.
  88115. * Values less than zero provide a filter of opposite hue.
  88116. */
  88117. get: function () {
  88118. return this._globalDensity;
  88119. },
  88120. /**
  88121. * Sets the global Density value.
  88122. * 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.
  88123. * Values less than zero provide a filter of opposite hue.
  88124. */
  88125. set: function (value) {
  88126. this._globalDensity = value;
  88127. this._dirty = true;
  88128. },
  88129. enumerable: true,
  88130. configurable: true
  88131. });
  88132. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88133. /**
  88134. * Gets the global Saturation value.
  88135. * 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.
  88136. */
  88137. get: function () {
  88138. return this._globalSaturation;
  88139. },
  88140. /**
  88141. * Sets the global Saturation value.
  88142. * 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.
  88143. */
  88144. set: function (value) {
  88145. this._globalSaturation = value;
  88146. this._dirty = true;
  88147. },
  88148. enumerable: true,
  88149. configurable: true
  88150. });
  88151. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88152. /**
  88153. * Gets the global Exposure value.
  88154. * 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.
  88155. */
  88156. get: function () {
  88157. return this._globalExposure;
  88158. },
  88159. /**
  88160. * Sets the global Exposure value.
  88161. * 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.
  88162. */
  88163. set: function (value) {
  88164. this._globalExposure = value;
  88165. this._dirty = true;
  88166. },
  88167. enumerable: true,
  88168. configurable: true
  88169. });
  88170. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88171. /**
  88172. * Gets the highlights Hue value.
  88173. * 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).
  88174. */
  88175. get: function () {
  88176. return this._highlightsHue;
  88177. },
  88178. /**
  88179. * Sets the highlights Hue value.
  88180. * 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).
  88181. */
  88182. set: function (value) {
  88183. this._highlightsHue = value;
  88184. this._dirty = true;
  88185. },
  88186. enumerable: true,
  88187. configurable: true
  88188. });
  88189. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88190. /**
  88191. * Gets the highlights Density value.
  88192. * 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.
  88193. * Values less than zero provide a filter of opposite hue.
  88194. */
  88195. get: function () {
  88196. return this._highlightsDensity;
  88197. },
  88198. /**
  88199. * Sets the highlights Density value.
  88200. * 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.
  88201. * Values less than zero provide a filter of opposite hue.
  88202. */
  88203. set: function (value) {
  88204. this._highlightsDensity = value;
  88205. this._dirty = true;
  88206. },
  88207. enumerable: true,
  88208. configurable: true
  88209. });
  88210. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88211. /**
  88212. * Gets the highlights Saturation value.
  88213. * 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.
  88214. */
  88215. get: function () {
  88216. return this._highlightsSaturation;
  88217. },
  88218. /**
  88219. * Sets the highlights Saturation value.
  88220. * 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.
  88221. */
  88222. set: function (value) {
  88223. this._highlightsSaturation = value;
  88224. this._dirty = true;
  88225. },
  88226. enumerable: true,
  88227. configurable: true
  88228. });
  88229. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88230. /**
  88231. * Gets the highlights Exposure value.
  88232. * 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.
  88233. */
  88234. get: function () {
  88235. return this._highlightsExposure;
  88236. },
  88237. /**
  88238. * Sets the highlights Exposure value.
  88239. * 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.
  88240. */
  88241. set: function (value) {
  88242. this._highlightsExposure = value;
  88243. this._dirty = true;
  88244. },
  88245. enumerable: true,
  88246. configurable: true
  88247. });
  88248. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88249. /**
  88250. * Gets the midtones Hue value.
  88251. * 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).
  88252. */
  88253. get: function () {
  88254. return this._midtonesHue;
  88255. },
  88256. /**
  88257. * Sets the midtones Hue value.
  88258. * 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).
  88259. */
  88260. set: function (value) {
  88261. this._midtonesHue = value;
  88262. this._dirty = true;
  88263. },
  88264. enumerable: true,
  88265. configurable: true
  88266. });
  88267. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88268. /**
  88269. * Gets the midtones Density value.
  88270. * 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.
  88271. * Values less than zero provide a filter of opposite hue.
  88272. */
  88273. get: function () {
  88274. return this._midtonesDensity;
  88275. },
  88276. /**
  88277. * Sets the midtones Density value.
  88278. * 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.
  88279. * Values less than zero provide a filter of opposite hue.
  88280. */
  88281. set: function (value) {
  88282. this._midtonesDensity = value;
  88283. this._dirty = true;
  88284. },
  88285. enumerable: true,
  88286. configurable: true
  88287. });
  88288. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88289. /**
  88290. * Gets the midtones Saturation value.
  88291. * 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.
  88292. */
  88293. get: function () {
  88294. return this._midtonesSaturation;
  88295. },
  88296. /**
  88297. * Sets the midtones Saturation value.
  88298. * 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.
  88299. */
  88300. set: function (value) {
  88301. this._midtonesSaturation = value;
  88302. this._dirty = true;
  88303. },
  88304. enumerable: true,
  88305. configurable: true
  88306. });
  88307. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88308. /**
  88309. * Gets the midtones Exposure value.
  88310. * 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.
  88311. */
  88312. get: function () {
  88313. return this._midtonesExposure;
  88314. },
  88315. /**
  88316. * Sets the midtones Exposure value.
  88317. * 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.
  88318. */
  88319. set: function (value) {
  88320. this._midtonesExposure = value;
  88321. this._dirty = true;
  88322. },
  88323. enumerable: true,
  88324. configurable: true
  88325. });
  88326. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88327. /**
  88328. * Gets the shadows Hue value.
  88329. * 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).
  88330. */
  88331. get: function () {
  88332. return this._shadowsHue;
  88333. },
  88334. /**
  88335. * Sets the shadows Hue value.
  88336. * 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).
  88337. */
  88338. set: function (value) {
  88339. this._shadowsHue = value;
  88340. this._dirty = true;
  88341. },
  88342. enumerable: true,
  88343. configurable: true
  88344. });
  88345. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88346. /**
  88347. * Gets the shadows Density value.
  88348. * 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.
  88349. * Values less than zero provide a filter of opposite hue.
  88350. */
  88351. get: function () {
  88352. return this._shadowsDensity;
  88353. },
  88354. /**
  88355. * Sets the shadows Density value.
  88356. * 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.
  88357. * Values less than zero provide a filter of opposite hue.
  88358. */
  88359. set: function (value) {
  88360. this._shadowsDensity = value;
  88361. this._dirty = true;
  88362. },
  88363. enumerable: true,
  88364. configurable: true
  88365. });
  88366. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88367. /**
  88368. * Gets the shadows Saturation value.
  88369. * 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.
  88370. */
  88371. get: function () {
  88372. return this._shadowsSaturation;
  88373. },
  88374. /**
  88375. * Sets the shadows Saturation value.
  88376. * 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.
  88377. */
  88378. set: function (value) {
  88379. this._shadowsSaturation = value;
  88380. this._dirty = true;
  88381. },
  88382. enumerable: true,
  88383. configurable: true
  88384. });
  88385. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88386. /**
  88387. * Gets the shadows Exposure value.
  88388. * 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.
  88389. */
  88390. get: function () {
  88391. return this._shadowsExposure;
  88392. },
  88393. /**
  88394. * Sets the shadows Exposure value.
  88395. * 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.
  88396. */
  88397. set: function (value) {
  88398. this._shadowsExposure = value;
  88399. this._dirty = true;
  88400. },
  88401. enumerable: true,
  88402. configurable: true
  88403. });
  88404. /**
  88405. * Returns the class name
  88406. * @returns The class name
  88407. */
  88408. ColorCurves.prototype.getClassName = function () {
  88409. return "ColorCurves";
  88410. };
  88411. /**
  88412. * Binds the color curves to the shader.
  88413. * @param colorCurves The color curve to bind
  88414. * @param effect The effect to bind to
  88415. * @param positiveUniform The positive uniform shader parameter
  88416. * @param neutralUniform The neutral uniform shader parameter
  88417. * @param negativeUniform The negative uniform shader parameter
  88418. */
  88419. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88420. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88421. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88422. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88423. if (colorCurves._dirty) {
  88424. colorCurves._dirty = false;
  88425. // Fill in global info.
  88426. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88427. // Compute highlights info.
  88428. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88429. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88430. // Compute midtones info.
  88431. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88432. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88433. // Compute shadows info.
  88434. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88435. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88436. // Compute deltas (neutral is midtones).
  88437. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88438. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88439. }
  88440. if (effect) {
  88441. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88442. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88443. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88444. }
  88445. };
  88446. /**
  88447. * Prepare the list of uniforms associated with the ColorCurves effects.
  88448. * @param uniformsList The list of uniforms used in the effect
  88449. */
  88450. ColorCurves.PrepareUniforms = function (uniformsList) {
  88451. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88452. };
  88453. /**
  88454. * Returns color grading data based on a hue, density, saturation and exposure value.
  88455. * @param filterHue The hue of the color filter.
  88456. * @param filterDensity The density of the color filter.
  88457. * @param saturation The saturation.
  88458. * @param exposure The exposure.
  88459. * @param result The result data container.
  88460. */
  88461. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88462. if (hue == null) {
  88463. return;
  88464. }
  88465. hue = ColorCurves.clamp(hue, 0, 360);
  88466. density = ColorCurves.clamp(density, -100, 100);
  88467. saturation = ColorCurves.clamp(saturation, -100, 100);
  88468. exposure = ColorCurves.clamp(exposure, -100, 100);
  88469. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88470. // so that the maximum filter density is only 50% control. This provides fine control
  88471. // for small values and reasonable range.
  88472. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88473. density *= 0.5;
  88474. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88475. if (density < 0) {
  88476. density *= -1;
  88477. hue = (hue + 180) % 360;
  88478. }
  88479. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88480. result.scaleToRef(2, result);
  88481. result.a = 1 + 0.01 * saturation;
  88482. };
  88483. /**
  88484. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88485. * @param value The input slider value in range [-100,100].
  88486. * @returns Adjusted value.
  88487. */
  88488. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88489. value /= 100;
  88490. var x = Math.abs(value);
  88491. x = Math.pow(x, 2);
  88492. if (value < 0) {
  88493. x *= -1;
  88494. }
  88495. x *= 100;
  88496. return x;
  88497. };
  88498. /**
  88499. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88500. * @param hue The hue (H) input.
  88501. * @param saturation The saturation (S) input.
  88502. * @param brightness The brightness (B) input.
  88503. * @result An RGBA color represented as Vector4.
  88504. */
  88505. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88506. var h = ColorCurves.clamp(hue, 0, 360);
  88507. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88508. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88509. if (s === 0) {
  88510. result.r = v;
  88511. result.g = v;
  88512. result.b = v;
  88513. }
  88514. else {
  88515. // sector 0 to 5
  88516. h /= 60;
  88517. var i = Math.floor(h);
  88518. // fractional part of h
  88519. var f = h - i;
  88520. var p = v * (1 - s);
  88521. var q = v * (1 - s * f);
  88522. var t = v * (1 - s * (1 - f));
  88523. switch (i) {
  88524. case 0:
  88525. result.r = v;
  88526. result.g = t;
  88527. result.b = p;
  88528. break;
  88529. case 1:
  88530. result.r = q;
  88531. result.g = v;
  88532. result.b = p;
  88533. break;
  88534. case 2:
  88535. result.r = p;
  88536. result.g = v;
  88537. result.b = t;
  88538. break;
  88539. case 3:
  88540. result.r = p;
  88541. result.g = q;
  88542. result.b = v;
  88543. break;
  88544. case 4:
  88545. result.r = t;
  88546. result.g = p;
  88547. result.b = v;
  88548. break;
  88549. default: // case 5:
  88550. result.r = v;
  88551. result.g = p;
  88552. result.b = q;
  88553. break;
  88554. }
  88555. }
  88556. result.a = 1;
  88557. };
  88558. /**
  88559. * Returns a value clamped between min and max
  88560. * @param value The value to clamp
  88561. * @param min The minimum of value
  88562. * @param max The maximum of value
  88563. * @returns The clamped value.
  88564. */
  88565. ColorCurves.clamp = function (value, min, max) {
  88566. return Math.min(Math.max(value, min), max);
  88567. };
  88568. /**
  88569. * Clones the current color curve instance.
  88570. * @return The cloned curves
  88571. */
  88572. ColorCurves.prototype.clone = function () {
  88573. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88574. };
  88575. /**
  88576. * Serializes the current color curve instance to a json representation.
  88577. * @return a JSON representation
  88578. */
  88579. ColorCurves.prototype.serialize = function () {
  88580. return BABYLON.SerializationHelper.Serialize(this);
  88581. };
  88582. /**
  88583. * Parses the color curve from a json representation.
  88584. * @param source the JSON source to parse
  88585. * @return The parsed curves
  88586. */
  88587. ColorCurves.Parse = function (source) {
  88588. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88589. };
  88590. __decorate([
  88591. BABYLON.serialize()
  88592. ], ColorCurves.prototype, "_globalHue", void 0);
  88593. __decorate([
  88594. BABYLON.serialize()
  88595. ], ColorCurves.prototype, "_globalDensity", void 0);
  88596. __decorate([
  88597. BABYLON.serialize()
  88598. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88599. __decorate([
  88600. BABYLON.serialize()
  88601. ], ColorCurves.prototype, "_globalExposure", void 0);
  88602. __decorate([
  88603. BABYLON.serialize()
  88604. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88605. __decorate([
  88606. BABYLON.serialize()
  88607. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88608. __decorate([
  88609. BABYLON.serialize()
  88610. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88611. __decorate([
  88612. BABYLON.serialize()
  88613. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88614. __decorate([
  88615. BABYLON.serialize()
  88616. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88617. __decorate([
  88618. BABYLON.serialize()
  88619. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88620. __decorate([
  88621. BABYLON.serialize()
  88622. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88623. __decorate([
  88624. BABYLON.serialize()
  88625. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88626. return ColorCurves;
  88627. }());
  88628. BABYLON.ColorCurves = ColorCurves;
  88629. })(BABYLON || (BABYLON = {}));
  88630. //# sourceMappingURL=babylon.colorCurves.js.map
  88631. var BABYLON;
  88632. (function (BABYLON) {
  88633. /**
  88634. * Post process which applies a refractin texture
  88635. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88636. */
  88637. var RefractionPostProcess = /** @class */ (function (_super) {
  88638. __extends(RefractionPostProcess, _super);
  88639. /**
  88640. * Initializes the RefractionPostProcess
  88641. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88642. * @param name The name of the effect.
  88643. * @param refractionTextureUrl Url of the refraction texture to use
  88644. * @param color the base color of the refraction (used to taint the rendering)
  88645. * @param depth simulated refraction depth
  88646. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88647. * @param camera The camera to apply the render pass to.
  88648. * @param options The required width/height ratio to downsize to before computing the render pass.
  88649. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88650. * @param engine The engine which the post process will be applied. (default: current engine)
  88651. * @param reusable If the post process can be reused on the same frame. (default: false)
  88652. */
  88653. function RefractionPostProcess(name, refractionTextureUrl,
  88654. /** the base color of the refraction (used to taint the rendering) */
  88655. color,
  88656. /** simulated refraction depth */
  88657. depth,
  88658. /** the coefficient of the base color (0 to remove base color tainting) */
  88659. colorLevel, options, camera, samplingMode, engine, reusable) {
  88660. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88661. _this.color = color;
  88662. _this.depth = depth;
  88663. _this.colorLevel = colorLevel;
  88664. _this._ownRefractionTexture = true;
  88665. _this.onActivateObservable.add(function (cam) {
  88666. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88667. });
  88668. _this.onApplyObservable.add(function (effect) {
  88669. effect.setColor3("baseColor", _this.color);
  88670. effect.setFloat("depth", _this.depth);
  88671. effect.setFloat("colorLevel", _this.colorLevel);
  88672. effect.setTexture("refractionSampler", _this._refTexture);
  88673. });
  88674. return _this;
  88675. }
  88676. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  88677. /**
  88678. * Gets or sets the refraction texture
  88679. * Please note that you are responsible for disposing the texture if you set it manually
  88680. */
  88681. get: function () {
  88682. return this._refTexture;
  88683. },
  88684. set: function (value) {
  88685. if (this._refTexture && this._ownRefractionTexture) {
  88686. this._refTexture.dispose();
  88687. }
  88688. this._refTexture = value;
  88689. this._ownRefractionTexture = false;
  88690. },
  88691. enumerable: true,
  88692. configurable: true
  88693. });
  88694. // Methods
  88695. /**
  88696. * Disposes of the post process
  88697. * @param camera Camera to dispose post process on
  88698. */
  88699. RefractionPostProcess.prototype.dispose = function (camera) {
  88700. if (this._refTexture && this._ownRefractionTexture) {
  88701. this._refTexture.dispose();
  88702. this._refTexture = null;
  88703. }
  88704. _super.prototype.dispose.call(this, camera);
  88705. };
  88706. return RefractionPostProcess;
  88707. }(BABYLON.PostProcess));
  88708. BABYLON.RefractionPostProcess = RefractionPostProcess;
  88709. })(BABYLON || (BABYLON = {}));
  88710. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  88711. var BABYLON;
  88712. (function (BABYLON) {
  88713. /**
  88714. * Post process used to render in black and white
  88715. */
  88716. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  88717. __extends(BlackAndWhitePostProcess, _super);
  88718. /**
  88719. * Creates a black and white post process
  88720. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  88721. * @param name The name of the effect.
  88722. * @param options The required width/height ratio to downsize to before computing the render pass.
  88723. * @param camera The camera to apply the render pass to.
  88724. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88725. * @param engine The engine which the post process will be applied. (default: current engine)
  88726. * @param reusable If the post process can be reused on the same frame. (default: false)
  88727. */
  88728. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  88729. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  88730. /**
  88731. * Linear about to convert he result to black and white (default: 1)
  88732. */
  88733. _this.degree = 1;
  88734. _this.onApplyObservable.add(function (effect) {
  88735. effect.setFloat("degree", _this.degree);
  88736. });
  88737. return _this;
  88738. }
  88739. return BlackAndWhitePostProcess;
  88740. }(BABYLON.PostProcess));
  88741. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  88742. })(BABYLON || (BABYLON = {}));
  88743. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  88744. var BABYLON;
  88745. (function (BABYLON) {
  88746. /**
  88747. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  88748. * input texture to perform effects such as edge detection or sharpening
  88749. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  88750. */
  88751. var ConvolutionPostProcess = /** @class */ (function (_super) {
  88752. __extends(ConvolutionPostProcess, _super);
  88753. /**
  88754. * Creates a new instance ConvolutionPostProcess
  88755. * @param name The name of the effect.
  88756. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  88757. * @param options The required width/height ratio to downsize to before computing the render pass.
  88758. * @param camera The camera to apply the render pass to.
  88759. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88760. * @param engine The engine which the post process will be applied. (default: current engine)
  88761. * @param reusable If the post process can be reused on the same frame. (default: false)
  88762. * @param textureType Type of textures used when performing the post process. (default: 0)
  88763. */
  88764. function ConvolutionPostProcess(name,
  88765. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  88766. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  88767. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88768. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88769. _this.kernel = kernel;
  88770. _this.onApply = function (effect) {
  88771. effect.setFloat2("screenSize", _this.width, _this.height);
  88772. effect.setArray("kernel", _this.kernel);
  88773. };
  88774. return _this;
  88775. }
  88776. // Statics
  88777. /**
  88778. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88779. */
  88780. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  88781. /**
  88782. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88783. */
  88784. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  88785. /**
  88786. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88787. */
  88788. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  88789. /**
  88790. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88791. */
  88792. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  88793. /**
  88794. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88795. */
  88796. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  88797. /**
  88798. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88799. */
  88800. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  88801. return ConvolutionPostProcess;
  88802. }(BABYLON.PostProcess));
  88803. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  88804. })(BABYLON || (BABYLON = {}));
  88805. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  88806. var BABYLON;
  88807. (function (BABYLON) {
  88808. /**
  88809. * Applies a kernel filter to the image
  88810. */
  88811. var FilterPostProcess = /** @class */ (function (_super) {
  88812. __extends(FilterPostProcess, _super);
  88813. /**
  88814. *
  88815. * @param name The name of the effect.
  88816. * @param kernelMatrix The matrix to be applied to the image
  88817. * @param options The required width/height ratio to downsize to before computing the render pass.
  88818. * @param camera The camera to apply the render pass to.
  88819. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88820. * @param engine The engine which the post process will be applied. (default: current engine)
  88821. * @param reusable If the post process can be reused on the same frame. (default: false)
  88822. */
  88823. function FilterPostProcess(name,
  88824. /** The matrix to be applied to the image */
  88825. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  88826. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  88827. _this.kernelMatrix = kernelMatrix;
  88828. _this.onApply = function (effect) {
  88829. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  88830. };
  88831. return _this;
  88832. }
  88833. return FilterPostProcess;
  88834. }(BABYLON.PostProcess));
  88835. BABYLON.FilterPostProcess = FilterPostProcess;
  88836. })(BABYLON || (BABYLON = {}));
  88837. //# sourceMappingURL=babylon.filterPostProcess.js.map
  88838. var BABYLON;
  88839. (function (BABYLON) {
  88840. /**
  88841. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  88842. */
  88843. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  88844. __extends(VolumetricLightScatteringPostProcess, _super);
  88845. /**
  88846. * @constructor
  88847. * @param name The post-process name
  88848. * @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)
  88849. * @param camera The camera that the post-process will be attached to
  88850. * @param mesh The mesh used to create the light scattering
  88851. * @param samples The post-process quality, default 100
  88852. * @param samplingModeThe post-process filtering mode
  88853. * @param engine The babylon engine
  88854. * @param reusable If the post-process is reusable
  88855. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  88856. */
  88857. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  88858. if (samples === void 0) { samples = 100; }
  88859. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88860. 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;
  88861. _this._screenCoordinates = BABYLON.Vector2.Zero();
  88862. /**
  88863. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  88864. */
  88865. _this.customMeshPosition = BABYLON.Vector3.Zero();
  88866. /**
  88867. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  88868. */
  88869. _this.useCustomMeshPosition = false;
  88870. /**
  88871. * If the post-process should inverse the light scattering direction
  88872. */
  88873. _this.invert = true;
  88874. /**
  88875. * Array containing the excluded meshes not rendered in the internal pass
  88876. */
  88877. _this.excludedMeshes = new Array();
  88878. /**
  88879. * Controls the overall intensity of the post-process
  88880. */
  88881. _this.exposure = 0.3;
  88882. /**
  88883. * Dissipates each sample's contribution in range [0, 1]
  88884. */
  88885. _this.decay = 0.96815;
  88886. /**
  88887. * Controls the overall intensity of each sample
  88888. */
  88889. _this.weight = 0.58767;
  88890. /**
  88891. * Controls the density of each sample
  88892. */
  88893. _this.density = 0.926;
  88894. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  88895. engine = scene.getEngine();
  88896. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  88897. // Configure mesh
  88898. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  88899. // Configure
  88900. _this._createPass(scene, ratio.passRatio || ratio);
  88901. _this.onActivate = function (camera) {
  88902. if (!_this.isSupported) {
  88903. _this.dispose(camera);
  88904. }
  88905. _this.onActivate = null;
  88906. };
  88907. _this.onApplyObservable.add(function (effect) {
  88908. _this._updateMeshScreenCoordinates(scene);
  88909. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  88910. effect.setFloat("exposure", _this.exposure);
  88911. effect.setFloat("decay", _this.decay);
  88912. effect.setFloat("weight", _this.weight);
  88913. effect.setFloat("density", _this.density);
  88914. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  88915. });
  88916. return _this;
  88917. }
  88918. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  88919. /**
  88920. * @hidden
  88921. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  88922. */
  88923. get: function () {
  88924. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  88925. return false;
  88926. },
  88927. set: function (useDiffuseColor) {
  88928. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  88929. },
  88930. enumerable: true,
  88931. configurable: true
  88932. });
  88933. /**
  88934. * Returns the string "VolumetricLightScatteringPostProcess"
  88935. * @returns "VolumetricLightScatteringPostProcess"
  88936. */
  88937. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  88938. return "VolumetricLightScatteringPostProcess";
  88939. };
  88940. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  88941. var mesh = subMesh.getMesh();
  88942. // Render this.mesh as default
  88943. if (mesh === this.mesh && mesh.material) {
  88944. return mesh.material.isReady(mesh);
  88945. }
  88946. var defines = [];
  88947. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88948. var material = subMesh.getMaterial();
  88949. // Alpha test
  88950. if (material) {
  88951. if (material.needAlphaTesting()) {
  88952. defines.push("#define ALPHATEST");
  88953. }
  88954. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88955. attribs.push(BABYLON.VertexBuffer.UVKind);
  88956. defines.push("#define UV1");
  88957. }
  88958. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88959. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88960. defines.push("#define UV2");
  88961. }
  88962. }
  88963. // Bones
  88964. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88965. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88966. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88967. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88968. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88969. }
  88970. else {
  88971. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88972. }
  88973. // Instances
  88974. if (useInstances) {
  88975. defines.push("#define INSTANCES");
  88976. attribs.push("world0");
  88977. attribs.push("world1");
  88978. attribs.push("world2");
  88979. attribs.push("world3");
  88980. }
  88981. // Get correct effect
  88982. var join = defines.join("\n");
  88983. if (this._cachedDefines !== join) {
  88984. this._cachedDefines = join;
  88985. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  88986. }
  88987. return this._volumetricLightScatteringPass.isReady();
  88988. };
  88989. /**
  88990. * Sets the new light position for light scattering effect
  88991. * @param position The new custom light position
  88992. */
  88993. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  88994. this.customMeshPosition = position;
  88995. };
  88996. /**
  88997. * Returns the light position for light scattering effect
  88998. * @return Vector3 The custom light position
  88999. */
  89000. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  89001. return this.customMeshPosition;
  89002. };
  89003. /**
  89004. * Disposes the internal assets and detaches the post-process from the camera
  89005. */
  89006. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  89007. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  89008. if (rttIndex !== -1) {
  89009. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  89010. }
  89011. this._volumetricLightScatteringRTT.dispose();
  89012. _super.prototype.dispose.call(this, camera);
  89013. };
  89014. /**
  89015. * Returns the render target texture used by the post-process
  89016. * @return the render target texture used by the post-process
  89017. */
  89018. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89019. return this._volumetricLightScatteringRTT;
  89020. };
  89021. // Private methods
  89022. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89023. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89024. return true;
  89025. }
  89026. return false;
  89027. };
  89028. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89029. var _this = this;
  89030. var engine = scene.getEngine();
  89031. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89032. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89033. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89034. this._volumetricLightScatteringRTT.renderList = null;
  89035. this._volumetricLightScatteringRTT.renderParticles = false;
  89036. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89037. var camera = this.getCamera();
  89038. if (camera) {
  89039. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89040. }
  89041. else {
  89042. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89043. }
  89044. // Custom render function for submeshes
  89045. var renderSubMesh = function (subMesh) {
  89046. var mesh = subMesh.getRenderingMesh();
  89047. if (_this._meshExcluded(mesh)) {
  89048. return;
  89049. }
  89050. var material = subMesh.getMaterial();
  89051. if (!material) {
  89052. return;
  89053. }
  89054. var scene = mesh.getScene();
  89055. var engine = scene.getEngine();
  89056. // Culling
  89057. engine.setState(material.backFaceCulling);
  89058. // Managing instances
  89059. var batch = mesh._getInstancesRenderList(subMesh._id);
  89060. if (batch.mustReturn) {
  89061. return;
  89062. }
  89063. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89064. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89065. var effect = _this._volumetricLightScatteringPass;
  89066. if (mesh === _this.mesh) {
  89067. if (subMesh.effect) {
  89068. effect = subMesh.effect;
  89069. }
  89070. else {
  89071. effect = material.getEffect();
  89072. }
  89073. }
  89074. engine.enableEffect(effect);
  89075. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89076. if (mesh === _this.mesh) {
  89077. material.bind(mesh.getWorldMatrix(), mesh);
  89078. }
  89079. else {
  89080. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89081. // Alpha test
  89082. if (material && material.needAlphaTesting()) {
  89083. var alphaTexture = material.getAlphaTestTexture();
  89084. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89085. if (alphaTexture) {
  89086. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89087. }
  89088. }
  89089. // Bones
  89090. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89091. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89092. }
  89093. }
  89094. // Draw
  89095. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89096. }
  89097. };
  89098. // Render target texture callbacks
  89099. var savedSceneClearColor;
  89100. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89101. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89102. savedSceneClearColor = scene.clearColor;
  89103. scene.clearColor = sceneClearColor;
  89104. });
  89105. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89106. scene.clearColor = savedSceneClearColor;
  89107. });
  89108. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89109. var engine = scene.getEngine();
  89110. var index;
  89111. if (depthOnlySubMeshes.length) {
  89112. engine.setColorWrite(false);
  89113. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89114. renderSubMesh(depthOnlySubMeshes.data[index]);
  89115. }
  89116. engine.setColorWrite(true);
  89117. }
  89118. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89119. renderSubMesh(opaqueSubMeshes.data[index]);
  89120. }
  89121. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89122. renderSubMesh(alphaTestSubMeshes.data[index]);
  89123. }
  89124. if (transparentSubMeshes.length) {
  89125. // Sort sub meshes
  89126. for (index = 0; index < transparentSubMeshes.length; index++) {
  89127. var submesh = transparentSubMeshes.data[index];
  89128. var boundingInfo = submesh.getBoundingInfo();
  89129. if (boundingInfo && scene.activeCamera) {
  89130. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89131. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89132. }
  89133. }
  89134. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89135. sortedArray.sort(function (a, b) {
  89136. // Alpha index first
  89137. if (a._alphaIndex > b._alphaIndex) {
  89138. return 1;
  89139. }
  89140. if (a._alphaIndex < b._alphaIndex) {
  89141. return -1;
  89142. }
  89143. // Then distance to camera
  89144. if (a._distanceToCamera < b._distanceToCamera) {
  89145. return 1;
  89146. }
  89147. if (a._distanceToCamera > b._distanceToCamera) {
  89148. return -1;
  89149. }
  89150. return 0;
  89151. });
  89152. // Render sub meshes
  89153. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89154. for (index = 0; index < sortedArray.length; index++) {
  89155. renderSubMesh(sortedArray[index]);
  89156. }
  89157. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89158. }
  89159. };
  89160. };
  89161. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89162. var transform = scene.getTransformMatrix();
  89163. var meshPosition;
  89164. if (this.useCustomMeshPosition) {
  89165. meshPosition = this.customMeshPosition;
  89166. }
  89167. else if (this.attachedNode) {
  89168. meshPosition = this.attachedNode.position;
  89169. }
  89170. else {
  89171. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89172. }
  89173. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89174. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89175. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89176. if (this.invert)
  89177. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89178. };
  89179. // Static methods
  89180. /**
  89181. * Creates a default mesh for the Volumeric Light Scattering post-process
  89182. * @param name The mesh name
  89183. * @param scene The scene where to create the mesh
  89184. * @return the default mesh
  89185. */
  89186. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89187. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89188. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89189. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89190. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89191. mesh.material = material;
  89192. return mesh;
  89193. };
  89194. __decorate([
  89195. BABYLON.serializeAsVector3()
  89196. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89197. __decorate([
  89198. BABYLON.serialize()
  89199. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89200. __decorate([
  89201. BABYLON.serialize()
  89202. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89203. __decorate([
  89204. BABYLON.serializeAsMeshReference()
  89205. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89206. __decorate([
  89207. BABYLON.serialize()
  89208. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89209. __decorate([
  89210. BABYLON.serialize()
  89211. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89212. __decorate([
  89213. BABYLON.serialize()
  89214. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89215. __decorate([
  89216. BABYLON.serialize()
  89217. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89218. __decorate([
  89219. BABYLON.serialize()
  89220. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89221. return VolumetricLightScatteringPostProcess;
  89222. }(BABYLON.PostProcess));
  89223. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89224. })(BABYLON || (BABYLON = {}));
  89225. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89226. var BABYLON;
  89227. (function (BABYLON) {
  89228. /**
  89229. *
  89230. * This post-process allows the modification of rendered colors by using
  89231. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89232. *
  89233. * The object needs to be provided an url to a texture containing the color
  89234. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89235. * Use an image editing software to tweak the LUT to match your needs.
  89236. *
  89237. * For an example of a color LUT, see here:
  89238. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89239. * For explanations on color grading, see here:
  89240. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89241. *
  89242. */
  89243. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89244. __extends(ColorCorrectionPostProcess, _super);
  89245. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89246. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89247. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89248. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89249. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89250. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89251. _this.onApply = function (effect) {
  89252. effect.setTexture("colorTable", _this._colorTableTexture);
  89253. };
  89254. return _this;
  89255. }
  89256. return ColorCorrectionPostProcess;
  89257. }(BABYLON.PostProcess));
  89258. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89259. })(BABYLON || (BABYLON = {}));
  89260. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89261. var BABYLON;
  89262. (function (BABYLON) {
  89263. /** Defines operator used for tonemapping */
  89264. var TonemappingOperator;
  89265. (function (TonemappingOperator) {
  89266. /** Hable */
  89267. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89268. /** Reinhard */
  89269. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89270. /** HejiDawson */
  89271. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89272. /** Photographic */
  89273. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89274. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89275. ;
  89276. /**
  89277. * Defines a post process to apply tone mapping
  89278. */
  89279. var TonemapPostProcess = /** @class */ (function (_super) {
  89280. __extends(TonemapPostProcess, _super);
  89281. /**
  89282. * Creates a new TonemapPostProcess
  89283. * @param name defines the name of the postprocess
  89284. * @param _operator defines the operator to use
  89285. * @param exposureAdjustment defines the required exposure adjustement
  89286. * @param camera defines the camera to use (can be null)
  89287. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89288. * @param engine defines the hosting engine (can be ignore if camera is set)
  89289. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89290. */
  89291. function TonemapPostProcess(name, _operator,
  89292. /** Defines the required exposure adjustement */
  89293. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89295. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89296. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89297. _this._operator = _operator;
  89298. _this.exposureAdjustment = exposureAdjustment;
  89299. var defines = "#define ";
  89300. if (_this._operator === TonemappingOperator.Hable)
  89301. defines += "HABLE_TONEMAPPING";
  89302. else if (_this._operator === TonemappingOperator.Reinhard)
  89303. defines += "REINHARD_TONEMAPPING";
  89304. else if (_this._operator === TonemappingOperator.HejiDawson)
  89305. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89306. else if (_this._operator === TonemappingOperator.Photographic)
  89307. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89308. //sadly a second call to create the effect.
  89309. _this.updateEffect(defines);
  89310. _this.onApply = function (effect) {
  89311. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89312. };
  89313. return _this;
  89314. }
  89315. return TonemapPostProcess;
  89316. }(BABYLON.PostProcess));
  89317. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89318. })(BABYLON || (BABYLON = {}));
  89319. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89320. var BABYLON;
  89321. (function (BABYLON) {
  89322. /**
  89323. * DisplayPassPostProcess which produces an output the same as it's input
  89324. */
  89325. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89326. __extends(DisplayPassPostProcess, _super);
  89327. /**
  89328. * Creates the DisplayPassPostProcess
  89329. * @param name The name of the effect.
  89330. * @param options The required width/height ratio to downsize to before computing the render pass.
  89331. * @param camera The camera to apply the render pass to.
  89332. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89333. * @param engine The engine which the post process will be applied. (default: current engine)
  89334. * @param reusable If the post process can be reused on the same frame. (default: false)
  89335. */
  89336. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89337. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89338. }
  89339. return DisplayPassPostProcess;
  89340. }(BABYLON.PostProcess));
  89341. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89342. })(BABYLON || (BABYLON = {}));
  89343. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89344. var BABYLON;
  89345. (function (BABYLON) {
  89346. /**
  89347. * Extracts highlights from the image
  89348. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89349. */
  89350. var HighlightsPostProcess = /** @class */ (function (_super) {
  89351. __extends(HighlightsPostProcess, _super);
  89352. /**
  89353. * Extracts highlights from the image
  89354. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89355. * @param name The name of the effect.
  89356. * @param options The required width/height ratio to downsize to before computing the render pass.
  89357. * @param camera The camera to apply the render pass to.
  89358. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89359. * @param engine The engine which the post process will be applied. (default: current engine)
  89360. * @param reusable If the post process can be reused on the same frame. (default: false)
  89361. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89362. */
  89363. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89364. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89365. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89366. }
  89367. return HighlightsPostProcess;
  89368. }(BABYLON.PostProcess));
  89369. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89370. })(BABYLON || (BABYLON = {}));
  89371. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89372. var BABYLON;
  89373. (function (BABYLON) {
  89374. /**
  89375. * ImageProcessingPostProcess
  89376. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89377. */
  89378. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89379. __extends(ImageProcessingPostProcess, _super);
  89380. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89381. if (camera === void 0) { camera = null; }
  89382. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89383. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89384. _this._fromLinearSpace = true;
  89385. /**
  89386. * Defines cache preventing GC.
  89387. */
  89388. _this._defines = {
  89389. IMAGEPROCESSING: false,
  89390. VIGNETTE: false,
  89391. VIGNETTEBLENDMODEMULTIPLY: false,
  89392. VIGNETTEBLENDMODEOPAQUE: false,
  89393. TONEMAPPING: false,
  89394. TONEMAPPING_ACES: false,
  89395. CONTRAST: false,
  89396. COLORCURVES: false,
  89397. COLORGRADING: false,
  89398. COLORGRADING3D: false,
  89399. FROMLINEARSPACE: false,
  89400. SAMPLER3DGREENDEPTH: false,
  89401. SAMPLER3DBGRMAP: false,
  89402. IMAGEPROCESSINGPOSTPROCESS: false,
  89403. EXPOSURE: false,
  89404. };
  89405. // Setup the configuration as forced by the constructor. This would then not force the
  89406. // scene materials output in linear space and let untouched the default forward pass.
  89407. if (imageProcessingConfiguration) {
  89408. imageProcessingConfiguration.applyByPostProcess = true;
  89409. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89410. // This will cause the shader to be compiled
  89411. _this.fromLinearSpace = false;
  89412. }
  89413. // Setup the default processing configuration to the scene.
  89414. else {
  89415. _this._attachImageProcessingConfiguration(null, true);
  89416. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89417. }
  89418. _this.onApply = function (effect) {
  89419. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89420. };
  89421. return _this;
  89422. }
  89423. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89424. /**
  89425. * Gets the image processing configuration used either in this material.
  89426. */
  89427. get: function () {
  89428. return this._imageProcessingConfiguration;
  89429. },
  89430. /**
  89431. * Sets the Default image processing configuration used either in the this material.
  89432. *
  89433. * If sets to null, the scene one is in use.
  89434. */
  89435. set: function (value) {
  89436. this._attachImageProcessingConfiguration(value);
  89437. },
  89438. enumerable: true,
  89439. configurable: true
  89440. });
  89441. /**
  89442. * Attaches a new image processing configuration to the PBR Material.
  89443. * @param configuration
  89444. */
  89445. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89446. var _this = this;
  89447. if (doNotBuild === void 0) { doNotBuild = false; }
  89448. if (configuration === this._imageProcessingConfiguration) {
  89449. return;
  89450. }
  89451. // Detaches observer.
  89452. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89453. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89454. }
  89455. // Pick the scene configuration if needed.
  89456. if (!configuration) {
  89457. var scene = null;
  89458. var engine = this.getEngine();
  89459. var camera = this.getCamera();
  89460. if (camera) {
  89461. scene = camera.getScene();
  89462. }
  89463. else if (engine && engine.scenes) {
  89464. var scenes = engine.scenes;
  89465. scene = scenes[scenes.length - 1];
  89466. }
  89467. else {
  89468. scene = BABYLON.Engine.LastCreatedScene;
  89469. }
  89470. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89471. }
  89472. else {
  89473. this._imageProcessingConfiguration = configuration;
  89474. }
  89475. // Attaches observer.
  89476. if (this._imageProcessingConfiguration) {
  89477. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89478. _this._updateParameters();
  89479. });
  89480. }
  89481. // Ensure the effect will be rebuilt.
  89482. if (!doNotBuild) {
  89483. this._updateParameters();
  89484. }
  89485. };
  89486. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89487. /**
  89488. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89489. */
  89490. get: function () {
  89491. return this.imageProcessingConfiguration.colorCurves;
  89492. },
  89493. /**
  89494. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89495. */
  89496. set: function (value) {
  89497. this.imageProcessingConfiguration.colorCurves = value;
  89498. },
  89499. enumerable: true,
  89500. configurable: true
  89501. });
  89502. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89503. /**
  89504. * Gets wether the color curves effect is enabled.
  89505. */
  89506. get: function () {
  89507. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89508. },
  89509. /**
  89510. * Sets wether the color curves effect is enabled.
  89511. */
  89512. set: function (value) {
  89513. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89514. },
  89515. enumerable: true,
  89516. configurable: true
  89517. });
  89518. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89519. /**
  89520. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89521. */
  89522. get: function () {
  89523. return this.imageProcessingConfiguration.colorGradingTexture;
  89524. },
  89525. /**
  89526. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89527. */
  89528. set: function (value) {
  89529. this.imageProcessingConfiguration.colorGradingTexture = value;
  89530. },
  89531. enumerable: true,
  89532. configurable: true
  89533. });
  89534. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89535. /**
  89536. * Gets wether the color grading effect is enabled.
  89537. */
  89538. get: function () {
  89539. return this.imageProcessingConfiguration.colorGradingEnabled;
  89540. },
  89541. /**
  89542. * Gets wether the color grading effect is enabled.
  89543. */
  89544. set: function (value) {
  89545. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89546. },
  89547. enumerable: true,
  89548. configurable: true
  89549. });
  89550. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89551. /**
  89552. * Gets exposure used in the effect.
  89553. */
  89554. get: function () {
  89555. return this.imageProcessingConfiguration.exposure;
  89556. },
  89557. /**
  89558. * Sets exposure used in the effect.
  89559. */
  89560. set: function (value) {
  89561. this.imageProcessingConfiguration.exposure = value;
  89562. },
  89563. enumerable: true,
  89564. configurable: true
  89565. });
  89566. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89567. /**
  89568. * Gets wether tonemapping is enabled or not.
  89569. */
  89570. get: function () {
  89571. return this._imageProcessingConfiguration.toneMappingEnabled;
  89572. },
  89573. /**
  89574. * Sets wether tonemapping is enabled or not
  89575. */
  89576. set: function (value) {
  89577. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89578. },
  89579. enumerable: true,
  89580. configurable: true
  89581. });
  89582. ;
  89583. ;
  89584. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89585. /**
  89586. * Gets contrast used in the effect.
  89587. */
  89588. get: function () {
  89589. return this.imageProcessingConfiguration.contrast;
  89590. },
  89591. /**
  89592. * Sets contrast used in the effect.
  89593. */
  89594. set: function (value) {
  89595. this.imageProcessingConfiguration.contrast = value;
  89596. },
  89597. enumerable: true,
  89598. configurable: true
  89599. });
  89600. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89601. /**
  89602. * Gets Vignette stretch size.
  89603. */
  89604. get: function () {
  89605. return this.imageProcessingConfiguration.vignetteStretch;
  89606. },
  89607. /**
  89608. * Sets Vignette stretch size.
  89609. */
  89610. set: function (value) {
  89611. this.imageProcessingConfiguration.vignetteStretch = value;
  89612. },
  89613. enumerable: true,
  89614. configurable: true
  89615. });
  89616. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89617. /**
  89618. * Gets Vignette centre X Offset.
  89619. */
  89620. get: function () {
  89621. return this.imageProcessingConfiguration.vignetteCentreX;
  89622. },
  89623. /**
  89624. * Sets Vignette centre X Offset.
  89625. */
  89626. set: function (value) {
  89627. this.imageProcessingConfiguration.vignetteCentreX = value;
  89628. },
  89629. enumerable: true,
  89630. configurable: true
  89631. });
  89632. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89633. /**
  89634. * Gets Vignette centre Y Offset.
  89635. */
  89636. get: function () {
  89637. return this.imageProcessingConfiguration.vignetteCentreY;
  89638. },
  89639. /**
  89640. * Sets Vignette centre Y Offset.
  89641. */
  89642. set: function (value) {
  89643. this.imageProcessingConfiguration.vignetteCentreY = value;
  89644. },
  89645. enumerable: true,
  89646. configurable: true
  89647. });
  89648. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89649. /**
  89650. * Gets Vignette weight or intensity of the vignette effect.
  89651. */
  89652. get: function () {
  89653. return this.imageProcessingConfiguration.vignetteWeight;
  89654. },
  89655. /**
  89656. * Sets Vignette weight or intensity of the vignette effect.
  89657. */
  89658. set: function (value) {
  89659. this.imageProcessingConfiguration.vignetteWeight = value;
  89660. },
  89661. enumerable: true,
  89662. configurable: true
  89663. });
  89664. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89665. /**
  89666. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89667. * if vignetteEnabled is set to true.
  89668. */
  89669. get: function () {
  89670. return this.imageProcessingConfiguration.vignetteColor;
  89671. },
  89672. /**
  89673. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89674. * if vignetteEnabled is set to true.
  89675. */
  89676. set: function (value) {
  89677. this.imageProcessingConfiguration.vignetteColor = value;
  89678. },
  89679. enumerable: true,
  89680. configurable: true
  89681. });
  89682. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  89683. /**
  89684. * Gets Camera field of view used by the Vignette effect.
  89685. */
  89686. get: function () {
  89687. return this.imageProcessingConfiguration.vignetteCameraFov;
  89688. },
  89689. /**
  89690. * Sets Camera field of view used by the Vignette effect.
  89691. */
  89692. set: function (value) {
  89693. this.imageProcessingConfiguration.vignetteCameraFov = value;
  89694. },
  89695. enumerable: true,
  89696. configurable: true
  89697. });
  89698. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  89699. /**
  89700. * Gets the vignette blend mode allowing different kind of effect.
  89701. */
  89702. get: function () {
  89703. return this.imageProcessingConfiguration.vignetteBlendMode;
  89704. },
  89705. /**
  89706. * Sets the vignette blend mode allowing different kind of effect.
  89707. */
  89708. set: function (value) {
  89709. this.imageProcessingConfiguration.vignetteBlendMode = value;
  89710. },
  89711. enumerable: true,
  89712. configurable: true
  89713. });
  89714. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  89715. /**
  89716. * Gets wether the vignette effect is enabled.
  89717. */
  89718. get: function () {
  89719. return this.imageProcessingConfiguration.vignetteEnabled;
  89720. },
  89721. /**
  89722. * Sets wether the vignette effect is enabled.
  89723. */
  89724. set: function (value) {
  89725. this.imageProcessingConfiguration.vignetteEnabled = value;
  89726. },
  89727. enumerable: true,
  89728. configurable: true
  89729. });
  89730. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  89731. /**
  89732. * Gets wether the input of the processing is in Gamma or Linear Space.
  89733. */
  89734. get: function () {
  89735. return this._fromLinearSpace;
  89736. },
  89737. /**
  89738. * Sets wether the input of the processing is in Gamma or Linear Space.
  89739. */
  89740. set: function (value) {
  89741. if (this._fromLinearSpace === value) {
  89742. return;
  89743. }
  89744. this._fromLinearSpace = value;
  89745. this._updateParameters();
  89746. },
  89747. enumerable: true,
  89748. configurable: true
  89749. });
  89750. /**
  89751. * "ImageProcessingPostProcess"
  89752. * @returns "ImageProcessingPostProcess"
  89753. */
  89754. ImageProcessingPostProcess.prototype.getClassName = function () {
  89755. return "ImageProcessingPostProcess";
  89756. };
  89757. ImageProcessingPostProcess.prototype._updateParameters = function () {
  89758. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  89759. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  89760. var defines = "";
  89761. for (var define in this._defines) {
  89762. if (this._defines[define]) {
  89763. defines += "#define " + define + ";\r\n";
  89764. }
  89765. }
  89766. var samplers = ["textureSampler"];
  89767. var uniforms = ["scale"];
  89768. if (BABYLON.ImageProcessingConfiguration) {
  89769. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  89770. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  89771. }
  89772. this.updateEffect(defines, uniforms, samplers);
  89773. };
  89774. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  89775. _super.prototype.dispose.call(this, camera);
  89776. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89777. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89778. }
  89779. if (this._imageProcessingConfiguration) {
  89780. this.imageProcessingConfiguration.applyByPostProcess = false;
  89781. }
  89782. };
  89783. __decorate([
  89784. BABYLON.serialize()
  89785. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  89786. return ImageProcessingPostProcess;
  89787. }(BABYLON.PostProcess));
  89788. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  89789. })(BABYLON || (BABYLON = {}));
  89790. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  89791. var BABYLON;
  89792. (function (BABYLON) {
  89793. /**
  89794. * Class used to store bone information
  89795. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  89796. */
  89797. var Bone = /** @class */ (function (_super) {
  89798. __extends(Bone, _super);
  89799. /**
  89800. * Create a new bone
  89801. * @param name defines the bone name
  89802. * @param skeleton defines the parent skeleton
  89803. * @param parentBone defines the parent (can be null if the bone is the root)
  89804. * @param localMatrix defines the local matrix
  89805. * @param restPose defines the rest pose matrix
  89806. * @param baseMatrix defines the base matrix
  89807. * @param index defines index of the bone in the hiearchy
  89808. */
  89809. function Bone(
  89810. /**
  89811. * defines the bone name
  89812. */
  89813. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  89814. if (parentBone === void 0) { parentBone = null; }
  89815. if (localMatrix === void 0) { localMatrix = null; }
  89816. if (restPose === void 0) { restPose = null; }
  89817. if (baseMatrix === void 0) { baseMatrix = null; }
  89818. if (index === void 0) { index = null; }
  89819. var _this = _super.call(this, name, skeleton.getScene()) || this;
  89820. _this.name = name;
  89821. /**
  89822. * Gets the list of child bones
  89823. */
  89824. _this.children = new Array();
  89825. /** Gets the animations associated with this bone */
  89826. _this.animations = new Array();
  89827. /**
  89828. * @hidden Internal only
  89829. * Set this value to map this bone to a different index in the transform matrices
  89830. * Set this value to -1 to exclude the bone from the transform matrices
  89831. */
  89832. _this._index = null;
  89833. _this._absoluteTransform = new BABYLON.Matrix();
  89834. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  89835. _this._scalingDeterminant = 1;
  89836. _this._worldTransform = new BABYLON.Matrix();
  89837. _this._needToDecompose = true;
  89838. _this._needToCompose = false;
  89839. _this._skeleton = skeleton;
  89840. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  89841. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  89842. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  89843. _this._index = index;
  89844. skeleton.bones.push(_this);
  89845. _this.setParent(parentBone, false);
  89846. if (baseMatrix || localMatrix) {
  89847. _this._updateDifferenceMatrix();
  89848. }
  89849. return _this;
  89850. }
  89851. Object.defineProperty(Bone.prototype, "_matrix", {
  89852. /** @hidden */
  89853. get: function () {
  89854. this._compose();
  89855. return this._localMatrix;
  89856. },
  89857. /** @hidden */
  89858. set: function (value) {
  89859. this._localMatrix.copyFrom(value);
  89860. this._needToDecompose = true;
  89861. },
  89862. enumerable: true,
  89863. configurable: true
  89864. });
  89865. // Members
  89866. /**
  89867. * Gets the parent skeleton
  89868. * @returns a skeleton
  89869. */
  89870. Bone.prototype.getSkeleton = function () {
  89871. return this._skeleton;
  89872. };
  89873. /**
  89874. * Gets parent bone
  89875. * @returns a bone or null if the bone is the root of the bone hierarchy
  89876. */
  89877. Bone.prototype.getParent = function () {
  89878. return this._parent;
  89879. };
  89880. /**
  89881. * Sets the parent bone
  89882. * @param parent defines the parent (can be null if the bone is the root)
  89883. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  89884. */
  89885. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  89886. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  89887. if (this._parent === parent) {
  89888. return;
  89889. }
  89890. if (this._parent) {
  89891. var index = this._parent.children.indexOf(this);
  89892. if (index !== -1) {
  89893. this._parent.children.splice(index, 1);
  89894. }
  89895. }
  89896. this._parent = parent;
  89897. if (this._parent) {
  89898. this._parent.children.push(this);
  89899. }
  89900. if (updateDifferenceMatrix) {
  89901. this._updateDifferenceMatrix();
  89902. }
  89903. this.markAsDirty();
  89904. };
  89905. /**
  89906. * Gets the local matrix
  89907. * @returns a matrix
  89908. */
  89909. Bone.prototype.getLocalMatrix = function () {
  89910. this._compose();
  89911. return this._localMatrix;
  89912. };
  89913. /**
  89914. * Gets the base matrix (initial matrix which remains unchanged)
  89915. * @returns a matrix
  89916. */
  89917. Bone.prototype.getBaseMatrix = function () {
  89918. return this._baseMatrix;
  89919. };
  89920. /**
  89921. * Gets the rest pose matrix
  89922. * @returns a matrix
  89923. */
  89924. Bone.prototype.getRestPose = function () {
  89925. return this._restPose;
  89926. };
  89927. /**
  89928. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  89929. */
  89930. Bone.prototype.getWorldMatrix = function () {
  89931. return this._worldTransform;
  89932. };
  89933. /**
  89934. * Sets the local matrix to rest pose matrix
  89935. */
  89936. Bone.prototype.returnToRest = function () {
  89937. this.updateMatrix(this._restPose.clone());
  89938. };
  89939. /**
  89940. * Gets the inverse of the absolute transform matrix.
  89941. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  89942. * @returns a matrix
  89943. */
  89944. Bone.prototype.getInvertedAbsoluteTransform = function () {
  89945. return this._invertedAbsoluteTransform;
  89946. };
  89947. /**
  89948. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  89949. * @returns a matrix
  89950. */
  89951. Bone.prototype.getAbsoluteTransform = function () {
  89952. return this._absoluteTransform;
  89953. };
  89954. Object.defineProperty(Bone.prototype, "position", {
  89955. // Properties (matches AbstractMesh properties)
  89956. /** Gets or sets current position (in local space) */
  89957. get: function () {
  89958. this._decompose();
  89959. return this._localPosition;
  89960. },
  89961. set: function (newPosition) {
  89962. this._decompose();
  89963. this._localPosition.copyFrom(newPosition);
  89964. this._markAsDirtyAndCompose();
  89965. },
  89966. enumerable: true,
  89967. configurable: true
  89968. });
  89969. Object.defineProperty(Bone.prototype, "rotation", {
  89970. /** Gets or sets current rotation (in local space) */
  89971. get: function () {
  89972. return this.getRotation();
  89973. },
  89974. set: function (newRotation) {
  89975. this.setRotation(newRotation);
  89976. },
  89977. enumerable: true,
  89978. configurable: true
  89979. });
  89980. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  89981. /** Gets or sets current rotation quaternion (in local space) */
  89982. get: function () {
  89983. this._decompose();
  89984. return this._localRotation;
  89985. },
  89986. set: function (newRotation) {
  89987. this.setRotationQuaternion(newRotation);
  89988. },
  89989. enumerable: true,
  89990. configurable: true
  89991. });
  89992. Object.defineProperty(Bone.prototype, "scaling", {
  89993. /** Gets or sets current scaling (in local space) */
  89994. get: function () {
  89995. return this.getScale();
  89996. },
  89997. set: function (newScaling) {
  89998. this.setScale(newScaling);
  89999. },
  90000. enumerable: true,
  90001. configurable: true
  90002. });
  90003. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  90004. /**
  90005. * Gets the animation properties override
  90006. */
  90007. get: function () {
  90008. return this._skeleton.animationPropertiesOverride;
  90009. },
  90010. enumerable: true,
  90011. configurable: true
  90012. });
  90013. // Methods
  90014. Bone.prototype._decompose = function () {
  90015. if (!this._needToDecompose) {
  90016. return;
  90017. }
  90018. this._needToDecompose = false;
  90019. if (!this._localScaling) {
  90020. this._localScaling = BABYLON.Vector3.Zero();
  90021. this._localRotation = BABYLON.Quaternion.Zero();
  90022. this._localPosition = BABYLON.Vector3.Zero();
  90023. }
  90024. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90025. };
  90026. Bone.prototype._compose = function () {
  90027. if (!this._needToCompose) {
  90028. return;
  90029. }
  90030. this._needToCompose = false;
  90031. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90032. };
  90033. /**
  90034. * Update the base and local matrices
  90035. * @param matrix defines the new base or local matrix
  90036. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90037. * @param updateLocalMatrix defines if the local matrix should be updated
  90038. */
  90039. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90040. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90041. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90042. this._baseMatrix.copyFrom(matrix);
  90043. if (updateDifferenceMatrix) {
  90044. this._updateDifferenceMatrix();
  90045. }
  90046. if (updateLocalMatrix) {
  90047. this._localMatrix.copyFrom(matrix);
  90048. this._markAsDirtyAndDecompose();
  90049. }
  90050. else {
  90051. this.markAsDirty();
  90052. }
  90053. };
  90054. /** @hidden */
  90055. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90056. if (updateChildren === void 0) { updateChildren = true; }
  90057. if (!rootMatrix) {
  90058. rootMatrix = this._baseMatrix;
  90059. }
  90060. if (this._parent) {
  90061. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90062. }
  90063. else {
  90064. this._absoluteTransform.copyFrom(rootMatrix);
  90065. }
  90066. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90067. if (updateChildren) {
  90068. for (var index = 0; index < this.children.length; index++) {
  90069. this.children[index]._updateDifferenceMatrix();
  90070. }
  90071. }
  90072. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90073. };
  90074. /**
  90075. * Flag the bone as dirty (Forcing it to update everything)
  90076. */
  90077. Bone.prototype.markAsDirty = function () {
  90078. this._currentRenderId++;
  90079. this._childRenderId++;
  90080. this._skeleton._markAsDirty();
  90081. };
  90082. Bone.prototype._markAsDirtyAndCompose = function () {
  90083. this.markAsDirty();
  90084. this._needToCompose = true;
  90085. };
  90086. Bone.prototype._markAsDirtyAndDecompose = function () {
  90087. this.markAsDirty();
  90088. this._needToDecompose = true;
  90089. };
  90090. /**
  90091. * Copy an animation range from another bone
  90092. * @param source defines the source bone
  90093. * @param rangeName defines the range name to copy
  90094. * @param frameOffset defines the frame offset
  90095. * @param rescaleAsRequired defines if rescaling must be applied if required
  90096. * @param skelDimensionsRatio defines the scaling ratio
  90097. * @returns true if operation was successful
  90098. */
  90099. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90100. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90101. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90102. // all animation may be coming from a library skeleton, so may need to create animation
  90103. if (this.animations.length === 0) {
  90104. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90105. this.animations[0].setKeys([]);
  90106. }
  90107. // get animation info / verify there is such a range from the source bone
  90108. var sourceRange = source.animations[0].getRange(rangeName);
  90109. if (!sourceRange) {
  90110. return false;
  90111. }
  90112. var from = sourceRange.from;
  90113. var to = sourceRange.to;
  90114. var sourceKeys = source.animations[0].getKeys();
  90115. // rescaling prep
  90116. var sourceBoneLength = source.length;
  90117. var sourceParent = source.getParent();
  90118. var parent = this.getParent();
  90119. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90120. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90121. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90122. var destKeys = this.animations[0].getKeys();
  90123. // loop vars declaration
  90124. var orig;
  90125. var origTranslation;
  90126. var mat;
  90127. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90128. orig = sourceKeys[key];
  90129. if (orig.frame >= from && orig.frame <= to) {
  90130. if (rescaleAsRequired) {
  90131. mat = orig.value.clone();
  90132. // scale based on parent ratio, when bone has parent
  90133. if (parentScalingReqd) {
  90134. origTranslation = mat.getTranslation();
  90135. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90136. // scale based on skeleton dimension ratio when root bone, and value is passed
  90137. }
  90138. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90139. origTranslation = mat.getTranslation();
  90140. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90141. // use original when root bone, and no data for skelDimensionsRatio
  90142. }
  90143. else {
  90144. mat = orig.value;
  90145. }
  90146. }
  90147. else {
  90148. mat = orig.value;
  90149. }
  90150. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90151. }
  90152. }
  90153. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90154. return true;
  90155. };
  90156. /**
  90157. * Translate the bone in local or world space
  90158. * @param vec The amount to translate the bone
  90159. * @param space The space that the translation is in
  90160. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90161. */
  90162. Bone.prototype.translate = function (vec, space, mesh) {
  90163. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90164. var lm = this.getLocalMatrix();
  90165. if (space == BABYLON.Space.LOCAL) {
  90166. lm.m[12] += vec.x;
  90167. lm.m[13] += vec.y;
  90168. lm.m[14] += vec.z;
  90169. }
  90170. else {
  90171. var wm = null;
  90172. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90173. if (mesh) {
  90174. wm = mesh.getWorldMatrix();
  90175. }
  90176. this._skeleton.computeAbsoluteTransforms();
  90177. var tmat = Bone._tmpMats[0];
  90178. var tvec = Bone._tmpVecs[0];
  90179. if (this._parent) {
  90180. if (mesh && wm) {
  90181. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90182. tmat.multiplyToRef(wm, tmat);
  90183. }
  90184. else {
  90185. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90186. }
  90187. }
  90188. tmat.m[12] = 0;
  90189. tmat.m[13] = 0;
  90190. tmat.m[14] = 0;
  90191. tmat.invert();
  90192. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90193. lm.m[12] += tvec.x;
  90194. lm.m[13] += tvec.y;
  90195. lm.m[14] += tvec.z;
  90196. }
  90197. this._markAsDirtyAndDecompose();
  90198. };
  90199. /**
  90200. * Set the postion of the bone in local or world space
  90201. * @param position The position to set the bone
  90202. * @param space The space that the position is in
  90203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90204. */
  90205. Bone.prototype.setPosition = function (position, space, mesh) {
  90206. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90207. var lm = this.getLocalMatrix();
  90208. if (space == BABYLON.Space.LOCAL) {
  90209. lm.m[12] = position.x;
  90210. lm.m[13] = position.y;
  90211. lm.m[14] = position.z;
  90212. }
  90213. else {
  90214. var wm = null;
  90215. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90216. if (mesh) {
  90217. wm = mesh.getWorldMatrix();
  90218. }
  90219. this._skeleton.computeAbsoluteTransforms();
  90220. var tmat = Bone._tmpMats[0];
  90221. var vec = Bone._tmpVecs[0];
  90222. if (this._parent) {
  90223. if (mesh && wm) {
  90224. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90225. tmat.multiplyToRef(wm, tmat);
  90226. }
  90227. else {
  90228. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90229. }
  90230. }
  90231. tmat.invert();
  90232. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90233. lm.m[12] = vec.x;
  90234. lm.m[13] = vec.y;
  90235. lm.m[14] = vec.z;
  90236. }
  90237. this._markAsDirtyAndDecompose();
  90238. };
  90239. /**
  90240. * Set the absolute position of the bone (world space)
  90241. * @param position The position to set the bone
  90242. * @param mesh The mesh that this bone is attached to
  90243. */
  90244. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90245. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90246. };
  90247. /**
  90248. * Scale the bone on the x, y and z axes (in local space)
  90249. * @param x The amount to scale the bone on the x axis
  90250. * @param y The amount to scale the bone on the y axis
  90251. * @param z The amount to scale the bone on the z axis
  90252. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90253. */
  90254. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90255. if (scaleChildren === void 0) { scaleChildren = false; }
  90256. var locMat = this.getLocalMatrix();
  90257. // Apply new scaling on top of current local matrix
  90258. var scaleMat = Bone._tmpMats[0];
  90259. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90260. scaleMat.multiplyToRef(locMat, locMat);
  90261. // Invert scaling matrix and apply the inverse to all children
  90262. scaleMat.invert();
  90263. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90264. var child = _a[_i];
  90265. var cm = child.getLocalMatrix();
  90266. cm.multiplyToRef(scaleMat, cm);
  90267. cm.m[12] *= x;
  90268. cm.m[13] *= y;
  90269. cm.m[14] *= z;
  90270. child._markAsDirtyAndDecompose();
  90271. }
  90272. this._markAsDirtyAndDecompose();
  90273. if (scaleChildren) {
  90274. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90275. var child = _c[_b];
  90276. child.scale(x, y, z, scaleChildren);
  90277. }
  90278. }
  90279. };
  90280. /**
  90281. * Set the bone scaling in local space
  90282. * @param scale defines the scaling vector
  90283. */
  90284. Bone.prototype.setScale = function (scale) {
  90285. this._decompose();
  90286. this._localScaling.copyFrom(scale);
  90287. this._markAsDirtyAndCompose();
  90288. };
  90289. /**
  90290. * Gets the current scaling in local space
  90291. * @returns the current scaling vector
  90292. */
  90293. Bone.prototype.getScale = function () {
  90294. this._decompose();
  90295. return this._localScaling;
  90296. };
  90297. /**
  90298. * Gets the current scaling in local space and stores it in a target vector
  90299. * @param result defines the target vector
  90300. */
  90301. Bone.prototype.getScaleToRef = function (result) {
  90302. this._decompose();
  90303. result.copyFrom(this._localScaling);
  90304. };
  90305. /**
  90306. * Set the yaw, pitch, and roll of the bone in local or world space
  90307. * @param yaw The rotation of the bone on the y axis
  90308. * @param pitch The rotation of the bone on the x axis
  90309. * @param roll The rotation of the bone on the z axis
  90310. * @param space The space that the axes of rotation are in
  90311. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90312. */
  90313. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90314. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90315. if (space === BABYLON.Space.LOCAL) {
  90316. var quat = Bone._tmpQuat;
  90317. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90318. this.setRotationQuaternion(quat, space, mesh);
  90319. return;
  90320. }
  90321. var rotMatInv = Bone._tmpMats[0];
  90322. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90323. return;
  90324. }
  90325. var rotMat = Bone._tmpMats[1];
  90326. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90327. rotMatInv.multiplyToRef(rotMat, rotMat);
  90328. this._rotateWithMatrix(rotMat, space, mesh);
  90329. };
  90330. /**
  90331. * Add a rotation to the bone on an axis in local or world space
  90332. * @param axis The axis to rotate the bone on
  90333. * @param amount The amount to rotate the bone
  90334. * @param space The space that the axis is in
  90335. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90336. */
  90337. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90338. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90339. var rmat = Bone._tmpMats[0];
  90340. rmat.m[12] = 0;
  90341. rmat.m[13] = 0;
  90342. rmat.m[14] = 0;
  90343. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90344. this._rotateWithMatrix(rmat, space, mesh);
  90345. };
  90346. /**
  90347. * Set the rotation of the bone to a particular axis angle in local or world space
  90348. * @param axis The axis to rotate the bone on
  90349. * @param angle The angle that the bone should be rotated to
  90350. * @param space The space that the axis is in
  90351. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90352. */
  90353. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90354. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90355. if (space === BABYLON.Space.LOCAL) {
  90356. var quat = Bone._tmpQuat;
  90357. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90358. this.setRotationQuaternion(quat, space, mesh);
  90359. return;
  90360. }
  90361. var rotMatInv = Bone._tmpMats[0];
  90362. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90363. return;
  90364. }
  90365. var rotMat = Bone._tmpMats[1];
  90366. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90367. rotMatInv.multiplyToRef(rotMat, rotMat);
  90368. this._rotateWithMatrix(rotMat, space, mesh);
  90369. };
  90370. /**
  90371. * Set the euler rotation of the bone in local of world space
  90372. * @param rotation The euler rotation that the bone should be set to
  90373. * @param space The space that the rotation is in
  90374. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90375. */
  90376. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90377. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90378. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90379. };
  90380. /**
  90381. * Set the quaternion rotation of the bone in local of world space
  90382. * @param quat The quaternion rotation that the bone should be set to
  90383. * @param space The space that the rotation is in
  90384. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90385. */
  90386. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90388. if (space === BABYLON.Space.LOCAL) {
  90389. this._decompose();
  90390. this._localRotation.copyFrom(quat);
  90391. this._markAsDirtyAndCompose();
  90392. return;
  90393. }
  90394. var rotMatInv = Bone._tmpMats[0];
  90395. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90396. return;
  90397. }
  90398. var rotMat = Bone._tmpMats[1];
  90399. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90400. rotMatInv.multiplyToRef(rotMat, rotMat);
  90401. this._rotateWithMatrix(rotMat, space, mesh);
  90402. };
  90403. /**
  90404. * Set the rotation matrix of the bone in local of world space
  90405. * @param rotMat The rotation matrix that the bone should be set to
  90406. * @param space The space that the rotation is in
  90407. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90408. */
  90409. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90410. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90411. if (space === BABYLON.Space.LOCAL) {
  90412. var quat = Bone._tmpQuat;
  90413. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90414. this.setRotationQuaternion(quat, space, mesh);
  90415. return;
  90416. }
  90417. var rotMatInv = Bone._tmpMats[0];
  90418. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90419. return;
  90420. }
  90421. var rotMat2 = Bone._tmpMats[1];
  90422. rotMat2.copyFrom(rotMat);
  90423. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90424. this._rotateWithMatrix(rotMat2, space, mesh);
  90425. };
  90426. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90427. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90428. var lmat = this.getLocalMatrix();
  90429. var lx = lmat.m[12];
  90430. var ly = lmat.m[13];
  90431. var lz = lmat.m[14];
  90432. var parent = this.getParent();
  90433. var parentScale = Bone._tmpMats[3];
  90434. var parentScaleInv = Bone._tmpMats[4];
  90435. if (parent && space == BABYLON.Space.WORLD) {
  90436. if (mesh) {
  90437. parentScale.copyFrom(mesh.getWorldMatrix());
  90438. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90439. }
  90440. else {
  90441. parentScale.copyFrom(parent.getAbsoluteTransform());
  90442. }
  90443. parentScaleInv.copyFrom(parentScale);
  90444. parentScaleInv.invert();
  90445. lmat.multiplyToRef(parentScale, lmat);
  90446. lmat.multiplyToRef(rmat, lmat);
  90447. lmat.multiplyToRef(parentScaleInv, lmat);
  90448. }
  90449. else {
  90450. if (space == BABYLON.Space.WORLD && mesh) {
  90451. parentScale.copyFrom(mesh.getWorldMatrix());
  90452. parentScaleInv.copyFrom(parentScale);
  90453. parentScaleInv.invert();
  90454. lmat.multiplyToRef(parentScale, lmat);
  90455. lmat.multiplyToRef(rmat, lmat);
  90456. lmat.multiplyToRef(parentScaleInv, lmat);
  90457. }
  90458. else {
  90459. lmat.multiplyToRef(rmat, lmat);
  90460. }
  90461. }
  90462. lmat.m[12] = lx;
  90463. lmat.m[13] = ly;
  90464. lmat.m[14] = lz;
  90465. this.computeAbsoluteTransforms();
  90466. this._markAsDirtyAndDecompose();
  90467. };
  90468. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90469. var scaleMatrix = Bone._tmpMats[2];
  90470. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90471. if (mesh) {
  90472. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90473. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90474. }
  90475. rotMatInv.invert();
  90476. if (isNaN(rotMatInv.m[0])) {
  90477. // Matrix failed to invert.
  90478. // This can happen if scale is zero for example.
  90479. return false;
  90480. }
  90481. scaleMatrix.m[0] *= this._scalingDeterminant;
  90482. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90483. return true;
  90484. };
  90485. /**
  90486. * Get the position of the bone in local or world space
  90487. * @param space The space that the returned position is in
  90488. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90489. * @returns The position of the bone
  90490. */
  90491. Bone.prototype.getPosition = function (space, mesh) {
  90492. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90493. if (mesh === void 0) { mesh = null; }
  90494. var pos = BABYLON.Vector3.Zero();
  90495. this.getPositionToRef(space, mesh, pos);
  90496. return pos;
  90497. };
  90498. /**
  90499. * Copy the position of the bone to a vector3 in local or world space
  90500. * @param space The space that the returned position is in
  90501. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90502. * @param result The vector3 to copy the position to
  90503. */
  90504. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90505. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90506. if (space == BABYLON.Space.LOCAL) {
  90507. var lm = this.getLocalMatrix();
  90508. result.x = lm.m[12];
  90509. result.y = lm.m[13];
  90510. result.z = lm.m[14];
  90511. }
  90512. else {
  90513. var wm = null;
  90514. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90515. if (mesh) {
  90516. wm = mesh.getWorldMatrix();
  90517. }
  90518. this._skeleton.computeAbsoluteTransforms();
  90519. var tmat = Bone._tmpMats[0];
  90520. if (mesh && wm) {
  90521. tmat.copyFrom(this.getAbsoluteTransform());
  90522. tmat.multiplyToRef(wm, tmat);
  90523. }
  90524. else {
  90525. tmat = this.getAbsoluteTransform();
  90526. }
  90527. result.x = tmat.m[12];
  90528. result.y = tmat.m[13];
  90529. result.z = tmat.m[14];
  90530. }
  90531. };
  90532. /**
  90533. * Get the absolute position of the bone (world space)
  90534. * @param mesh The mesh that this bone is attached to
  90535. * @returns The absolute position of the bone
  90536. */
  90537. Bone.prototype.getAbsolutePosition = function (mesh) {
  90538. if (mesh === void 0) { mesh = null; }
  90539. var pos = BABYLON.Vector3.Zero();
  90540. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90541. return pos;
  90542. };
  90543. /**
  90544. * Copy the absolute position of the bone (world space) to the result param
  90545. * @param mesh The mesh that this bone is attached to
  90546. * @param result The vector3 to copy the absolute position to
  90547. */
  90548. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90549. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90550. };
  90551. /**
  90552. * Compute the absolute transforms of this bone and its children
  90553. */
  90554. Bone.prototype.computeAbsoluteTransforms = function () {
  90555. this._compose();
  90556. if (this._parent) {
  90557. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90558. }
  90559. else {
  90560. this._absoluteTransform.copyFrom(this._localMatrix);
  90561. var poseMatrix = this._skeleton.getPoseMatrix();
  90562. if (poseMatrix) {
  90563. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90564. }
  90565. }
  90566. var children = this.children;
  90567. var len = children.length;
  90568. for (var i = 0; i < len; i++) {
  90569. children[i].computeAbsoluteTransforms();
  90570. }
  90571. };
  90572. /**
  90573. * Get the world direction from an axis that is in the local space of the bone
  90574. * @param localAxis The local direction that is used to compute the world direction
  90575. * @param mesh The mesh that this bone is attached to
  90576. * @returns The world direction
  90577. */
  90578. Bone.prototype.getDirection = function (localAxis, mesh) {
  90579. if (mesh === void 0) { mesh = null; }
  90580. var result = BABYLON.Vector3.Zero();
  90581. this.getDirectionToRef(localAxis, mesh, result);
  90582. return result;
  90583. };
  90584. /**
  90585. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90586. * @param localAxis The local direction that is used to compute the world direction
  90587. * @param mesh The mesh that this bone is attached to
  90588. * @param result The vector3 that the world direction will be copied to
  90589. */
  90590. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90591. if (mesh === void 0) { mesh = null; }
  90592. var wm = null;
  90593. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90594. if (mesh) {
  90595. wm = mesh.getWorldMatrix();
  90596. }
  90597. this._skeleton.computeAbsoluteTransforms();
  90598. var mat = Bone._tmpMats[0];
  90599. mat.copyFrom(this.getAbsoluteTransform());
  90600. if (mesh && wm) {
  90601. mat.multiplyToRef(wm, mat);
  90602. }
  90603. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90604. result.normalize();
  90605. };
  90606. /**
  90607. * Get the euler rotation of the bone in local or world space
  90608. * @param space The space that the rotation should be in
  90609. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90610. * @returns The euler rotation
  90611. */
  90612. Bone.prototype.getRotation = function (space, mesh) {
  90613. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90614. if (mesh === void 0) { mesh = null; }
  90615. var result = BABYLON.Vector3.Zero();
  90616. this.getRotationToRef(space, mesh, result);
  90617. return result;
  90618. };
  90619. /**
  90620. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90621. * @param space The space that the rotation should be in
  90622. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90623. * @param result The vector3 that the rotation should be copied to
  90624. */
  90625. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90626. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90627. if (mesh === void 0) { mesh = null; }
  90628. var quat = Bone._tmpQuat;
  90629. this.getRotationQuaternionToRef(space, mesh, quat);
  90630. quat.toEulerAnglesToRef(result);
  90631. };
  90632. /**
  90633. * Get the quaternion rotation of the bone in either local or world space
  90634. * @param space The space that the rotation should be in
  90635. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90636. * @returns The quaternion rotation
  90637. */
  90638. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90640. if (mesh === void 0) { mesh = null; }
  90641. var result = BABYLON.Quaternion.Identity();
  90642. this.getRotationQuaternionToRef(space, mesh, result);
  90643. return result;
  90644. };
  90645. /**
  90646. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90647. * @param space The space that the rotation should be in
  90648. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90649. * @param result The quaternion that the rotation should be copied to
  90650. */
  90651. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90652. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90653. if (mesh === void 0) { mesh = null; }
  90654. if (space == BABYLON.Space.LOCAL) {
  90655. this._decompose();
  90656. result.copyFrom(this._localRotation);
  90657. }
  90658. else {
  90659. var mat = Bone._tmpMats[0];
  90660. var amat = this.getAbsoluteTransform();
  90661. if (mesh) {
  90662. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90663. }
  90664. else {
  90665. mat.copyFrom(amat);
  90666. }
  90667. mat.m[0] *= this._scalingDeterminant;
  90668. mat.m[1] *= this._scalingDeterminant;
  90669. mat.m[2] *= this._scalingDeterminant;
  90670. mat.decompose(undefined, result, undefined);
  90671. }
  90672. };
  90673. /**
  90674. * Get the rotation matrix of the bone in local or world space
  90675. * @param space The space that the rotation should be in
  90676. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90677. * @returns The rotation matrix
  90678. */
  90679. Bone.prototype.getRotationMatrix = function (space, mesh) {
  90680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90681. var result = BABYLON.Matrix.Identity();
  90682. this.getRotationMatrixToRef(space, mesh, result);
  90683. return result;
  90684. };
  90685. /**
  90686. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  90687. * @param space The space that the rotation should be in
  90688. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90689. * @param result The quaternion that the rotation should be copied to
  90690. */
  90691. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  90692. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90693. if (space == BABYLON.Space.LOCAL) {
  90694. this.getLocalMatrix().getRotationMatrixToRef(result);
  90695. }
  90696. else {
  90697. var mat = Bone._tmpMats[0];
  90698. var amat = this.getAbsoluteTransform();
  90699. if (mesh) {
  90700. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90701. }
  90702. else {
  90703. mat.copyFrom(amat);
  90704. }
  90705. mat.m[0] *= this._scalingDeterminant;
  90706. mat.m[1] *= this._scalingDeterminant;
  90707. mat.m[2] *= this._scalingDeterminant;
  90708. mat.getRotationMatrixToRef(result);
  90709. }
  90710. };
  90711. /**
  90712. * Get the world position of a point that is in the local space of the bone
  90713. * @param position The local position
  90714. * @param mesh The mesh that this bone is attached to
  90715. * @returns The world position
  90716. */
  90717. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  90718. if (mesh === void 0) { mesh = null; }
  90719. var result = BABYLON.Vector3.Zero();
  90720. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  90721. return result;
  90722. };
  90723. /**
  90724. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  90725. * @param position The local position
  90726. * @param mesh The mesh that this bone is attached to
  90727. * @param result The vector3 that the world position should be copied to
  90728. */
  90729. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  90730. if (mesh === void 0) { mesh = null; }
  90731. var wm = null;
  90732. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90733. if (mesh) {
  90734. wm = mesh.getWorldMatrix();
  90735. }
  90736. this._skeleton.computeAbsoluteTransforms();
  90737. var tmat = Bone._tmpMats[0];
  90738. if (mesh && wm) {
  90739. tmat.copyFrom(this.getAbsoluteTransform());
  90740. tmat.multiplyToRef(wm, tmat);
  90741. }
  90742. else {
  90743. tmat = this.getAbsoluteTransform();
  90744. }
  90745. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  90746. };
  90747. /**
  90748. * Get the local position of a point that is in world space
  90749. * @param position The world position
  90750. * @param mesh The mesh that this bone is attached to
  90751. * @returns The local position
  90752. */
  90753. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  90754. if (mesh === void 0) { mesh = null; }
  90755. var result = BABYLON.Vector3.Zero();
  90756. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  90757. return result;
  90758. };
  90759. /**
  90760. * Get the local position of a point that is in world space and copy it to the result param
  90761. * @param position The world position
  90762. * @param mesh The mesh that this bone is attached to
  90763. * @param result The vector3 that the local position should be copied to
  90764. */
  90765. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  90766. if (mesh === void 0) { mesh = null; }
  90767. var wm = null;
  90768. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90769. if (mesh) {
  90770. wm = mesh.getWorldMatrix();
  90771. }
  90772. this._skeleton.computeAbsoluteTransforms();
  90773. var tmat = Bone._tmpMats[0];
  90774. tmat.copyFrom(this.getAbsoluteTransform());
  90775. if (mesh && wm) {
  90776. tmat.multiplyToRef(wm, tmat);
  90777. }
  90778. tmat.invert();
  90779. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  90780. };
  90781. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90782. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  90783. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90784. return Bone;
  90785. }(BABYLON.Node));
  90786. BABYLON.Bone = Bone;
  90787. })(BABYLON || (BABYLON = {}));
  90788. //# sourceMappingURL=babylon.bone.js.map
  90789. var BABYLON;
  90790. (function (BABYLON) {
  90791. /**
  90792. * Class used to apply inverse kinematics to bones
  90793. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  90794. */
  90795. var BoneIKController = /** @class */ (function () {
  90796. /**
  90797. * Creates a new BoneIKController
  90798. * @param mesh defines the mesh to control
  90799. * @param bone defines the bone to control
  90800. * @param options defines options to set up the controller
  90801. */
  90802. function BoneIKController(mesh, bone, options) {
  90803. /**
  90804. * Gets or sets the target position
  90805. */
  90806. this.targetPosition = BABYLON.Vector3.Zero();
  90807. /**
  90808. * Gets or sets the pole target position
  90809. */
  90810. this.poleTargetPosition = BABYLON.Vector3.Zero();
  90811. /**
  90812. * Gets or sets the pole target local offset
  90813. */
  90814. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  90815. /**
  90816. * Gets or sets the pole angle
  90817. */
  90818. this.poleAngle = 0;
  90819. /**
  90820. * 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)
  90821. */
  90822. this.slerpAmount = 1;
  90823. this._bone1Quat = BABYLON.Quaternion.Identity();
  90824. this._bone1Mat = BABYLON.Matrix.Identity();
  90825. this._bone2Ang = Math.PI;
  90826. this._maxAngle = Math.PI;
  90827. this._rightHandedSystem = false;
  90828. this._bendAxis = BABYLON.Vector3.Right();
  90829. this._slerping = false;
  90830. this._adjustRoll = 0;
  90831. this._bone2 = bone;
  90832. this._bone1 = bone.getParent();
  90833. if (!this._bone1) {
  90834. return;
  90835. }
  90836. this.mesh = mesh;
  90837. var bonePos = bone.getPosition();
  90838. if (bone.getAbsoluteTransform().determinant() > 0) {
  90839. this._rightHandedSystem = true;
  90840. this._bendAxis.x = 0;
  90841. this._bendAxis.y = 0;
  90842. this._bendAxis.z = -1;
  90843. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  90844. this._adjustRoll = Math.PI * .5;
  90845. this._bendAxis.z = 1;
  90846. }
  90847. }
  90848. if (this._bone1.length) {
  90849. var boneScale1 = this._bone1.getScale();
  90850. var boneScale2 = this._bone2.getScale();
  90851. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  90852. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  90853. }
  90854. else if (this._bone1.children[0]) {
  90855. mesh.computeWorldMatrix(true);
  90856. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  90857. var pos2 = this._bone2.getAbsolutePosition(mesh);
  90858. var pos3 = this._bone1.getAbsolutePosition(mesh);
  90859. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  90860. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  90861. }
  90862. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  90863. this.maxAngle = Math.PI;
  90864. if (options) {
  90865. if (options.targetMesh) {
  90866. this.targetMesh = options.targetMesh;
  90867. this.targetMesh.computeWorldMatrix(true);
  90868. }
  90869. if (options.poleTargetMesh) {
  90870. this.poleTargetMesh = options.poleTargetMesh;
  90871. this.poleTargetMesh.computeWorldMatrix(true);
  90872. }
  90873. else if (options.poleTargetBone) {
  90874. this.poleTargetBone = options.poleTargetBone;
  90875. }
  90876. else if (this._bone1.getParent()) {
  90877. this.poleTargetBone = this._bone1.getParent();
  90878. }
  90879. if (options.poleTargetLocalOffset) {
  90880. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  90881. }
  90882. if (options.poleAngle) {
  90883. this.poleAngle = options.poleAngle;
  90884. }
  90885. if (options.bendAxis) {
  90886. this._bendAxis.copyFrom(options.bendAxis);
  90887. }
  90888. if (options.maxAngle) {
  90889. this.maxAngle = options.maxAngle;
  90890. }
  90891. if (options.slerpAmount) {
  90892. this.slerpAmount = options.slerpAmount;
  90893. }
  90894. }
  90895. }
  90896. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  90897. /**
  90898. * Gets or sets maximum allowed angle
  90899. */
  90900. get: function () {
  90901. return this._maxAngle;
  90902. },
  90903. set: function (value) {
  90904. this._setMaxAngle(value);
  90905. },
  90906. enumerable: true,
  90907. configurable: true
  90908. });
  90909. BoneIKController.prototype._setMaxAngle = function (ang) {
  90910. if (ang < 0) {
  90911. ang = 0;
  90912. }
  90913. if (ang > Math.PI || ang == undefined) {
  90914. ang = Math.PI;
  90915. }
  90916. this._maxAngle = ang;
  90917. var a = this._bone1Length;
  90918. var b = this._bone2Length;
  90919. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  90920. };
  90921. /**
  90922. * Force the controller to update the bones
  90923. */
  90924. BoneIKController.prototype.update = function () {
  90925. var bone1 = this._bone1;
  90926. if (!bone1) {
  90927. return;
  90928. }
  90929. var target = this.targetPosition;
  90930. var poleTarget = this.poleTargetPosition;
  90931. var mat1 = BoneIKController._tmpMats[0];
  90932. var mat2 = BoneIKController._tmpMats[1];
  90933. if (this.targetMesh) {
  90934. target.copyFrom(this.targetMesh.getAbsolutePosition());
  90935. }
  90936. if (this.poleTargetBone) {
  90937. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  90938. }
  90939. else if (this.poleTargetMesh) {
  90940. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  90941. }
  90942. var bonePos = BoneIKController._tmpVecs[0];
  90943. var zaxis = BoneIKController._tmpVecs[1];
  90944. var xaxis = BoneIKController._tmpVecs[2];
  90945. var yaxis = BoneIKController._tmpVecs[3];
  90946. var upAxis = BoneIKController._tmpVecs[4];
  90947. var _tmpQuat = BoneIKController._tmpQuat;
  90948. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  90949. poleTarget.subtractToRef(bonePos, upAxis);
  90950. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  90951. upAxis.y = 1;
  90952. }
  90953. else {
  90954. upAxis.normalize();
  90955. }
  90956. target.subtractToRef(bonePos, yaxis);
  90957. yaxis.normalize();
  90958. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  90959. zaxis.normalize();
  90960. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  90961. xaxis.normalize();
  90962. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  90963. var a = this._bone1Length;
  90964. var b = this._bone2Length;
  90965. var c = BABYLON.Vector3.Distance(bonePos, target);
  90966. if (this._maxReach > 0) {
  90967. c = Math.min(this._maxReach, c);
  90968. }
  90969. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  90970. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  90971. if (acosa > 1) {
  90972. acosa = 1;
  90973. }
  90974. if (acosb > 1) {
  90975. acosb = 1;
  90976. }
  90977. if (acosa < -1) {
  90978. acosa = -1;
  90979. }
  90980. if (acosb < -1) {
  90981. acosb = -1;
  90982. }
  90983. var angA = Math.acos(acosa);
  90984. var angB = Math.acos(acosb);
  90985. var angC = -angA - angB;
  90986. if (this._rightHandedSystem) {
  90987. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  90988. mat2.multiplyToRef(mat1, mat1);
  90989. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  90990. mat2.multiplyToRef(mat1, mat1);
  90991. }
  90992. else {
  90993. var _tmpVec = BoneIKController._tmpVecs[5];
  90994. _tmpVec.copyFrom(this._bendAxis);
  90995. _tmpVec.x *= -1;
  90996. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  90997. mat2.multiplyToRef(mat1, mat1);
  90998. }
  90999. if (this.poleAngle) {
  91000. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  91001. mat1.multiplyToRef(mat2, mat1);
  91002. }
  91003. if (this._bone1) {
  91004. if (this.slerpAmount < 1) {
  91005. if (!this._slerping) {
  91006. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  91007. }
  91008. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  91009. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  91010. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  91011. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  91012. this._slerping = true;
  91013. }
  91014. else {
  91015. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91016. this._bone1Mat.copyFrom(mat1);
  91017. this._slerping = false;
  91018. }
  91019. }
  91020. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91021. this._bone2Ang = angC;
  91022. };
  91023. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91024. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91025. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91026. return BoneIKController;
  91027. }());
  91028. BABYLON.BoneIKController = BoneIKController;
  91029. })(BABYLON || (BABYLON = {}));
  91030. //# sourceMappingURL=babylon.boneIKController.js.map
  91031. var BABYLON;
  91032. (function (BABYLON) {
  91033. /**
  91034. * Class used to make a bone look toward a point in space
  91035. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91036. */
  91037. var BoneLookController = /** @class */ (function () {
  91038. /**
  91039. * Create a BoneLookController
  91040. * @param mesh the mesh that the bone belongs to
  91041. * @param bone the bone that will be looking to the target
  91042. * @param target the target Vector3 to look at
  91043. * @param settings optional settings:
  91044. * * maxYaw: the maximum angle the bone will yaw to
  91045. * * minYaw: the minimum angle the bone will yaw to
  91046. * * maxPitch: the maximum angle the bone will pitch to
  91047. * * minPitch: the minimum angle the bone will yaw to
  91048. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91049. * * upAxis: the up axis of the coordinate system
  91050. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91051. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91052. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91053. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91054. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91055. * * adjustRoll: used to make an adjustment to the roll of the bone
  91056. **/
  91057. function BoneLookController(mesh, bone, target, options) {
  91058. /**
  91059. * The up axis of the coordinate system that is used when the bone is rotated
  91060. */
  91061. this.upAxis = BABYLON.Vector3.Up();
  91062. /**
  91063. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91064. */
  91065. this.upAxisSpace = BABYLON.Space.LOCAL;
  91066. /**
  91067. * Used to make an adjustment to the yaw of the bone
  91068. */
  91069. this.adjustYaw = 0;
  91070. /**
  91071. * Used to make an adjustment to the pitch of the bone
  91072. */
  91073. this.adjustPitch = 0;
  91074. /**
  91075. * Used to make an adjustment to the roll of the bone
  91076. */
  91077. this.adjustRoll = 0;
  91078. /**
  91079. * 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)
  91080. */
  91081. this.slerpAmount = 1;
  91082. this._boneQuat = BABYLON.Quaternion.Identity();
  91083. this._slerping = false;
  91084. this._firstFrameSkipped = false;
  91085. this._fowardAxis = BABYLON.Vector3.Forward();
  91086. this.mesh = mesh;
  91087. this.bone = bone;
  91088. this.target = target;
  91089. if (options) {
  91090. if (options.adjustYaw) {
  91091. this.adjustYaw = options.adjustYaw;
  91092. }
  91093. if (options.adjustPitch) {
  91094. this.adjustPitch = options.adjustPitch;
  91095. }
  91096. if (options.adjustRoll) {
  91097. this.adjustRoll = options.adjustRoll;
  91098. }
  91099. if (options.maxYaw != null) {
  91100. this.maxYaw = options.maxYaw;
  91101. }
  91102. else {
  91103. this.maxYaw = Math.PI;
  91104. }
  91105. if (options.minYaw != null) {
  91106. this.minYaw = options.minYaw;
  91107. }
  91108. else {
  91109. this.minYaw = -Math.PI;
  91110. }
  91111. if (options.maxPitch != null) {
  91112. this.maxPitch = options.maxPitch;
  91113. }
  91114. else {
  91115. this.maxPitch = Math.PI;
  91116. }
  91117. if (options.minPitch != null) {
  91118. this.minPitch = options.minPitch;
  91119. }
  91120. else {
  91121. this.minPitch = -Math.PI;
  91122. }
  91123. if (options.slerpAmount != null) {
  91124. this.slerpAmount = options.slerpAmount;
  91125. }
  91126. if (options.upAxis != null) {
  91127. this.upAxis = options.upAxis;
  91128. }
  91129. if (options.upAxisSpace != null) {
  91130. this.upAxisSpace = options.upAxisSpace;
  91131. }
  91132. if (options.yawAxis != null || options.pitchAxis != null) {
  91133. var newYawAxis = BABYLON.Axis.Y;
  91134. var newPitchAxis = BABYLON.Axis.X;
  91135. if (options.yawAxis != null) {
  91136. newYawAxis = options.yawAxis.clone();
  91137. newYawAxis.normalize();
  91138. }
  91139. if (options.pitchAxis != null) {
  91140. newPitchAxis = options.pitchAxis.clone();
  91141. newPitchAxis.normalize();
  91142. }
  91143. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91144. this._transformYawPitch = BABYLON.Matrix.Identity();
  91145. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91146. this._transformYawPitchInv = this._transformYawPitch.clone();
  91147. this._transformYawPitch.invert();
  91148. }
  91149. }
  91150. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91151. this.upAxisSpace = BABYLON.Space.LOCAL;
  91152. }
  91153. }
  91154. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91155. /**
  91156. * Gets or sets the minimum yaw angle that the bone can look to
  91157. */
  91158. get: function () {
  91159. return this._minYaw;
  91160. },
  91161. set: function (value) {
  91162. this._minYaw = value;
  91163. this._minYawSin = Math.sin(value);
  91164. this._minYawCos = Math.cos(value);
  91165. if (this._maxYaw != null) {
  91166. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91167. this._yawRange = this._maxYaw - this._minYaw;
  91168. }
  91169. },
  91170. enumerable: true,
  91171. configurable: true
  91172. });
  91173. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91174. /**
  91175. * Gets or sets the maximum yaw angle that the bone can look to
  91176. */
  91177. get: function () {
  91178. return this._maxYaw;
  91179. },
  91180. set: function (value) {
  91181. this._maxYaw = value;
  91182. this._maxYawSin = Math.sin(value);
  91183. this._maxYawCos = Math.cos(value);
  91184. if (this._minYaw != null) {
  91185. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91186. this._yawRange = this._maxYaw - this._minYaw;
  91187. }
  91188. },
  91189. enumerable: true,
  91190. configurable: true
  91191. });
  91192. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91193. /**
  91194. * Gets or sets the minimum pitch angle that the bone can look to
  91195. */
  91196. get: function () {
  91197. return this._minPitch;
  91198. },
  91199. set: function (value) {
  91200. this._minPitch = value;
  91201. this._minPitchTan = Math.tan(value);
  91202. },
  91203. enumerable: true,
  91204. configurable: true
  91205. });
  91206. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91207. /**
  91208. * Gets or sets the maximum pitch angle that the bone can look to
  91209. */
  91210. get: function () {
  91211. return this._maxPitch;
  91212. },
  91213. set: function (value) {
  91214. this._maxPitch = value;
  91215. this._maxPitchTan = Math.tan(value);
  91216. },
  91217. enumerable: true,
  91218. configurable: true
  91219. });
  91220. /**
  91221. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91222. */
  91223. BoneLookController.prototype.update = function () {
  91224. //skip the first frame when slerping so that the mesh rotation is correct
  91225. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91226. this._firstFrameSkipped = true;
  91227. return;
  91228. }
  91229. var bone = this.bone;
  91230. var bonePos = BoneLookController._tmpVecs[0];
  91231. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91232. var target = this.target;
  91233. var _tmpMat1 = BoneLookController._tmpMats[0];
  91234. var _tmpMat2 = BoneLookController._tmpMats[1];
  91235. var mesh = this.mesh;
  91236. var parentBone = bone.getParent();
  91237. var upAxis = BoneLookController._tmpVecs[1];
  91238. upAxis.copyFrom(this.upAxis);
  91239. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91240. if (this._transformYawPitch) {
  91241. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91242. }
  91243. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91244. }
  91245. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91246. mesh.getDirectionToRef(upAxis, upAxis);
  91247. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91248. upAxis.normalize();
  91249. }
  91250. }
  91251. var checkYaw = false;
  91252. var checkPitch = false;
  91253. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91254. checkYaw = true;
  91255. }
  91256. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91257. checkPitch = true;
  91258. }
  91259. if (checkYaw || checkPitch) {
  91260. var spaceMat = BoneLookController._tmpMats[2];
  91261. var spaceMatInv = BoneLookController._tmpMats[3];
  91262. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91263. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91264. }
  91265. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91266. spaceMat.copyFrom(mesh.getWorldMatrix());
  91267. }
  91268. else {
  91269. var forwardAxis = BoneLookController._tmpVecs[2];
  91270. forwardAxis.copyFrom(this._fowardAxis);
  91271. if (this._transformYawPitch) {
  91272. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91273. }
  91274. if (parentBone) {
  91275. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91276. }
  91277. else {
  91278. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91279. }
  91280. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91281. rightAxis.normalize();
  91282. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91283. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91284. }
  91285. spaceMat.invertToRef(spaceMatInv);
  91286. var xzlen = null;
  91287. if (checkPitch) {
  91288. var localTarget = BoneLookController._tmpVecs[3];
  91289. target.subtractToRef(bonePos, localTarget);
  91290. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91291. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91292. var pitch = Math.atan2(localTarget.y, xzlen);
  91293. var newPitch = pitch;
  91294. if (pitch > this._maxPitch) {
  91295. localTarget.y = this._maxPitchTan * xzlen;
  91296. newPitch = this._maxPitch;
  91297. }
  91298. else if (pitch < this._minPitch) {
  91299. localTarget.y = this._minPitchTan * xzlen;
  91300. newPitch = this._minPitch;
  91301. }
  91302. if (pitch != newPitch) {
  91303. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91304. localTarget.addInPlace(bonePos);
  91305. target = localTarget;
  91306. }
  91307. }
  91308. if (checkYaw) {
  91309. var localTarget = BoneLookController._tmpVecs[4];
  91310. target.subtractToRef(bonePos, localTarget);
  91311. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91312. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91313. var newYaw = yaw;
  91314. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91315. if (xzlen == null) {
  91316. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91317. }
  91318. if (this._yawRange > Math.PI) {
  91319. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91320. localTarget.z = this._maxYawCos * xzlen;
  91321. localTarget.x = this._maxYawSin * xzlen;
  91322. newYaw = this._maxYaw;
  91323. }
  91324. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91325. localTarget.z = this._minYawCos * xzlen;
  91326. localTarget.x = this._minYawSin * xzlen;
  91327. newYaw = this._minYaw;
  91328. }
  91329. }
  91330. else {
  91331. if (yaw > this._maxYaw) {
  91332. localTarget.z = this._maxYawCos * xzlen;
  91333. localTarget.x = this._maxYawSin * xzlen;
  91334. newYaw = this._maxYaw;
  91335. }
  91336. else if (yaw < this._minYaw) {
  91337. localTarget.z = this._minYawCos * xzlen;
  91338. localTarget.x = this._minYawSin * xzlen;
  91339. newYaw = this._minYaw;
  91340. }
  91341. }
  91342. }
  91343. if (this._slerping && this._yawRange > Math.PI) {
  91344. //are we going to be crossing into the min/max region?
  91345. var boneFwd = BoneLookController._tmpVecs[8];
  91346. boneFwd.copyFrom(BABYLON.Axis.Z);
  91347. if (this._transformYawPitch) {
  91348. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91349. }
  91350. var boneRotMat = BoneLookController._tmpMats[4];
  91351. this._boneQuat.toRotationMatrix(boneRotMat);
  91352. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91353. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91354. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91355. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91356. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91357. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91358. if (angBtwTar > angBtwMidYaw) {
  91359. if (xzlen == null) {
  91360. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91361. }
  91362. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91363. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91364. if (angBtwMin < angBtwMax) {
  91365. newYaw = boneYaw + Math.PI * .75;
  91366. localTarget.z = Math.cos(newYaw) * xzlen;
  91367. localTarget.x = Math.sin(newYaw) * xzlen;
  91368. }
  91369. else {
  91370. newYaw = boneYaw - Math.PI * .75;
  91371. localTarget.z = Math.cos(newYaw) * xzlen;
  91372. localTarget.x = Math.sin(newYaw) * xzlen;
  91373. }
  91374. }
  91375. }
  91376. if (yaw != newYaw) {
  91377. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91378. localTarget.addInPlace(bonePos);
  91379. target = localTarget;
  91380. }
  91381. }
  91382. }
  91383. var zaxis = BoneLookController._tmpVecs[5];
  91384. var xaxis = BoneLookController._tmpVecs[6];
  91385. var yaxis = BoneLookController._tmpVecs[7];
  91386. var _tmpQuat = BoneLookController._tmpQuat;
  91387. target.subtractToRef(bonePos, zaxis);
  91388. zaxis.normalize();
  91389. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91390. xaxis.normalize();
  91391. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91392. yaxis.normalize();
  91393. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91394. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91395. return;
  91396. }
  91397. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91398. return;
  91399. }
  91400. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91401. return;
  91402. }
  91403. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91404. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91405. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91406. }
  91407. if (this.slerpAmount < 1) {
  91408. if (!this._slerping) {
  91409. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91410. }
  91411. if (this._transformYawPitch) {
  91412. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91413. }
  91414. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91415. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91416. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91417. this._slerping = true;
  91418. }
  91419. else {
  91420. if (this._transformYawPitch) {
  91421. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91422. }
  91423. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91424. this._slerping = false;
  91425. }
  91426. };
  91427. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91428. var angDiff = ang2 - ang1;
  91429. angDiff %= Math.PI * 2;
  91430. if (angDiff > Math.PI) {
  91431. angDiff -= Math.PI * 2;
  91432. }
  91433. else if (angDiff < -Math.PI) {
  91434. angDiff += Math.PI * 2;
  91435. }
  91436. return angDiff;
  91437. };
  91438. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91439. ang1 %= (2 * Math.PI);
  91440. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91441. ang2 %= (2 * Math.PI);
  91442. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91443. var ab = 0;
  91444. if (ang1 < ang2) {
  91445. ab = ang2 - ang1;
  91446. }
  91447. else {
  91448. ab = ang1 - ang2;
  91449. }
  91450. if (ab > Math.PI) {
  91451. ab = Math.PI * 2 - ab;
  91452. }
  91453. return ab;
  91454. };
  91455. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91456. ang %= (2 * Math.PI);
  91457. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91458. ang1 %= (2 * Math.PI);
  91459. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91460. ang2 %= (2 * Math.PI);
  91461. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91462. if (ang1 < ang2) {
  91463. if (ang > ang1 && ang < ang2) {
  91464. return true;
  91465. }
  91466. }
  91467. else {
  91468. if (ang > ang2 && ang < ang1) {
  91469. return true;
  91470. }
  91471. }
  91472. return false;
  91473. };
  91474. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91475. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91476. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91477. return BoneLookController;
  91478. }());
  91479. BABYLON.BoneLookController = BoneLookController;
  91480. })(BABYLON || (BABYLON = {}));
  91481. //# sourceMappingURL=babylon.boneLookController.js.map
  91482. var BABYLON;
  91483. (function (BABYLON) {
  91484. /**
  91485. * Class used to handle skinning animations
  91486. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91487. */
  91488. var Skeleton = /** @class */ (function () {
  91489. /**
  91490. * Creates a new skeleton
  91491. * @param name defines the skeleton name
  91492. * @param id defines the skeleton Id
  91493. * @param scene defines the hosting scene
  91494. */
  91495. function Skeleton(
  91496. /** defines the skeleton name */
  91497. name,
  91498. /** defines the skeleton Id */
  91499. id, scene) {
  91500. this.name = name;
  91501. this.id = id;
  91502. /**
  91503. * Gets the list of child bones
  91504. */
  91505. this.bones = new Array();
  91506. /**
  91507. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91508. */
  91509. this.needInitialSkinMatrix = false;
  91510. this._isDirty = true;
  91511. this._meshesWithPoseMatrix = new Array();
  91512. this._identity = BABYLON.Matrix.Identity();
  91513. this._ranges = {};
  91514. this._lastAbsoluteTransformsUpdateId = -1;
  91515. /**
  91516. * Specifies if the skeleton should be serialized
  91517. */
  91518. this.doNotSerialize = false;
  91519. this._animationPropertiesOverride = null;
  91520. // Events
  91521. /**
  91522. * An observable triggered before computing the skeleton's matrices
  91523. */
  91524. this.onBeforeComputeObservable = new BABYLON.Observable();
  91525. this.bones = [];
  91526. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91527. scene.skeletons.push(this);
  91528. //make sure it will recalculate the matrix next time prepare is called.
  91529. this._isDirty = true;
  91530. }
  91531. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91532. /**
  91533. * Gets or sets the animation properties override
  91534. */
  91535. get: function () {
  91536. if (!this._animationPropertiesOverride) {
  91537. return this._scene.animationPropertiesOverride;
  91538. }
  91539. return this._animationPropertiesOverride;
  91540. },
  91541. set: function (value) {
  91542. this._animationPropertiesOverride = value;
  91543. },
  91544. enumerable: true,
  91545. configurable: true
  91546. });
  91547. // Members
  91548. /**
  91549. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91550. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91551. * @returns a Float32Array containing matrices data
  91552. */
  91553. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91554. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91555. return mesh._bonesTransformMatrices;
  91556. }
  91557. if (!this._transformMatrices) {
  91558. this.prepare();
  91559. }
  91560. return this._transformMatrices;
  91561. };
  91562. /**
  91563. * Gets the current hosting scene
  91564. * @returns a scene object
  91565. */
  91566. Skeleton.prototype.getScene = function () {
  91567. return this._scene;
  91568. };
  91569. // Methods
  91570. /**
  91571. * Gets a string representing the current skeleton data
  91572. * @param fullDetails defines a boolean indicating if we want a verbose version
  91573. * @returns a string representing the current skeleton data
  91574. */
  91575. Skeleton.prototype.toString = function (fullDetails) {
  91576. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91577. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91578. if (fullDetails) {
  91579. ret += ", Ranges: {";
  91580. var first = true;
  91581. for (var name_1 in this._ranges) {
  91582. if (first) {
  91583. ret += ", ";
  91584. first = false;
  91585. }
  91586. ret += name_1;
  91587. }
  91588. ret += "}";
  91589. }
  91590. return ret;
  91591. };
  91592. /**
  91593. * Get bone's index searching by name
  91594. * @param name defines bone's name to search for
  91595. * @return the indice of the bone. Returns -1 if not found
  91596. */
  91597. Skeleton.prototype.getBoneIndexByName = function (name) {
  91598. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91599. if (this.bones[boneIndex].name === name) {
  91600. return boneIndex;
  91601. }
  91602. }
  91603. return -1;
  91604. };
  91605. /**
  91606. * Creater a new animation range
  91607. * @param name defines the name of the range
  91608. * @param from defines the start key
  91609. * @param to defines the end key
  91610. */
  91611. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91612. // check name not already in use
  91613. if (!this._ranges[name]) {
  91614. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91615. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91616. if (this.bones[i].animations[0]) {
  91617. this.bones[i].animations[0].createRange(name, from, to);
  91618. }
  91619. }
  91620. }
  91621. };
  91622. /**
  91623. * Delete a specific animation range
  91624. * @param name defines the name of the range
  91625. * @param deleteFrames defines if frames must be removed as well
  91626. */
  91627. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91628. if (deleteFrames === void 0) { deleteFrames = true; }
  91629. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91630. if (this.bones[i].animations[0]) {
  91631. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91632. }
  91633. }
  91634. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91635. };
  91636. /**
  91637. * Gets a specific animation range
  91638. * @param name defines the name of the range to look for
  91639. * @returns the requested animation range or null if not found
  91640. */
  91641. Skeleton.prototype.getAnimationRange = function (name) {
  91642. return this._ranges[name];
  91643. };
  91644. /**
  91645. * Gets the list of all animation ranges defined on this skeleton
  91646. * @returns an array
  91647. */
  91648. Skeleton.prototype.getAnimationRanges = function () {
  91649. var animationRanges = [];
  91650. var name;
  91651. var i = 0;
  91652. for (name in this._ranges) {
  91653. animationRanges[i] = this._ranges[name];
  91654. i++;
  91655. }
  91656. return animationRanges;
  91657. };
  91658. /**
  91659. * Copy animation range from a source skeleton.
  91660. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91661. * @param source defines the source skeleton
  91662. * @param name defines the name of the range to copy
  91663. * @param rescaleAsRequired defines if rescaling must be applied if required
  91664. * @returns true if operation was successful
  91665. */
  91666. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91667. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91668. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91669. return false;
  91670. }
  91671. var ret = true;
  91672. var frameOffset = this._getHighestAnimationFrame() + 1;
  91673. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91674. var boneDict = {};
  91675. var sourceBones = source.bones;
  91676. var nBones;
  91677. var i;
  91678. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  91679. boneDict[sourceBones[i].name] = sourceBones[i];
  91680. }
  91681. if (this.bones.length !== sourceBones.length) {
  91682. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  91683. ret = false;
  91684. }
  91685. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  91686. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  91687. var boneName = this.bones[i].name;
  91688. var sourceBone = boneDict[boneName];
  91689. if (sourceBone) {
  91690. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  91691. }
  91692. else {
  91693. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  91694. ret = false;
  91695. }
  91696. }
  91697. // do not call createAnimationRange(), since it also is done to bones, which was already done
  91698. var range = source.getAnimationRange(name);
  91699. if (range) {
  91700. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  91701. }
  91702. return ret;
  91703. };
  91704. /**
  91705. * Forces the skeleton to go to rest pose
  91706. */
  91707. Skeleton.prototype.returnToRest = function () {
  91708. for (var index = 0; index < this.bones.length; index++) {
  91709. this.bones[index].returnToRest();
  91710. }
  91711. };
  91712. Skeleton.prototype._getHighestAnimationFrame = function () {
  91713. var ret = 0;
  91714. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91715. if (this.bones[i].animations[0]) {
  91716. var highest = this.bones[i].animations[0].getHighestFrame();
  91717. if (ret < highest) {
  91718. ret = highest;
  91719. }
  91720. }
  91721. }
  91722. return ret;
  91723. };
  91724. /**
  91725. * Begin a specific animation range
  91726. * @param name defines the name of the range to start
  91727. * @param loop defines if looping must be turned on (false by default)
  91728. * @param speedRatio defines the speed ratio to apply (1 by default)
  91729. * @param onAnimationEnd defines a callback which will be called when animation will end
  91730. * @returns a new animatable
  91731. */
  91732. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  91733. var range = this.getAnimationRange(name);
  91734. if (!range) {
  91735. return null;
  91736. }
  91737. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  91738. };
  91739. /** @hidden */
  91740. Skeleton.prototype._markAsDirty = function () {
  91741. this._isDirty = true;
  91742. };
  91743. /** @hidden */
  91744. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  91745. this._meshesWithPoseMatrix.push(mesh);
  91746. };
  91747. /** @hidden */
  91748. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  91749. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  91750. if (index > -1) {
  91751. this._meshesWithPoseMatrix.splice(index, 1);
  91752. }
  91753. };
  91754. /** @hidden */
  91755. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  91756. this.onBeforeComputeObservable.notifyObservers(this);
  91757. for (var index = 0; index < this.bones.length; index++) {
  91758. var bone = this.bones[index];
  91759. var parentBone = bone.getParent();
  91760. if (parentBone) {
  91761. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  91762. }
  91763. else {
  91764. if (initialSkinMatrix) {
  91765. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  91766. }
  91767. else {
  91768. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  91769. }
  91770. }
  91771. if (bone._index !== -1) {
  91772. var mappedIndex = bone._index === null ? index : bone._index;
  91773. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  91774. }
  91775. }
  91776. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  91777. };
  91778. /**
  91779. * Build all resources required to render a skeleton
  91780. */
  91781. Skeleton.prototype.prepare = function () {
  91782. if (!this._isDirty) {
  91783. return;
  91784. }
  91785. if (this.needInitialSkinMatrix) {
  91786. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  91787. var mesh = this._meshesWithPoseMatrix[index];
  91788. var poseMatrix = mesh.getPoseMatrix();
  91789. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  91790. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  91791. }
  91792. if (this._synchronizedWithMesh !== mesh) {
  91793. this._synchronizedWithMesh = mesh;
  91794. // Prepare bones
  91795. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  91796. var bone = this.bones[boneIndex];
  91797. if (!bone.getParent()) {
  91798. var matrix = bone.getBaseMatrix();
  91799. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  91800. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  91801. }
  91802. }
  91803. }
  91804. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  91805. }
  91806. }
  91807. else {
  91808. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  91809. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  91810. }
  91811. this._computeTransformMatrices(this._transformMatrices, null);
  91812. }
  91813. this._isDirty = false;
  91814. this._scene._activeBones.addCount(this.bones.length, false);
  91815. };
  91816. /**
  91817. * Gets the list of animatables currently running for this skeleton
  91818. * @returns an array of animatables
  91819. */
  91820. Skeleton.prototype.getAnimatables = function () {
  91821. if (!this._animatables || this._animatables.length !== this.bones.length) {
  91822. this._animatables = [];
  91823. for (var index = 0; index < this.bones.length; index++) {
  91824. this._animatables.push(this.bones[index]);
  91825. }
  91826. }
  91827. return this._animatables;
  91828. };
  91829. /**
  91830. * Clone the current skeleton
  91831. * @param name defines the name of the new skeleton
  91832. * @param id defines the id of the enw skeleton
  91833. * @returns the new skeleton
  91834. */
  91835. Skeleton.prototype.clone = function (name, id) {
  91836. var result = new Skeleton(name, id || name, this._scene);
  91837. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  91838. for (var index = 0; index < this.bones.length; index++) {
  91839. var source = this.bones[index];
  91840. var parentBone = null;
  91841. var parent_1 = source.getParent();
  91842. if (parent_1) {
  91843. var parentIndex = this.bones.indexOf(parent_1);
  91844. parentBone = result.bones[parentIndex];
  91845. }
  91846. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  91847. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  91848. }
  91849. if (this._ranges) {
  91850. result._ranges = {};
  91851. for (var rangeName in this._ranges) {
  91852. var range = this._ranges[rangeName];
  91853. if (range) {
  91854. result._ranges[rangeName] = range.clone();
  91855. }
  91856. }
  91857. }
  91858. this._isDirty = true;
  91859. return result;
  91860. };
  91861. /**
  91862. * Enable animation blending for this skeleton
  91863. * @param blendingSpeed defines the blending speed to apply
  91864. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  91865. */
  91866. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  91867. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  91868. this.bones.forEach(function (bone) {
  91869. bone.animations.forEach(function (animation) {
  91870. animation.enableBlending = true;
  91871. animation.blendingSpeed = blendingSpeed;
  91872. });
  91873. });
  91874. };
  91875. /**
  91876. * Releases all resources associated with the current skeleton
  91877. */
  91878. Skeleton.prototype.dispose = function () {
  91879. this._meshesWithPoseMatrix = [];
  91880. // Animations
  91881. this.getScene().stopAnimation(this);
  91882. // Remove from scene
  91883. this.getScene().removeSkeleton(this);
  91884. };
  91885. /**
  91886. * Serialize the skeleton in a JSON object
  91887. * @returns a JSON object
  91888. */
  91889. Skeleton.prototype.serialize = function () {
  91890. var serializationObject = {};
  91891. serializationObject.name = this.name;
  91892. serializationObject.id = this.id;
  91893. if (this.dimensionsAtRest) {
  91894. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  91895. }
  91896. serializationObject.bones = [];
  91897. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  91898. for (var index = 0; index < this.bones.length; index++) {
  91899. var bone = this.bones[index];
  91900. var parent_2 = bone.getParent();
  91901. var serializedBone = {
  91902. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  91903. name: bone.name,
  91904. matrix: bone.getBaseMatrix().toArray(),
  91905. rest: bone.getRestPose().toArray()
  91906. };
  91907. serializationObject.bones.push(serializedBone);
  91908. if (bone.length) {
  91909. serializedBone.length = bone.length;
  91910. }
  91911. if (bone.metadata) {
  91912. serializedBone.metadata = bone.metadata;
  91913. }
  91914. if (bone.animations && bone.animations.length > 0) {
  91915. serializedBone.animation = bone.animations[0].serialize();
  91916. }
  91917. serializationObject.ranges = [];
  91918. for (var name in this._ranges) {
  91919. var source = this._ranges[name];
  91920. if (!source) {
  91921. continue;
  91922. }
  91923. var range = {};
  91924. range.name = name;
  91925. range.from = source.from;
  91926. range.to = source.to;
  91927. serializationObject.ranges.push(range);
  91928. }
  91929. }
  91930. return serializationObject;
  91931. };
  91932. /**
  91933. * Creates a new skeleton from serialized data
  91934. * @param parsedSkeleton defines the serialized data
  91935. * @param scene defines the hosting scene
  91936. * @returns a new skeleton
  91937. */
  91938. Skeleton.Parse = function (parsedSkeleton, scene) {
  91939. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  91940. if (parsedSkeleton.dimensionsAtRest) {
  91941. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  91942. }
  91943. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  91944. var index;
  91945. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  91946. var parsedBone = parsedSkeleton.bones[index];
  91947. var parentBone = null;
  91948. if (parsedBone.parentBoneIndex > -1) {
  91949. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  91950. }
  91951. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  91952. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  91953. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  91954. bone.id = parsedBone.id;
  91955. }
  91956. if (parsedBone.length) {
  91957. bone.length = parsedBone.length;
  91958. }
  91959. if (parsedBone.metadata) {
  91960. bone.metadata = parsedBone.metadata;
  91961. }
  91962. if (parsedBone.animation) {
  91963. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  91964. }
  91965. }
  91966. // placed after bones, so createAnimationRange can cascade down
  91967. if (parsedSkeleton.ranges) {
  91968. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  91969. var data = parsedSkeleton.ranges[index];
  91970. skeleton.createAnimationRange(data.name, data.from, data.to);
  91971. }
  91972. }
  91973. return skeleton;
  91974. };
  91975. /**
  91976. * Compute all node absolute transforms
  91977. * @param forceUpdate defines if computation must be done even if cache is up to date
  91978. */
  91979. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  91980. if (forceUpdate === void 0) { forceUpdate = false; }
  91981. var renderId = this._scene.getRenderId();
  91982. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  91983. this.bones[0].computeAbsoluteTransforms();
  91984. this._lastAbsoluteTransformsUpdateId = renderId;
  91985. }
  91986. };
  91987. /**
  91988. * Gets the root pose matrix
  91989. * @returns a matrix
  91990. */
  91991. Skeleton.prototype.getPoseMatrix = function () {
  91992. var poseMatrix = null;
  91993. if (this._meshesWithPoseMatrix.length > 0) {
  91994. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  91995. }
  91996. return poseMatrix;
  91997. };
  91998. /**
  91999. * Sorts bones per internal index
  92000. */
  92001. Skeleton.prototype.sortBones = function () {
  92002. var bones = new Array();
  92003. var visited = new Array(this.bones.length);
  92004. for (var index = 0; index < this.bones.length; index++) {
  92005. this._sortBones(index, bones, visited);
  92006. }
  92007. this.bones = bones;
  92008. };
  92009. Skeleton.prototype._sortBones = function (index, bones, visited) {
  92010. if (visited[index]) {
  92011. return;
  92012. }
  92013. visited[index] = true;
  92014. var bone = this.bones[index];
  92015. if (bone._index === undefined) {
  92016. bone._index = index;
  92017. }
  92018. var parentBone = bone.getParent();
  92019. if (parentBone) {
  92020. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92021. }
  92022. bones.push(bone);
  92023. };
  92024. return Skeleton;
  92025. }());
  92026. BABYLON.Skeleton = Skeleton;
  92027. })(BABYLON || (BABYLON = {}));
  92028. //# sourceMappingURL=babylon.skeleton.js.map
  92029. var BABYLON;
  92030. (function (BABYLON) {
  92031. ;
  92032. /**
  92033. * This groups tools to convert HDR texture to native colors array.
  92034. */
  92035. var HDRTools = /** @class */ (function () {
  92036. function HDRTools() {
  92037. }
  92038. HDRTools.Ldexp = function (mantissa, exponent) {
  92039. if (exponent > 1023) {
  92040. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92041. }
  92042. if (exponent < -1074) {
  92043. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92044. }
  92045. return mantissa * Math.pow(2, exponent);
  92046. };
  92047. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92048. if (exponent > 0) { /*nonzero pixel*/
  92049. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92050. float32array[index + 0] = red * exponent;
  92051. float32array[index + 1] = green * exponent;
  92052. float32array[index + 2] = blue * exponent;
  92053. }
  92054. else {
  92055. float32array[index + 0] = 0;
  92056. float32array[index + 1] = 0;
  92057. float32array[index + 2] = 0;
  92058. }
  92059. };
  92060. HDRTools.readStringLine = function (uint8array, startIndex) {
  92061. var line = "";
  92062. var character = "";
  92063. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92064. character = String.fromCharCode(uint8array[i]);
  92065. if (character == "\n") {
  92066. break;
  92067. }
  92068. line += character;
  92069. }
  92070. return line;
  92071. };
  92072. /**
  92073. * Reads header information from an RGBE texture stored in a native array.
  92074. * More information on this format are available here:
  92075. * https://en.wikipedia.org/wiki/RGBE_image_format
  92076. *
  92077. * @param uint8array The binary file stored in native array.
  92078. * @return The header information.
  92079. */
  92080. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92081. var height = 0;
  92082. var width = 0;
  92083. var line = this.readStringLine(uint8array, 0);
  92084. if (line[0] != '#' || line[1] != '?') {
  92085. throw "Bad HDR Format.";
  92086. }
  92087. var endOfHeader = false;
  92088. var findFormat = false;
  92089. var lineIndex = 0;
  92090. do {
  92091. lineIndex += (line.length + 1);
  92092. line = this.readStringLine(uint8array, lineIndex);
  92093. if (line == "FORMAT=32-bit_rle_rgbe") {
  92094. findFormat = true;
  92095. }
  92096. else if (line.length == 0) {
  92097. endOfHeader = true;
  92098. }
  92099. } while (!endOfHeader);
  92100. if (!findFormat) {
  92101. throw "HDR Bad header format, unsupported FORMAT";
  92102. }
  92103. lineIndex += (line.length + 1);
  92104. line = this.readStringLine(uint8array, lineIndex);
  92105. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92106. var match = sizeRegexp.exec(line);
  92107. // TODO. Support +Y and -X if needed.
  92108. if (!match || match.length < 3) {
  92109. throw "HDR Bad header format, no size";
  92110. }
  92111. width = parseInt(match[2]);
  92112. height = parseInt(match[1]);
  92113. if (width < 8 || width > 0x7fff) {
  92114. throw "HDR Bad header format, unsupported size";
  92115. }
  92116. lineIndex += (line.length + 1);
  92117. return {
  92118. height: height,
  92119. width: width,
  92120. dataPosition: lineIndex
  92121. };
  92122. };
  92123. /**
  92124. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92125. * This RGBE texture needs to store the information as a panorama.
  92126. *
  92127. * More information on this format are available here:
  92128. * https://en.wikipedia.org/wiki/RGBE_image_format
  92129. *
  92130. * @param buffer The binary file stored in an array buffer.
  92131. * @param size The expected size of the extracted cubemap.
  92132. * @return The Cube Map information.
  92133. */
  92134. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92135. var uint8array = new Uint8Array(buffer);
  92136. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92137. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92138. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92139. return cubeMapData;
  92140. };
  92141. /**
  92142. * Returns the pixels data extracted from an RGBE texture.
  92143. * This pixels will be stored left to right up to down in the R G B order in one array.
  92144. *
  92145. * More information on this format are available here:
  92146. * https://en.wikipedia.org/wiki/RGBE_image_format
  92147. *
  92148. * @param uint8array The binary file stored in an array buffer.
  92149. * @param hdrInfo The header information of the file.
  92150. * @return The pixels data in RGB right to left up to down order.
  92151. */
  92152. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92153. // Keep for multi format supports.
  92154. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92155. };
  92156. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92157. var num_scanlines = hdrInfo.height;
  92158. var scanline_width = hdrInfo.width;
  92159. var a, b, c, d, count;
  92160. var dataIndex = hdrInfo.dataPosition;
  92161. var index = 0, endIndex = 0, i = 0;
  92162. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92163. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92164. // 3 channels of 4 bytes per pixel in float.
  92165. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92166. var resultArray = new Float32Array(resultBuffer);
  92167. // read in each successive scanline
  92168. while (num_scanlines > 0) {
  92169. a = uint8array[dataIndex++];
  92170. b = uint8array[dataIndex++];
  92171. c = uint8array[dataIndex++];
  92172. d = uint8array[dataIndex++];
  92173. if (a != 2 || b != 2 || (c & 0x80)) {
  92174. // this file is not run length encoded
  92175. throw "HDR Bad header format, not RLE";
  92176. }
  92177. if (((c << 8) | d) != scanline_width) {
  92178. throw "HDR Bad header format, wrong scan line width";
  92179. }
  92180. index = 0;
  92181. // read each of the four channels for the scanline into the buffer
  92182. for (i = 0; i < 4; i++) {
  92183. endIndex = (i + 1) * scanline_width;
  92184. while (index < endIndex) {
  92185. a = uint8array[dataIndex++];
  92186. b = uint8array[dataIndex++];
  92187. if (a > 128) {
  92188. // a run of the same value
  92189. count = a - 128;
  92190. if ((count == 0) || (count > endIndex - index)) {
  92191. throw "HDR Bad Format, bad scanline data (run)";
  92192. }
  92193. while (count-- > 0) {
  92194. scanLineArray[index++] = b;
  92195. }
  92196. }
  92197. else {
  92198. // a non-run
  92199. count = a;
  92200. if ((count == 0) || (count > endIndex - index)) {
  92201. throw "HDR Bad Format, bad scanline data (non-run)";
  92202. }
  92203. scanLineArray[index++] = b;
  92204. if (--count > 0) {
  92205. for (var j = 0; j < count; j++) {
  92206. scanLineArray[index++] = uint8array[dataIndex++];
  92207. }
  92208. }
  92209. }
  92210. }
  92211. }
  92212. // now convert data from buffer into floats
  92213. for (i = 0; i < scanline_width; i++) {
  92214. a = scanLineArray[i];
  92215. b = scanLineArray[i + scanline_width];
  92216. c = scanLineArray[i + 2 * scanline_width];
  92217. d = scanLineArray[i + 3 * scanline_width];
  92218. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92219. }
  92220. num_scanlines--;
  92221. }
  92222. return resultArray;
  92223. };
  92224. return HDRTools;
  92225. }());
  92226. BABYLON.HDRTools = HDRTools;
  92227. })(BABYLON || (BABYLON = {}));
  92228. //# sourceMappingURL=babylon.hdr.js.map
  92229. var BABYLON;
  92230. (function (BABYLON) {
  92231. /**
  92232. * This represents a texture coming from an HDR input.
  92233. *
  92234. * The only supported format is currently panorama picture stored in RGBE format.
  92235. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92236. */
  92237. var HDRCubeTexture = /** @class */ (function (_super) {
  92238. __extends(HDRCubeTexture, _super);
  92239. /**
  92240. * Instantiates an HDRTexture from the following parameters.
  92241. *
  92242. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92243. * @param scene The scene the texture will be used in
  92244. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92245. * @param noMipmap Forces to not generate the mipmap if true
  92246. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92247. * @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)
  92248. * @param reserved Reserved flag for internal use.
  92249. */
  92250. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92251. if (noMipmap === void 0) { noMipmap = false; }
  92252. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92253. if (gammaSpace === void 0) { gammaSpace = false; }
  92254. if (reserved === void 0) { reserved = false; }
  92255. if (onLoad === void 0) { onLoad = null; }
  92256. if (onError === void 0) { onError = null; }
  92257. var _this = _super.call(this, scene) || this;
  92258. _this._generateHarmonics = true;
  92259. _this._onLoad = null;
  92260. _this._onError = null;
  92261. /**
  92262. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92263. */
  92264. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92265. _this._isBlocking = true;
  92266. _this._rotationY = 0;
  92267. /**
  92268. * Gets or sets the center of the bounding box associated with the cube texture
  92269. * It must define where the camera used to render the texture was set
  92270. */
  92271. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92272. if (!url) {
  92273. return _this;
  92274. }
  92275. _this.name = url;
  92276. _this.url = url;
  92277. _this.hasAlpha = false;
  92278. _this.isCube = true;
  92279. _this._textureMatrix = BABYLON.Matrix.Identity();
  92280. _this._onLoad = onLoad;
  92281. _this._onError = onError;
  92282. _this.gammaSpace = gammaSpace;
  92283. _this._noMipmap = noMipmap;
  92284. _this._size = size;
  92285. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92286. if (!_this._texture) {
  92287. if (!scene.useDelayedTextureLoading) {
  92288. _this.loadTexture();
  92289. }
  92290. else {
  92291. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92292. }
  92293. }
  92294. return _this;
  92295. }
  92296. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92297. /**
  92298. * Gets wether or not the texture is blocking during loading.
  92299. */
  92300. get: function () {
  92301. return this._isBlocking;
  92302. },
  92303. /**
  92304. * Sets wether or not the texture is blocking during loading.
  92305. */
  92306. set: function (value) {
  92307. this._isBlocking = value;
  92308. },
  92309. enumerable: true,
  92310. configurable: true
  92311. });
  92312. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92313. /**
  92314. * Gets texture matrix rotation angle around Y axis radians.
  92315. */
  92316. get: function () {
  92317. return this._rotationY;
  92318. },
  92319. /**
  92320. * Sets texture matrix rotation angle around Y axis in radians.
  92321. */
  92322. set: function (value) {
  92323. this._rotationY = value;
  92324. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92325. },
  92326. enumerable: true,
  92327. configurable: true
  92328. });
  92329. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92330. get: function () {
  92331. return this._boundingBoxSize;
  92332. },
  92333. /**
  92334. * Gets or sets the size of the bounding box associated with the cube texture
  92335. * When defined, the cubemap will switch to local mode
  92336. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92337. * @example https://www.babylonjs-playground.com/#RNASML
  92338. */
  92339. set: function (value) {
  92340. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92341. return;
  92342. }
  92343. this._boundingBoxSize = value;
  92344. var scene = this.getScene();
  92345. if (scene) {
  92346. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92347. }
  92348. },
  92349. enumerable: true,
  92350. configurable: true
  92351. });
  92352. /**
  92353. * Occurs when the file is raw .hdr file.
  92354. */
  92355. HDRCubeTexture.prototype.loadTexture = function () {
  92356. var _this = this;
  92357. var callback = function (buffer) {
  92358. _this.lodGenerationOffset = 0.0;
  92359. _this.lodGenerationScale = 0.8;
  92360. var scene = _this.getScene();
  92361. if (!scene) {
  92362. return null;
  92363. }
  92364. // Extract the raw linear data.
  92365. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92366. // Generate harmonics if needed.
  92367. if (_this._generateHarmonics) {
  92368. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92369. _this.sphericalPolynomial = sphericalPolynomial;
  92370. }
  92371. var results = [];
  92372. var byteArray = null;
  92373. // Push each faces.
  92374. for (var j = 0; j < 6; j++) {
  92375. // Create uintarray fallback.
  92376. if (!scene.getEngine().getCaps().textureFloat) {
  92377. // 3 channels of 1 bytes per pixel in bytes.
  92378. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92379. byteArray = new Uint8Array(byteBuffer);
  92380. }
  92381. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92382. // If special cases.
  92383. if (_this.gammaSpace || byteArray) {
  92384. for (var i = 0; i < _this._size * _this._size; i++) {
  92385. // Put in gamma space if requested.
  92386. if (_this.gammaSpace) {
  92387. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92388. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92389. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92390. }
  92391. // Convert to int texture for fallback.
  92392. if (byteArray) {
  92393. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92394. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92395. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92396. // May use luminance instead if the result is not accurate.
  92397. var max = Math.max(Math.max(r, g), b);
  92398. if (max > 255) {
  92399. var scale = 255 / max;
  92400. r *= scale;
  92401. g *= scale;
  92402. b *= scale;
  92403. }
  92404. byteArray[(i * 3) + 0] = r;
  92405. byteArray[(i * 3) + 1] = g;
  92406. byteArray[(i * 3) + 2] = b;
  92407. }
  92408. }
  92409. }
  92410. if (byteArray) {
  92411. results.push(byteArray);
  92412. }
  92413. else {
  92414. results.push(dataFace);
  92415. }
  92416. }
  92417. return results;
  92418. };
  92419. var scene = this.getScene();
  92420. if (scene) {
  92421. 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);
  92422. }
  92423. };
  92424. HDRCubeTexture.prototype.clone = function () {
  92425. var scene = this.getScene();
  92426. if (!scene) {
  92427. return this;
  92428. }
  92429. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92430. // Base texture
  92431. newTexture.level = this.level;
  92432. newTexture.wrapU = this.wrapU;
  92433. newTexture.wrapV = this.wrapV;
  92434. newTexture.coordinatesIndex = this.coordinatesIndex;
  92435. newTexture.coordinatesMode = this.coordinatesMode;
  92436. return newTexture;
  92437. };
  92438. // Methods
  92439. HDRCubeTexture.prototype.delayLoad = function () {
  92440. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92441. return;
  92442. }
  92443. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92444. this._texture = this._getFromCache(this.url, this._noMipmap);
  92445. if (!this._texture) {
  92446. this.loadTexture();
  92447. }
  92448. };
  92449. /**
  92450. * Get the texture reflection matrix used to rotate/transform the reflection.
  92451. * @returns the reflection matrix
  92452. */
  92453. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92454. return this._textureMatrix;
  92455. };
  92456. /**
  92457. * Set the texture reflection matrix used to rotate/transform the reflection.
  92458. * @param value Define the reflection matrix to set
  92459. */
  92460. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92461. this._textureMatrix = value;
  92462. };
  92463. /**
  92464. * Parses a JSON representation of an HDR Texture in order to create the texture
  92465. * @param parsedTexture Define the JSON representation
  92466. * @param scene Define the scene the texture should be created in
  92467. * @param rootUrl Define the root url in case we need to load relative dependencies
  92468. * @returns the newly created texture after parsing
  92469. */
  92470. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92471. var texture = null;
  92472. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92473. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92474. texture.name = parsedTexture.name;
  92475. texture.hasAlpha = parsedTexture.hasAlpha;
  92476. texture.level = parsedTexture.level;
  92477. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92478. texture.isBlocking = parsedTexture.isBlocking;
  92479. }
  92480. if (texture) {
  92481. if (parsedTexture.boundingBoxPosition) {
  92482. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92483. }
  92484. if (parsedTexture.boundingBoxSize) {
  92485. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92486. }
  92487. if (parsedTexture.rotationY) {
  92488. texture.rotationY = parsedTexture.rotationY;
  92489. }
  92490. }
  92491. return texture;
  92492. };
  92493. HDRCubeTexture.prototype.serialize = function () {
  92494. if (!this.name) {
  92495. return null;
  92496. }
  92497. var serializationObject = {};
  92498. serializationObject.name = this.name;
  92499. serializationObject.hasAlpha = this.hasAlpha;
  92500. serializationObject.isCube = true;
  92501. serializationObject.level = this.level;
  92502. serializationObject.size = this._size;
  92503. serializationObject.coordinatesMode = this.coordinatesMode;
  92504. serializationObject.useInGammaSpace = this.gammaSpace;
  92505. serializationObject.generateHarmonics = this._generateHarmonics;
  92506. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92507. serializationObject.noMipmap = this._noMipmap;
  92508. serializationObject.isBlocking = this._isBlocking;
  92509. serializationObject.rotationY = this._rotationY;
  92510. return serializationObject;
  92511. };
  92512. HDRCubeTexture._facesMapping = [
  92513. "right",
  92514. "left",
  92515. "up",
  92516. "down",
  92517. "front",
  92518. "back"
  92519. ];
  92520. return HDRCubeTexture;
  92521. }(BABYLON.BaseTexture));
  92522. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92523. })(BABYLON || (BABYLON = {}));
  92524. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92525. var BABYLON;
  92526. (function (BABYLON) {
  92527. /**
  92528. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92529. */
  92530. var PanoramaToCubeMapTools = /** @class */ (function () {
  92531. function PanoramaToCubeMapTools() {
  92532. }
  92533. /**
  92534. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92535. *
  92536. * @param float32Array The source data.
  92537. * @param inputWidth The width of the input panorama.
  92538. * @param inputHeight The height of the input panorama.
  92539. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92540. * @return The cubemap data
  92541. */
  92542. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92543. if (!float32Array) {
  92544. throw "ConvertPanoramaToCubemap: input cannot be null";
  92545. }
  92546. if (float32Array.length != inputWidth * inputHeight * 3) {
  92547. throw "ConvertPanoramaToCubemap: input size is wrong";
  92548. }
  92549. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92550. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92551. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92552. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92553. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92554. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92555. return {
  92556. front: textureFront,
  92557. back: textureBack,
  92558. left: textureLeft,
  92559. right: textureRight,
  92560. up: textureUp,
  92561. down: textureDown,
  92562. size: size,
  92563. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92564. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92565. gammaSpace: false,
  92566. };
  92567. };
  92568. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92569. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92570. var textureArray = new Float32Array(buffer);
  92571. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92572. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92573. var dy = 1 / texSize;
  92574. var fy = 0;
  92575. for (var y = 0; y < texSize; y++) {
  92576. var xv1 = faceData[0];
  92577. var xv2 = faceData[2];
  92578. for (var x = 0; x < texSize; x++) {
  92579. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92580. v.normalize();
  92581. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92582. // 3 channels per pixels
  92583. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92584. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92585. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92586. xv1 = xv1.add(rotDX1);
  92587. xv2 = xv2.add(rotDX2);
  92588. }
  92589. fy += dy;
  92590. }
  92591. return textureArray;
  92592. };
  92593. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92594. var theta = Math.atan2(vDir.z, vDir.x);
  92595. var phi = Math.acos(vDir.y);
  92596. while (theta < -Math.PI)
  92597. theta += 2 * Math.PI;
  92598. while (theta > Math.PI)
  92599. theta -= 2 * Math.PI;
  92600. var dx = theta / Math.PI;
  92601. var dy = phi / Math.PI;
  92602. // recenter.
  92603. dx = dx * 0.5 + 0.5;
  92604. var px = Math.round(dx * inputWidth);
  92605. if (px < 0)
  92606. px = 0;
  92607. else if (px >= inputWidth)
  92608. px = inputWidth - 1;
  92609. var py = Math.round(dy * inputHeight);
  92610. if (py < 0)
  92611. py = 0;
  92612. else if (py >= inputHeight)
  92613. py = inputHeight - 1;
  92614. var inputY = (inputHeight - py - 1);
  92615. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92616. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92617. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92618. return {
  92619. r: r,
  92620. g: g,
  92621. b: b
  92622. };
  92623. };
  92624. PanoramaToCubeMapTools.FACE_FRONT = [
  92625. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92626. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92627. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92628. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92629. ];
  92630. PanoramaToCubeMapTools.FACE_BACK = [
  92631. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92632. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92633. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92634. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92635. ];
  92636. PanoramaToCubeMapTools.FACE_RIGHT = [
  92637. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92638. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92639. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92640. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92641. ];
  92642. PanoramaToCubeMapTools.FACE_LEFT = [
  92643. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92644. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92645. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92646. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92647. ];
  92648. PanoramaToCubeMapTools.FACE_DOWN = [
  92649. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92650. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92651. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92652. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92653. ];
  92654. PanoramaToCubeMapTools.FACE_UP = [
  92655. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92656. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92657. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92658. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92659. ];
  92660. return PanoramaToCubeMapTools;
  92661. }());
  92662. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92663. })(BABYLON || (BABYLON = {}));
  92664. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92665. var BABYLON;
  92666. (function (BABYLON) {
  92667. /**
  92668. * Vector2 wth index property
  92669. */
  92670. var IndexedVector2 = /** @class */ (function (_super) {
  92671. __extends(IndexedVector2, _super);
  92672. function IndexedVector2(original,
  92673. /** Index of the vector2 */
  92674. index) {
  92675. var _this = _super.call(this, original.x, original.y) || this;
  92676. _this.index = index;
  92677. return _this;
  92678. }
  92679. return IndexedVector2;
  92680. }(BABYLON.Vector2));
  92681. /**
  92682. * Defines points to create a polygon
  92683. */
  92684. var PolygonPoints = /** @class */ (function () {
  92685. function PolygonPoints() {
  92686. this.elements = new Array();
  92687. }
  92688. PolygonPoints.prototype.add = function (originalPoints) {
  92689. var _this = this;
  92690. var result = new Array();
  92691. originalPoints.forEach(function (point) {
  92692. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  92693. var newPoint = new IndexedVector2(point, _this.elements.length);
  92694. result.push(newPoint);
  92695. _this.elements.push(newPoint);
  92696. }
  92697. });
  92698. return result;
  92699. };
  92700. PolygonPoints.prototype.computeBounds = function () {
  92701. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92702. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92703. this.elements.forEach(function (point) {
  92704. // x
  92705. if (point.x < lmin.x) {
  92706. lmin.x = point.x;
  92707. }
  92708. else if (point.x > lmax.x) {
  92709. lmax.x = point.x;
  92710. }
  92711. // y
  92712. if (point.y < lmin.y) {
  92713. lmin.y = point.y;
  92714. }
  92715. else if (point.y > lmax.y) {
  92716. lmax.y = point.y;
  92717. }
  92718. });
  92719. return {
  92720. min: lmin,
  92721. max: lmax,
  92722. width: lmax.x - lmin.x,
  92723. height: lmax.y - lmin.y
  92724. };
  92725. };
  92726. return PolygonPoints;
  92727. }());
  92728. /**
  92729. * Polygon
  92730. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  92731. */
  92732. var Polygon = /** @class */ (function () {
  92733. function Polygon() {
  92734. }
  92735. /**
  92736. * Creates a rectangle
  92737. * @param xmin bottom X coord
  92738. * @param ymin bottom Y coord
  92739. * @param xmax top X coord
  92740. * @param ymax top Y coord
  92741. * @returns points that make the resulting rectation
  92742. */
  92743. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  92744. return [
  92745. new BABYLON.Vector2(xmin, ymin),
  92746. new BABYLON.Vector2(xmax, ymin),
  92747. new BABYLON.Vector2(xmax, ymax),
  92748. new BABYLON.Vector2(xmin, ymax)
  92749. ];
  92750. };
  92751. /**
  92752. * Creates a circle
  92753. * @param radius radius of circle
  92754. * @param cx scale in x
  92755. * @param cy scale in y
  92756. * @param numberOfSides number of sides that make up the circle
  92757. * @returns points that make the resulting circle
  92758. */
  92759. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  92760. if (cx === void 0) { cx = 0; }
  92761. if (cy === void 0) { cy = 0; }
  92762. if (numberOfSides === void 0) { numberOfSides = 32; }
  92763. var result = new Array();
  92764. var angle = 0;
  92765. var increment = (Math.PI * 2) / numberOfSides;
  92766. for (var i = 0; i < numberOfSides; i++) {
  92767. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  92768. angle -= increment;
  92769. }
  92770. return result;
  92771. };
  92772. /**
  92773. * Creates a polygon from input string
  92774. * @param input Input polygon data
  92775. * @returns the parsed points
  92776. */
  92777. Polygon.Parse = function (input) {
  92778. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  92779. var i, result = [];
  92780. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  92781. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  92782. }
  92783. return result;
  92784. };
  92785. /**
  92786. * Starts building a polygon from x and y coordinates
  92787. * @param x x coordinate
  92788. * @param y y coordinate
  92789. * @returns the started path2
  92790. */
  92791. Polygon.StartingAt = function (x, y) {
  92792. return BABYLON.Path2.StartingAt(x, y);
  92793. };
  92794. return Polygon;
  92795. }());
  92796. BABYLON.Polygon = Polygon;
  92797. /**
  92798. * Builds a polygon
  92799. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  92800. */
  92801. var PolygonMeshBuilder = /** @class */ (function () {
  92802. /**
  92803. * Creates a PolygonMeshBuilder
  92804. * @param name name of the builder
  92805. * @param contours Path of the polygon
  92806. * @param scene scene to add to
  92807. */
  92808. function PolygonMeshBuilder(name, contours, scene) {
  92809. this._points = new PolygonPoints();
  92810. this._outlinepoints = new PolygonPoints();
  92811. this._holes = new Array();
  92812. this._epoints = new Array();
  92813. this._eholes = new Array();
  92814. this._name = name;
  92815. this._scene = scene;
  92816. var points;
  92817. if (contours instanceof BABYLON.Path2) {
  92818. points = contours.getPoints();
  92819. }
  92820. else {
  92821. points = contours;
  92822. }
  92823. this._addToepoint(points);
  92824. this._points.add(points);
  92825. this._outlinepoints.add(points);
  92826. if (typeof earcut === 'undefined') {
  92827. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  92828. }
  92829. }
  92830. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  92831. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  92832. var p = points_1[_i];
  92833. this._epoints.push(p.x, p.y);
  92834. }
  92835. };
  92836. /**
  92837. * Adds a whole within the polygon
  92838. * @param hole Array of points defining the hole
  92839. * @returns this
  92840. */
  92841. PolygonMeshBuilder.prototype.addHole = function (hole) {
  92842. this._points.add(hole);
  92843. var holepoints = new PolygonPoints();
  92844. holepoints.add(hole);
  92845. this._holes.push(holepoints);
  92846. this._eholes.push(this._epoints.length / 2);
  92847. this._addToepoint(hole);
  92848. return this;
  92849. };
  92850. /**
  92851. * Creates the polygon
  92852. * @param updatable If the mesh should be updatable
  92853. * @param depth The depth of the mesh created
  92854. * @returns the created mesh
  92855. */
  92856. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  92857. var _this = this;
  92858. if (updatable === void 0) { updatable = false; }
  92859. if (depth === void 0) { depth = 0; }
  92860. var result = new BABYLON.Mesh(this._name, this._scene);
  92861. var normals = new Array();
  92862. var positions = new Array();
  92863. var uvs = new Array();
  92864. var bounds = this._points.computeBounds();
  92865. this._points.elements.forEach(function (p) {
  92866. normals.push(0, 1.0, 0);
  92867. positions.push(p.x, 0, p.y);
  92868. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  92869. });
  92870. var indices = new Array();
  92871. var res = earcut(this._epoints, this._eholes, 2);
  92872. for (var i = 0; i < res.length; i++) {
  92873. indices.push(res[i]);
  92874. }
  92875. if (depth > 0) {
  92876. var positionscount = (positions.length / 3); //get the current pointcount
  92877. this._points.elements.forEach(function (p) {
  92878. normals.push(0, -1.0, 0);
  92879. positions.push(p.x, -depth, p.y);
  92880. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  92881. });
  92882. var totalCount = indices.length;
  92883. for (var i = 0; i < totalCount; i += 3) {
  92884. var i0 = indices[i + 0];
  92885. var i1 = indices[i + 1];
  92886. var i2 = indices[i + 2];
  92887. indices.push(i2 + positionscount);
  92888. indices.push(i1 + positionscount);
  92889. indices.push(i0 + positionscount);
  92890. }
  92891. //Add the sides
  92892. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  92893. this._holes.forEach(function (hole) {
  92894. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  92895. });
  92896. }
  92897. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  92898. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  92899. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  92900. result.setIndices(indices);
  92901. return result;
  92902. };
  92903. /**
  92904. * Adds a side to the polygon
  92905. * @param positions points that make the polygon
  92906. * @param normals normals of the polygon
  92907. * @param uvs uvs of the polygon
  92908. * @param indices indices of the polygon
  92909. * @param bounds bounds of the polygon
  92910. * @param points points of the polygon
  92911. * @param depth depth of the polygon
  92912. * @param flip flip of the polygon
  92913. */
  92914. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  92915. var StartIndex = positions.length / 3;
  92916. var ulength = 0;
  92917. for (var i = 0; i < points.elements.length; i++) {
  92918. var p = points.elements[i];
  92919. var p1;
  92920. if ((i + 1) > points.elements.length - 1) {
  92921. p1 = points.elements[0];
  92922. }
  92923. else {
  92924. p1 = points.elements[i + 1];
  92925. }
  92926. positions.push(p.x, 0, p.y);
  92927. positions.push(p.x, -depth, p.y);
  92928. positions.push(p1.x, 0, p1.y);
  92929. positions.push(p1.x, -depth, p1.y);
  92930. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  92931. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  92932. var v3 = v2.subtract(v1);
  92933. var v4 = new BABYLON.Vector3(0, 1, 0);
  92934. var vn = BABYLON.Vector3.Cross(v3, v4);
  92935. vn = vn.normalize();
  92936. uvs.push(ulength / bounds.width, 0);
  92937. uvs.push(ulength / bounds.width, 1);
  92938. ulength += v3.length();
  92939. uvs.push((ulength / bounds.width), 0);
  92940. uvs.push((ulength / bounds.width), 1);
  92941. if (!flip) {
  92942. normals.push(-vn.x, -vn.y, -vn.z);
  92943. normals.push(-vn.x, -vn.y, -vn.z);
  92944. normals.push(-vn.x, -vn.y, -vn.z);
  92945. normals.push(-vn.x, -vn.y, -vn.z);
  92946. indices.push(StartIndex);
  92947. indices.push(StartIndex + 1);
  92948. indices.push(StartIndex + 2);
  92949. indices.push(StartIndex + 1);
  92950. indices.push(StartIndex + 3);
  92951. indices.push(StartIndex + 2);
  92952. }
  92953. else {
  92954. normals.push(vn.x, vn.y, vn.z);
  92955. normals.push(vn.x, vn.y, vn.z);
  92956. normals.push(vn.x, vn.y, vn.z);
  92957. normals.push(vn.x, vn.y, vn.z);
  92958. indices.push(StartIndex);
  92959. indices.push(StartIndex + 2);
  92960. indices.push(StartIndex + 1);
  92961. indices.push(StartIndex + 1);
  92962. indices.push(StartIndex + 2);
  92963. indices.push(StartIndex + 3);
  92964. }
  92965. StartIndex += 4;
  92966. }
  92967. ;
  92968. };
  92969. return PolygonMeshBuilder;
  92970. }());
  92971. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  92972. })(BABYLON || (BABYLON = {}));
  92973. //# sourceMappingURL=babylon.polygonMesh.js.map
  92974. var BABYLON;
  92975. (function (BABYLON) {
  92976. /**
  92977. * Unique ID when we import meshes from Babylon to CSG
  92978. */
  92979. var currentCSGMeshId = 0;
  92980. /**
  92981. * Represents a vertex of a polygon. Use your own vertex class instead of this
  92982. * one to provide additional features like texture coordinates and vertex
  92983. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  92984. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  92985. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  92986. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  92987. * is not used anywhere else.
  92988. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  92989. */
  92990. var Vertex = /** @class */ (function () {
  92991. /**
  92992. * Initializes the vertex
  92993. * @param pos The position of the vertex
  92994. * @param normal The normal of the vertex
  92995. * @param uv The texture coordinate of the vertex
  92996. */
  92997. function Vertex(
  92998. /**
  92999. * The position of the vertex
  93000. */
  93001. pos,
  93002. /**
  93003. * The normal of the vertex
  93004. */
  93005. normal,
  93006. /**
  93007. * The texture coordinate of the vertex
  93008. */
  93009. uv) {
  93010. this.pos = pos;
  93011. this.normal = normal;
  93012. this.uv = uv;
  93013. }
  93014. /**
  93015. * Make a clone, or deep copy, of the vertex
  93016. * @returns A new Vertex
  93017. */
  93018. Vertex.prototype.clone = function () {
  93019. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93020. };
  93021. /**
  93022. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93023. * orientation of a polygon is flipped.
  93024. */
  93025. Vertex.prototype.flip = function () {
  93026. this.normal = this.normal.scale(-1);
  93027. };
  93028. /**
  93029. * Create a new vertex between this vertex and `other` by linearly
  93030. * interpolating all properties using a parameter of `t`. Subclasses should
  93031. * override this to interpolate additional properties.
  93032. * @param other the vertex to interpolate against
  93033. * @param t The factor used to linearly interpolate between the vertices
  93034. */
  93035. Vertex.prototype.interpolate = function (other, t) {
  93036. 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));
  93037. };
  93038. return Vertex;
  93039. }());
  93040. /**
  93041. * Represents a plane in 3D space.
  93042. */
  93043. var Plane = /** @class */ (function () {
  93044. /**
  93045. * Initializes the plane
  93046. * @param normal The normal for the plane
  93047. * @param w
  93048. */
  93049. function Plane(normal, w) {
  93050. this.normal = normal;
  93051. this.w = w;
  93052. }
  93053. /**
  93054. * Construct a plane from three points
  93055. * @param a Point a
  93056. * @param b Point b
  93057. * @param c Point c
  93058. */
  93059. Plane.FromPoints = function (a, b, c) {
  93060. var v0 = c.subtract(a);
  93061. var v1 = b.subtract(a);
  93062. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93063. return null;
  93064. }
  93065. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93066. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93067. };
  93068. /**
  93069. * Clone, or make a deep copy of the plane
  93070. * @returns a new Plane
  93071. */
  93072. Plane.prototype.clone = function () {
  93073. return new Plane(this.normal.clone(), this.w);
  93074. };
  93075. /**
  93076. * Flip the face of the plane
  93077. */
  93078. Plane.prototype.flip = function () {
  93079. this.normal.scaleInPlace(-1);
  93080. this.w = -this.w;
  93081. };
  93082. /**
  93083. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93084. * fragments in the appropriate lists. Coplanar polygons go into either
  93085. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93086. * respect to this plane. Polygons in front or in back of this plane go into
  93087. * either `front` or `back`
  93088. * @param polygon The polygon to be split
  93089. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93090. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93091. * @param front Will contain the polygons in front of the plane
  93092. * @param back Will contain the polygons begind the plane
  93093. */
  93094. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93095. var COPLANAR = 0;
  93096. var FRONT = 1;
  93097. var BACK = 2;
  93098. var SPANNING = 3;
  93099. // Classify each point as well as the entire polygon into one of the above
  93100. // four classes.
  93101. var polygonType = 0;
  93102. var types = [];
  93103. var i;
  93104. var t;
  93105. for (i = 0; i < polygon.vertices.length; i++) {
  93106. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93107. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93108. polygonType |= type;
  93109. types.push(type);
  93110. }
  93111. // Put the polygon in the correct list, splitting it when necessary
  93112. switch (polygonType) {
  93113. case COPLANAR:
  93114. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93115. break;
  93116. case FRONT:
  93117. front.push(polygon);
  93118. break;
  93119. case BACK:
  93120. back.push(polygon);
  93121. break;
  93122. case SPANNING:
  93123. var f = [], b = [];
  93124. for (i = 0; i < polygon.vertices.length; i++) {
  93125. var j = (i + 1) % polygon.vertices.length;
  93126. var ti = types[i], tj = types[j];
  93127. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93128. if (ti !== BACK)
  93129. f.push(vi);
  93130. if (ti !== FRONT)
  93131. b.push(ti !== BACK ? vi.clone() : vi);
  93132. if ((ti | tj) === SPANNING) {
  93133. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93134. var v = vi.interpolate(vj, t);
  93135. f.push(v);
  93136. b.push(v.clone());
  93137. }
  93138. }
  93139. var poly;
  93140. if (f.length >= 3) {
  93141. poly = new Polygon(f, polygon.shared);
  93142. if (poly.plane)
  93143. front.push(poly);
  93144. }
  93145. if (b.length >= 3) {
  93146. poly = new Polygon(b, polygon.shared);
  93147. if (poly.plane)
  93148. back.push(poly);
  93149. }
  93150. break;
  93151. }
  93152. };
  93153. /**
  93154. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93155. * point is on the plane
  93156. */
  93157. Plane.EPSILON = 1e-5;
  93158. return Plane;
  93159. }());
  93160. /**
  93161. * Represents a convex polygon. The vertices used to initialize a polygon must
  93162. * be coplanar and form a convex loop.
  93163. *
  93164. * Each convex polygon has a `shared` property, which is shared between all
  93165. * polygons that are clones of each other or were split from the same polygon.
  93166. * This can be used to define per-polygon properties (such as surface color)
  93167. */
  93168. var Polygon = /** @class */ (function () {
  93169. /**
  93170. * Initializes the polygon
  93171. * @param vertices The vertices of the polygon
  93172. * @param shared The properties shared across all polygons
  93173. */
  93174. function Polygon(vertices, shared) {
  93175. this.vertices = vertices;
  93176. this.shared = shared;
  93177. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93178. }
  93179. /**
  93180. * Clones, or makes a deep copy, or the polygon
  93181. */
  93182. Polygon.prototype.clone = function () {
  93183. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93184. return new Polygon(vertices, this.shared);
  93185. };
  93186. /**
  93187. * Flips the faces of the polygon
  93188. */
  93189. Polygon.prototype.flip = function () {
  93190. this.vertices.reverse().map(function (v) { v.flip(); });
  93191. this.plane.flip();
  93192. };
  93193. return Polygon;
  93194. }());
  93195. /**
  93196. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93197. * by picking a polygon to split along. That polygon (and all other coplanar
  93198. * polygons) are added directly to that node and the other polygons are added to
  93199. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93200. * no distinction between internal and leaf nodes
  93201. */
  93202. var Node = /** @class */ (function () {
  93203. /**
  93204. * Initializes the node
  93205. * @param polygons A collection of polygons held in the node
  93206. */
  93207. function Node(polygons) {
  93208. this.plane = null;
  93209. this.front = null;
  93210. this.back = null;
  93211. this.polygons = new Array();
  93212. if (polygons) {
  93213. this.build(polygons);
  93214. }
  93215. }
  93216. /**
  93217. * Clones, or makes a deep copy, of the node
  93218. * @returns The cloned node
  93219. */
  93220. Node.prototype.clone = function () {
  93221. var node = new Node();
  93222. node.plane = this.plane && this.plane.clone();
  93223. node.front = this.front && this.front.clone();
  93224. node.back = this.back && this.back.clone();
  93225. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93226. return node;
  93227. };
  93228. /**
  93229. * Convert solid space to empty space and empty space to solid space
  93230. */
  93231. Node.prototype.invert = function () {
  93232. for (var i = 0; i < this.polygons.length; i++) {
  93233. this.polygons[i].flip();
  93234. }
  93235. if (this.plane) {
  93236. this.plane.flip();
  93237. }
  93238. if (this.front) {
  93239. this.front.invert();
  93240. }
  93241. if (this.back) {
  93242. this.back.invert();
  93243. }
  93244. var temp = this.front;
  93245. this.front = this.back;
  93246. this.back = temp;
  93247. };
  93248. /**
  93249. * Recursively remove all polygons in `polygons` that are inside this BSP
  93250. * tree.
  93251. * @param polygons Polygons to remove from the BSP
  93252. * @returns Polygons clipped from the BSP
  93253. */
  93254. Node.prototype.clipPolygons = function (polygons) {
  93255. if (!this.plane)
  93256. return polygons.slice();
  93257. var front = new Array(), back = new Array();
  93258. for (var i = 0; i < polygons.length; i++) {
  93259. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93260. }
  93261. if (this.front) {
  93262. front = this.front.clipPolygons(front);
  93263. }
  93264. if (this.back) {
  93265. back = this.back.clipPolygons(back);
  93266. }
  93267. else {
  93268. back = [];
  93269. }
  93270. return front.concat(back);
  93271. };
  93272. /**
  93273. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93274. * `bsp`.
  93275. * @param bsp BSP containing polygons to remove from this BSP
  93276. */
  93277. Node.prototype.clipTo = function (bsp) {
  93278. this.polygons = bsp.clipPolygons(this.polygons);
  93279. if (this.front)
  93280. this.front.clipTo(bsp);
  93281. if (this.back)
  93282. this.back.clipTo(bsp);
  93283. };
  93284. /**
  93285. * Return a list of all polygons in this BSP tree
  93286. * @returns List of all polygons in this BSP tree
  93287. */
  93288. Node.prototype.allPolygons = function () {
  93289. var polygons = this.polygons.slice();
  93290. if (this.front)
  93291. polygons = polygons.concat(this.front.allPolygons());
  93292. if (this.back)
  93293. polygons = polygons.concat(this.back.allPolygons());
  93294. return polygons;
  93295. };
  93296. /**
  93297. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93298. * new polygons are filtered down to the bottom of the tree and become new
  93299. * nodes there. Each set of polygons is partitioned using the first polygon
  93300. * (no heuristic is used to pick a good split)
  93301. * @param polygons Polygons used to construct the BSP tree
  93302. */
  93303. Node.prototype.build = function (polygons) {
  93304. if (!polygons.length)
  93305. return;
  93306. if (!this.plane)
  93307. this.plane = polygons[0].plane.clone();
  93308. var front = new Array(), back = new Array();
  93309. for (var i = 0; i < polygons.length; i++) {
  93310. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93311. }
  93312. if (front.length) {
  93313. if (!this.front)
  93314. this.front = new Node();
  93315. this.front.build(front);
  93316. }
  93317. if (back.length) {
  93318. if (!this.back)
  93319. this.back = new Node();
  93320. this.back.build(back);
  93321. }
  93322. };
  93323. return Node;
  93324. }());
  93325. /**
  93326. * Class for building Constructive Solid Geometry
  93327. */
  93328. var CSG = /** @class */ (function () {
  93329. function CSG() {
  93330. this.polygons = new Array();
  93331. }
  93332. /**
  93333. * Convert the BABYLON.Mesh to BABYLON.CSG
  93334. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93335. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93336. */
  93337. CSG.FromMesh = function (mesh) {
  93338. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93339. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93340. if (mesh instanceof BABYLON.Mesh) {
  93341. mesh.computeWorldMatrix(true);
  93342. matrix = mesh.getWorldMatrix();
  93343. meshPosition = mesh.position.clone();
  93344. meshRotation = mesh.rotation.clone();
  93345. if (mesh.rotationQuaternion) {
  93346. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93347. }
  93348. meshScaling = mesh.scaling.clone();
  93349. }
  93350. else {
  93351. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93352. }
  93353. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93354. var subMeshes = mesh.subMeshes;
  93355. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93356. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93357. vertices = [];
  93358. for (var j = 0; j < 3; j++) {
  93359. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93360. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93361. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93362. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93363. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93364. vertex = new Vertex(position, normal, uv);
  93365. vertices.push(vertex);
  93366. }
  93367. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93368. // To handle the case of degenerated triangle
  93369. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93370. if (polygon.plane)
  93371. polygons.push(polygon);
  93372. }
  93373. }
  93374. var csg = CSG.FromPolygons(polygons);
  93375. csg.matrix = matrix;
  93376. csg.position = meshPosition;
  93377. csg.rotation = meshRotation;
  93378. csg.scaling = meshScaling;
  93379. csg.rotationQuaternion = meshRotationQuaternion;
  93380. currentCSGMeshId++;
  93381. return csg;
  93382. };
  93383. /**
  93384. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93385. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93386. */
  93387. CSG.FromPolygons = function (polygons) {
  93388. var csg = new CSG();
  93389. csg.polygons = polygons;
  93390. return csg;
  93391. };
  93392. /**
  93393. * Clones, or makes a deep copy, of the BABYLON.CSG
  93394. * @returns A new BABYLON.CSG
  93395. */
  93396. CSG.prototype.clone = function () {
  93397. var csg = new CSG();
  93398. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93399. csg.copyTransformAttributes(this);
  93400. return csg;
  93401. };
  93402. /**
  93403. * Unions this CSG with another CSG
  93404. * @param csg The CSG to union against this CSG
  93405. * @returns The unioned CSG
  93406. */
  93407. CSG.prototype.union = function (csg) {
  93408. var a = new Node(this.clone().polygons);
  93409. var b = new Node(csg.clone().polygons);
  93410. a.clipTo(b);
  93411. b.clipTo(a);
  93412. b.invert();
  93413. b.clipTo(a);
  93414. b.invert();
  93415. a.build(b.allPolygons());
  93416. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93417. };
  93418. /**
  93419. * Unions this CSG with another CSG in place
  93420. * @param csg The CSG to union against this CSG
  93421. */
  93422. CSG.prototype.unionInPlace = function (csg) {
  93423. var a = new Node(this.polygons);
  93424. var b = new Node(csg.polygons);
  93425. a.clipTo(b);
  93426. b.clipTo(a);
  93427. b.invert();
  93428. b.clipTo(a);
  93429. b.invert();
  93430. a.build(b.allPolygons());
  93431. this.polygons = a.allPolygons();
  93432. };
  93433. /**
  93434. * Subtracts this CSG with another CSG
  93435. * @param csg The CSG to subtract against this CSG
  93436. * @returns A new BABYLON.CSG
  93437. */
  93438. CSG.prototype.subtract = function (csg) {
  93439. var a = new Node(this.clone().polygons);
  93440. var b = new Node(csg.clone().polygons);
  93441. a.invert();
  93442. a.clipTo(b);
  93443. b.clipTo(a);
  93444. b.invert();
  93445. b.clipTo(a);
  93446. b.invert();
  93447. a.build(b.allPolygons());
  93448. a.invert();
  93449. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93450. };
  93451. /**
  93452. * Subtracts this CSG with another CSG in place
  93453. * @param csg The CSG to subtact against this CSG
  93454. */
  93455. CSG.prototype.subtractInPlace = function (csg) {
  93456. var a = new Node(this.polygons);
  93457. var b = new Node(csg.polygons);
  93458. a.invert();
  93459. a.clipTo(b);
  93460. b.clipTo(a);
  93461. b.invert();
  93462. b.clipTo(a);
  93463. b.invert();
  93464. a.build(b.allPolygons());
  93465. a.invert();
  93466. this.polygons = a.allPolygons();
  93467. };
  93468. /**
  93469. * Intersect this CSG with another CSG
  93470. * @param csg The CSG to intersect against this CSG
  93471. * @returns A new BABYLON.CSG
  93472. */
  93473. CSG.prototype.intersect = function (csg) {
  93474. var a = new Node(this.clone().polygons);
  93475. var b = new Node(csg.clone().polygons);
  93476. a.invert();
  93477. b.clipTo(a);
  93478. b.invert();
  93479. a.clipTo(b);
  93480. b.clipTo(a);
  93481. a.build(b.allPolygons());
  93482. a.invert();
  93483. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93484. };
  93485. /**
  93486. * Intersects this CSG with another CSG in place
  93487. * @param csg The CSG to intersect against this CSG
  93488. */
  93489. CSG.prototype.intersectInPlace = function (csg) {
  93490. var a = new Node(this.polygons);
  93491. var b = new Node(csg.polygons);
  93492. a.invert();
  93493. b.clipTo(a);
  93494. b.invert();
  93495. a.clipTo(b);
  93496. b.clipTo(a);
  93497. a.build(b.allPolygons());
  93498. a.invert();
  93499. this.polygons = a.allPolygons();
  93500. };
  93501. /**
  93502. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93503. * not modified.
  93504. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93505. */
  93506. CSG.prototype.inverse = function () {
  93507. var csg = this.clone();
  93508. csg.inverseInPlace();
  93509. return csg;
  93510. };
  93511. /**
  93512. * Inverses the BABYLON.CSG in place
  93513. */
  93514. CSG.prototype.inverseInPlace = function () {
  93515. this.polygons.map(function (p) { p.flip(); });
  93516. };
  93517. /**
  93518. * This is used to keep meshes transformations so they can be restored
  93519. * when we build back a Babylon Mesh
  93520. * NB : All CSG operations are performed in world coordinates
  93521. * @param csg The BABYLON.CSG to copy the transform attributes from
  93522. * @returns This BABYLON.CSG
  93523. */
  93524. CSG.prototype.copyTransformAttributes = function (csg) {
  93525. this.matrix = csg.matrix;
  93526. this.position = csg.position;
  93527. this.rotation = csg.rotation;
  93528. this.scaling = csg.scaling;
  93529. this.rotationQuaternion = csg.rotationQuaternion;
  93530. return this;
  93531. };
  93532. /**
  93533. * Build Raw mesh from CSG
  93534. * Coordinates here are in world space
  93535. * @param name The name of the mesh geometry
  93536. * @param scene The BABYLON.Scene
  93537. * @param keepSubMeshes Specifies if the submeshes should be kept
  93538. * @returns A new BABYLON.Mesh
  93539. */
  93540. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93541. var matrix = this.matrix.clone();
  93542. matrix.invert();
  93543. 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;
  93544. if (keepSubMeshes) {
  93545. // Sort Polygons, since subMeshes are indices range
  93546. polygons.sort(function (a, b) {
  93547. if (a.shared.meshId === b.shared.meshId) {
  93548. return a.shared.subMeshId - b.shared.subMeshId;
  93549. }
  93550. else {
  93551. return a.shared.meshId - b.shared.meshId;
  93552. }
  93553. });
  93554. }
  93555. for (var i = 0, il = polygons.length; i < il; i++) {
  93556. polygon = polygons[i];
  93557. // Building SubMeshes
  93558. if (!subMesh_dict[polygon.shared.meshId]) {
  93559. subMesh_dict[polygon.shared.meshId] = {};
  93560. }
  93561. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93562. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93563. indexStart: +Infinity,
  93564. indexEnd: -Infinity,
  93565. materialIndex: polygon.shared.materialIndex
  93566. };
  93567. }
  93568. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93569. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93570. polygonIndices[0] = 0;
  93571. polygonIndices[1] = j - 1;
  93572. polygonIndices[2] = j;
  93573. for (var k = 0; k < 3; k++) {
  93574. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93575. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93576. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93577. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93578. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93579. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93580. // Check if 2 points can be merged
  93581. if (!(typeof vertex_idx !== 'undefined' &&
  93582. normals[vertex_idx * 3] === localNormal.x &&
  93583. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93584. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93585. uvs[vertex_idx * 2] === uv.x &&
  93586. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93587. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93588. uvs.push(uv.x, uv.y);
  93589. normals.push(normal.x, normal.y, normal.z);
  93590. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93591. }
  93592. indices.push(vertex_idx);
  93593. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93594. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93595. currentIndex++;
  93596. }
  93597. }
  93598. }
  93599. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93600. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93601. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93602. mesh.setIndices(indices, null);
  93603. if (keepSubMeshes) {
  93604. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93605. var materialIndexOffset = 0, materialMaxIndex;
  93606. mesh.subMeshes = new Array();
  93607. for (var m in subMesh_dict) {
  93608. materialMaxIndex = -1;
  93609. for (var sm in subMesh_dict[m]) {
  93610. subMesh_obj = subMesh_dict[m][sm];
  93611. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93612. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93613. }
  93614. materialIndexOffset += ++materialMaxIndex;
  93615. }
  93616. }
  93617. return mesh;
  93618. };
  93619. /**
  93620. * Build Mesh from CSG taking material and transforms into account
  93621. * @param name The name of the BABYLON.Mesh
  93622. * @param material The material of the BABYLON.Mesh
  93623. * @param scene The BABYLON.Scene
  93624. * @param keepSubMeshes Specifies if submeshes should be kept
  93625. * @returns The new BABYLON.Mesh
  93626. */
  93627. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93628. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93629. mesh.material = material;
  93630. mesh.position.copyFrom(this.position);
  93631. mesh.rotation.copyFrom(this.rotation);
  93632. if (this.rotationQuaternion) {
  93633. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93634. }
  93635. mesh.scaling.copyFrom(this.scaling);
  93636. mesh.computeWorldMatrix(true);
  93637. return mesh;
  93638. };
  93639. return CSG;
  93640. }());
  93641. BABYLON.CSG = CSG;
  93642. })(BABYLON || (BABYLON = {}));
  93643. //# sourceMappingURL=babylon.csg.js.map
  93644. var BABYLON;
  93645. (function (BABYLON) {
  93646. /**
  93647. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93648. * It controls one of the indiviual texture used in the effect.
  93649. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93650. */
  93651. var LensFlare = /** @class */ (function () {
  93652. /**
  93653. * Instantiates a new Lens Flare.
  93654. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93655. * It controls one of the indiviual texture used in the effect.
  93656. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93657. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  93658. * @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.
  93659. * @param color Define the lens color
  93660. * @param imgUrl Define the lens texture url
  93661. * @param system Define the `lensFlareSystem` this flare is part of
  93662. */
  93663. function LensFlare(
  93664. /**
  93665. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  93666. */
  93667. size,
  93668. /**
  93669. * 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.
  93670. */
  93671. position, color, imgUrl, system) {
  93672. this.size = size;
  93673. this.position = position;
  93674. /**
  93675. * Define the alpha mode to render this particular lens.
  93676. */
  93677. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93678. this.color = color || new BABYLON.Color3(1, 1, 1);
  93679. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  93680. this._system = system;
  93681. system.lensFlares.push(this);
  93682. }
  93683. /**
  93684. * Creates a new Lens Flare.
  93685. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93686. * It controls one of the indiviual texture used in the effect.
  93687. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93688. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  93689. * @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.
  93690. * @param color Define the lens color
  93691. * @param imgUrl Define the lens texture url
  93692. * @param system Define the `lensFlareSystem` this flare is part of
  93693. * @returns The newly created Lens Flare
  93694. */
  93695. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  93696. return new LensFlare(size, position, color, imgUrl, system);
  93697. };
  93698. /**
  93699. * Dispose and release the lens flare with its associated resources.
  93700. */
  93701. LensFlare.prototype.dispose = function () {
  93702. if (this.texture) {
  93703. this.texture.dispose();
  93704. }
  93705. // Remove from scene
  93706. var index = this._system.lensFlares.indexOf(this);
  93707. this._system.lensFlares.splice(index, 1);
  93708. };
  93709. ;
  93710. return LensFlare;
  93711. }());
  93712. BABYLON.LensFlare = LensFlare;
  93713. })(BABYLON || (BABYLON = {}));
  93714. //# sourceMappingURL=babylon.lensFlare.js.map
  93715. var BABYLON;
  93716. (function (BABYLON) {
  93717. // Adds the parser to the scene parsers.
  93718. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  93719. // Lens flares
  93720. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  93721. if (!container.lensFlareSystems) {
  93722. container.lensFlareSystems = new Array();
  93723. }
  93724. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  93725. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  93726. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  93727. container.lensFlareSystems.push(lf);
  93728. }
  93729. }
  93730. });
  93731. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  93732. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  93733. if (this.lensFlareSystems[index].name === name) {
  93734. return this.lensFlareSystems[index];
  93735. }
  93736. }
  93737. return null;
  93738. };
  93739. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  93740. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  93741. if (this.lensFlareSystems[index].id === id) {
  93742. return this.lensFlareSystems[index];
  93743. }
  93744. }
  93745. return null;
  93746. };
  93747. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  93748. var index = this.lensFlareSystems.indexOf(toRemove);
  93749. if (index !== -1) {
  93750. this.lensFlareSystems.splice(index, 1);
  93751. }
  93752. return index;
  93753. };
  93754. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  93755. this.lensFlareSystems.push(newLensFlareSystem);
  93756. };
  93757. /**
  93758. * Defines the lens flare scene component responsible to manage any lens flares
  93759. * in a given scene.
  93760. */
  93761. var LensFlareSystemSceneComponent = /** @class */ (function () {
  93762. /**
  93763. * Creates a new instance of the component for the given scene
  93764. * @param scene Defines the scene to register the component in
  93765. */
  93766. function LensFlareSystemSceneComponent(scene) {
  93767. /**
  93768. * The component name helpfull to identify the component in the list of scene components.
  93769. */
  93770. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  93771. this.scene = scene;
  93772. scene.lensFlareSystems = new Array();
  93773. }
  93774. /**
  93775. * Registers the component in a given scene
  93776. */
  93777. LensFlareSystemSceneComponent.prototype.register = function () {
  93778. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  93779. };
  93780. /**
  93781. * Rebuilds the elements related to this component in case of
  93782. * context lost for instance.
  93783. */
  93784. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  93785. // Nothing to do for lens flare
  93786. };
  93787. /**
  93788. * Adds all the element from the container to the scene
  93789. * @param container the container holding the elements
  93790. */
  93791. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  93792. var _this = this;
  93793. if (!container.lensFlareSystems) {
  93794. return;
  93795. }
  93796. container.lensFlareSystems.forEach(function (o) {
  93797. _this.scene.addLensFlareSystem(o);
  93798. });
  93799. };
  93800. /**
  93801. * Removes all the elements in the container from the scene
  93802. * @param container contains the elements to remove
  93803. */
  93804. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  93805. var _this = this;
  93806. if (!container.lensFlareSystems) {
  93807. return;
  93808. }
  93809. container.lensFlareSystems.forEach(function (o) {
  93810. _this.scene.removeLensFlareSystem(o);
  93811. });
  93812. };
  93813. /**
  93814. * Serializes the component data to the specified json object
  93815. * @param serializationObject The object to serialize to
  93816. */
  93817. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  93818. // Lens flares
  93819. serializationObject.lensFlareSystems = [];
  93820. var lensFlareSystems = this.scene.lensFlareSystems;
  93821. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  93822. var lensFlareSystem = lensFlareSystems_1[_i];
  93823. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  93824. }
  93825. };
  93826. /**
  93827. * Disposes the component and the associated ressources.
  93828. */
  93829. LensFlareSystemSceneComponent.prototype.dispose = function () {
  93830. var lensFlareSystems = this.scene.lensFlareSystems;
  93831. while (lensFlareSystems.length) {
  93832. lensFlareSystems[0].dispose();
  93833. }
  93834. };
  93835. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  93836. // Lens flares
  93837. if (this.scene.lensFlaresEnabled) {
  93838. var lensFlareSystems = this.scene.lensFlareSystems;
  93839. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  93840. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  93841. var lensFlareSystem = lensFlareSystems_2[_i];
  93842. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  93843. lensFlareSystem.render();
  93844. }
  93845. }
  93846. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  93847. }
  93848. };
  93849. return LensFlareSystemSceneComponent;
  93850. }());
  93851. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  93852. })(BABYLON || (BABYLON = {}));
  93853. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  93854. var BABYLON;
  93855. (function (BABYLON) {
  93856. /**
  93857. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  93858. * It is usually composed of several `BABYLON.lensFlare`.
  93859. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93860. */
  93861. var LensFlareSystem = /** @class */ (function () {
  93862. /**
  93863. * Instantiates a lens flare system.
  93864. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  93865. * It is usually composed of several `BABYLON.lensFlare`.
  93866. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93867. * @param name Define the name of the lens flare system in the scene
  93868. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  93869. * @param scene Define the scene the lens flare system belongs to
  93870. */
  93871. function LensFlareSystem(
  93872. /**
  93873. * Define the name of the lens flare system
  93874. */
  93875. name, emitter, scene) {
  93876. this.name = name;
  93877. /**
  93878. * List of lens flares used in this system.
  93879. */
  93880. this.lensFlares = new Array();
  93881. /**
  93882. * Define a limit from the border the lens flare can be visible.
  93883. */
  93884. this.borderLimit = 300;
  93885. /**
  93886. * Define a viewport border we do not want to see the lens flare in.
  93887. */
  93888. this.viewportBorder = 0;
  93889. /**
  93890. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  93891. */
  93892. this.layerMask = 0x0FFFFFFF;
  93893. this._vertexBuffers = {};
  93894. this._isEnabled = true;
  93895. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93896. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  93897. if (!component) {
  93898. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  93899. scene._addComponent(component);
  93900. }
  93901. this._emitter = emitter;
  93902. this.id = name;
  93903. scene.lensFlareSystems.push(this);
  93904. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  93905. var engine = scene.getEngine();
  93906. // VBO
  93907. var vertices = [];
  93908. vertices.push(1, 1);
  93909. vertices.push(-1, 1);
  93910. vertices.push(-1, -1);
  93911. vertices.push(1, -1);
  93912. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93913. // Indices
  93914. var indices = [];
  93915. indices.push(0);
  93916. indices.push(1);
  93917. indices.push(2);
  93918. indices.push(0);
  93919. indices.push(2);
  93920. indices.push(3);
  93921. this._indexBuffer = engine.createIndexBuffer(indices);
  93922. // Effects
  93923. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  93924. }
  93925. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  93926. /**
  93927. * Define if the lens flare system is enabled.
  93928. */
  93929. get: function () {
  93930. return this._isEnabled;
  93931. },
  93932. set: function (value) {
  93933. this._isEnabled = value;
  93934. },
  93935. enumerable: true,
  93936. configurable: true
  93937. });
  93938. /**
  93939. * Get the scene the effects belongs to.
  93940. * @returns the scene holding the lens flare system
  93941. */
  93942. LensFlareSystem.prototype.getScene = function () {
  93943. return this._scene;
  93944. };
  93945. /**
  93946. * Get the emitter of the lens flare system.
  93947. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  93948. * @returns the emitter of the lens flare system
  93949. */
  93950. LensFlareSystem.prototype.getEmitter = function () {
  93951. return this._emitter;
  93952. };
  93953. /**
  93954. * Set the emitter of the lens flare system.
  93955. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  93956. * @param newEmitter Define the new emitter of the system
  93957. */
  93958. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  93959. this._emitter = newEmitter;
  93960. };
  93961. /**
  93962. * Get the lens flare system emitter position.
  93963. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  93964. * @returns the position
  93965. */
  93966. LensFlareSystem.prototype.getEmitterPosition = function () {
  93967. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  93968. };
  93969. /**
  93970. * @hidden
  93971. */
  93972. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  93973. var position = this.getEmitterPosition();
  93974. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  93975. this._positionX = position.x;
  93976. this._positionY = position.y;
  93977. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  93978. if (this.viewportBorder > 0) {
  93979. globalViewport.x -= this.viewportBorder;
  93980. globalViewport.y -= this.viewportBorder;
  93981. globalViewport.width += this.viewportBorder * 2;
  93982. globalViewport.height += this.viewportBorder * 2;
  93983. position.x += this.viewportBorder;
  93984. position.y += this.viewportBorder;
  93985. this._positionX += this.viewportBorder;
  93986. this._positionY += this.viewportBorder;
  93987. }
  93988. if (position.z > 0) {
  93989. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  93990. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  93991. return true;
  93992. }
  93993. return true;
  93994. }
  93995. return false;
  93996. };
  93997. /** @hidden */
  93998. LensFlareSystem.prototype._isVisible = function () {
  93999. if (!this._isEnabled || !this._scene.activeCamera) {
  94000. return false;
  94001. }
  94002. var emitterPosition = this.getEmitterPosition();
  94003. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  94004. var distance = direction.length();
  94005. direction.normalize();
  94006. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  94007. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  94008. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  94009. };
  94010. /**
  94011. * @hidden
  94012. */
  94013. LensFlareSystem.prototype.render = function () {
  94014. if (!this._effect.isReady() || !this._scene.activeCamera)
  94015. return false;
  94016. var engine = this._scene.getEngine();
  94017. var viewport = this._scene.activeCamera.viewport;
  94018. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94019. // Position
  94020. if (!this.computeEffectivePosition(globalViewport)) {
  94021. return false;
  94022. }
  94023. // Visibility
  94024. if (!this._isVisible()) {
  94025. return false;
  94026. }
  94027. // Intensity
  94028. var awayX;
  94029. var awayY;
  94030. if (this._positionX < this.borderLimit + globalViewport.x) {
  94031. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94032. }
  94033. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94034. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94035. }
  94036. else {
  94037. awayX = 0;
  94038. }
  94039. if (this._positionY < this.borderLimit + globalViewport.y) {
  94040. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94041. }
  94042. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94043. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94044. }
  94045. else {
  94046. awayY = 0;
  94047. }
  94048. var away = (awayX > awayY) ? awayX : awayY;
  94049. away -= this.viewportBorder;
  94050. if (away > this.borderLimit) {
  94051. away = this.borderLimit;
  94052. }
  94053. var intensity = 1.0 - (away / this.borderLimit);
  94054. if (intensity < 0) {
  94055. return false;
  94056. }
  94057. if (intensity > 1.0) {
  94058. intensity = 1.0;
  94059. }
  94060. if (this.viewportBorder > 0) {
  94061. globalViewport.x += this.viewportBorder;
  94062. globalViewport.y += this.viewportBorder;
  94063. globalViewport.width -= this.viewportBorder * 2;
  94064. globalViewport.height -= this.viewportBorder * 2;
  94065. this._positionX -= this.viewportBorder;
  94066. this._positionY -= this.viewportBorder;
  94067. }
  94068. // Position
  94069. var centerX = globalViewport.x + globalViewport.width / 2;
  94070. var centerY = globalViewport.y + globalViewport.height / 2;
  94071. var distX = centerX - this._positionX;
  94072. var distY = centerY - this._positionY;
  94073. // Effects
  94074. engine.enableEffect(this._effect);
  94075. engine.setState(false);
  94076. engine.setDepthBuffer(false);
  94077. // VBOs
  94078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94079. // Flares
  94080. for (var index = 0; index < this.lensFlares.length; index++) {
  94081. var flare = this.lensFlares[index];
  94082. engine.setAlphaMode(flare.alphaMode);
  94083. var x = centerX - (distX * flare.position);
  94084. var y = centerY - (distY * flare.position);
  94085. var cw = flare.size;
  94086. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94087. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94088. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94089. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94090. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94091. // Texture
  94092. this._effect.setTexture("textureSampler", flare.texture);
  94093. // Color
  94094. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94095. // Draw order
  94096. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94097. }
  94098. engine.setDepthBuffer(true);
  94099. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94100. return true;
  94101. };
  94102. /**
  94103. * Dispose and release the lens flare with its associated resources.
  94104. */
  94105. LensFlareSystem.prototype.dispose = function () {
  94106. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94107. if (vertexBuffer) {
  94108. vertexBuffer.dispose();
  94109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94110. }
  94111. if (this._indexBuffer) {
  94112. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94113. this._indexBuffer = null;
  94114. }
  94115. while (this.lensFlares.length) {
  94116. this.lensFlares[0].dispose();
  94117. }
  94118. // Remove from scene
  94119. var index = this._scene.lensFlareSystems.indexOf(this);
  94120. this._scene.lensFlareSystems.splice(index, 1);
  94121. };
  94122. /**
  94123. * Parse a lens flare system from a JSON repressentation
  94124. * @param parsedLensFlareSystem Define the JSON to parse
  94125. * @param scene Define the scene the parsed system should be instantiated in
  94126. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94127. * @returns the parsed system
  94128. */
  94129. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94130. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94131. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94132. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94133. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94134. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94135. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94136. var parsedFlare = parsedLensFlareSystem.flares[index];
  94137. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94138. }
  94139. return lensFlareSystem;
  94140. };
  94141. /**
  94142. * Serialize the current Lens Flare System into a JSON representation.
  94143. * @returns the serialized JSON
  94144. */
  94145. LensFlareSystem.prototype.serialize = function () {
  94146. var serializationObject = {};
  94147. serializationObject.id = this.id;
  94148. serializationObject.name = this.name;
  94149. serializationObject.emitterId = this.getEmitter().id;
  94150. serializationObject.borderLimit = this.borderLimit;
  94151. serializationObject.flares = [];
  94152. for (var index = 0; index < this.lensFlares.length; index++) {
  94153. var flare = this.lensFlares[index];
  94154. serializationObject.flares.push({
  94155. size: flare.size,
  94156. position: flare.position,
  94157. color: flare.color.asArray(),
  94158. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94159. });
  94160. }
  94161. return serializationObject;
  94162. };
  94163. return LensFlareSystem;
  94164. }());
  94165. BABYLON.LensFlareSystem = LensFlareSystem;
  94166. })(BABYLON || (BABYLON = {}));
  94167. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94168. var BABYLON;
  94169. (function (BABYLON) {
  94170. /**
  94171. * This is a holder class for the physics joint created by the physics plugin
  94172. * It holds a set of functions to control the underlying joint
  94173. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94174. */
  94175. var PhysicsJoint = /** @class */ (function () {
  94176. /**
  94177. * Initializes the physics joint
  94178. * @param type The type of the physics joint
  94179. * @param jointData The data for the physics joint
  94180. */
  94181. function PhysicsJoint(
  94182. /**
  94183. * The type of the physics joint
  94184. */
  94185. type,
  94186. /**
  94187. * The data for the physics joint
  94188. */
  94189. jointData) {
  94190. this.type = type;
  94191. this.jointData = jointData;
  94192. jointData.nativeParams = jointData.nativeParams || {};
  94193. }
  94194. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94195. /**
  94196. * Gets the physics joint
  94197. */
  94198. get: function () {
  94199. return this._physicsJoint;
  94200. },
  94201. /**
  94202. * Sets the physics joint
  94203. */
  94204. set: function (newJoint) {
  94205. if (this._physicsJoint) {
  94206. //remove from the wolrd
  94207. }
  94208. this._physicsJoint = newJoint;
  94209. },
  94210. enumerable: true,
  94211. configurable: true
  94212. });
  94213. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94214. /**
  94215. * Sets the physics plugin
  94216. */
  94217. set: function (physicsPlugin) {
  94218. this._physicsPlugin = physicsPlugin;
  94219. },
  94220. enumerable: true,
  94221. configurable: true
  94222. });
  94223. /**
  94224. * Execute a function that is physics-plugin specific.
  94225. * @param {Function} func the function that will be executed.
  94226. * It accepts two parameters: the physics world and the physics joint
  94227. */
  94228. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94229. func(this._physicsPlugin.world, this._physicsJoint);
  94230. };
  94231. //TODO check if the native joints are the same
  94232. //Joint Types
  94233. /**
  94234. * Distance-Joint type
  94235. */
  94236. PhysicsJoint.DistanceJoint = 0;
  94237. /**
  94238. * Hinge-Joint type
  94239. */
  94240. PhysicsJoint.HingeJoint = 1;
  94241. /**
  94242. * Ball-and-Socket joint type
  94243. */
  94244. PhysicsJoint.BallAndSocketJoint = 2;
  94245. /**
  94246. * Wheel-Joint type
  94247. */
  94248. PhysicsJoint.WheelJoint = 3;
  94249. /**
  94250. * Slider-Joint type
  94251. */
  94252. PhysicsJoint.SliderJoint = 4;
  94253. //OIMO
  94254. /**
  94255. * Prismatic-Joint type
  94256. */
  94257. PhysicsJoint.PrismaticJoint = 5;
  94258. //
  94259. /**
  94260. * Universal-Joint type
  94261. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94262. */
  94263. PhysicsJoint.UniversalJoint = 6;
  94264. /**
  94265. * Hinge-Joint 2 type
  94266. */
  94267. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94268. //Cannon
  94269. /**
  94270. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94271. */
  94272. PhysicsJoint.PointToPointJoint = 8;
  94273. //Cannon only at the moment
  94274. /**
  94275. * Spring-Joint type
  94276. */
  94277. PhysicsJoint.SpringJoint = 9;
  94278. /**
  94279. * Lock-Joint type
  94280. */
  94281. PhysicsJoint.LockJoint = 10;
  94282. return PhysicsJoint;
  94283. }());
  94284. BABYLON.PhysicsJoint = PhysicsJoint;
  94285. /**
  94286. * A class representing a physics distance joint
  94287. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94288. */
  94289. var DistanceJoint = /** @class */ (function (_super) {
  94290. __extends(DistanceJoint, _super);
  94291. /**
  94292. *
  94293. * @param jointData The data for the Distance-Joint
  94294. */
  94295. function DistanceJoint(jointData) {
  94296. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94297. }
  94298. /**
  94299. * Update the predefined distance.
  94300. * @param maxDistance The maximum preferred distance
  94301. * @param minDistance The minimum preferred distance
  94302. */
  94303. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94304. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94305. };
  94306. return DistanceJoint;
  94307. }(PhysicsJoint));
  94308. BABYLON.DistanceJoint = DistanceJoint;
  94309. /**
  94310. * Represents a Motor-Enabled Joint
  94311. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94312. */
  94313. var MotorEnabledJoint = /** @class */ (function (_super) {
  94314. __extends(MotorEnabledJoint, _super);
  94315. /**
  94316. * Initializes the Motor-Enabled Joint
  94317. * @param type The type of the joint
  94318. * @param jointData The physica joint data for the joint
  94319. */
  94320. function MotorEnabledJoint(type, jointData) {
  94321. return _super.call(this, type, jointData) || this;
  94322. }
  94323. /**
  94324. * Set the motor values.
  94325. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94326. * @param force the force to apply
  94327. * @param maxForce max force for this motor.
  94328. */
  94329. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94330. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94331. };
  94332. /**
  94333. * Set the motor's limits.
  94334. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94335. * @param upperLimit The upper limit of the motor
  94336. * @param lowerLimit The lower limit of the motor
  94337. */
  94338. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94339. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94340. };
  94341. return MotorEnabledJoint;
  94342. }(PhysicsJoint));
  94343. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94344. /**
  94345. * This class represents a single physics Hinge-Joint
  94346. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94347. */
  94348. var HingeJoint = /** @class */ (function (_super) {
  94349. __extends(HingeJoint, _super);
  94350. /**
  94351. * Initializes the Hinge-Joint
  94352. * @param jointData The joint data for the Hinge-Joint
  94353. */
  94354. function HingeJoint(jointData) {
  94355. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94356. }
  94357. /**
  94358. * Set the motor values.
  94359. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94360. * @param {number} force the force to apply
  94361. * @param {number} maxForce max force for this motor.
  94362. */
  94363. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94364. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94365. };
  94366. /**
  94367. * Set the motor's limits.
  94368. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94369. * @param upperLimit The upper limit of the motor
  94370. * @param lowerLimit The lower limit of the motor
  94371. */
  94372. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94373. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94374. };
  94375. return HingeJoint;
  94376. }(MotorEnabledJoint));
  94377. BABYLON.HingeJoint = HingeJoint;
  94378. /**
  94379. * This class represents a dual hinge physics joint (same as wheel joint)
  94380. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94381. */
  94382. var Hinge2Joint = /** @class */ (function (_super) {
  94383. __extends(Hinge2Joint, _super);
  94384. /**
  94385. * Initializes the Hinge2-Joint
  94386. * @param jointData The joint data for the Hinge2-Joint
  94387. */
  94388. function Hinge2Joint(jointData) {
  94389. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94390. }
  94391. /**
  94392. * Set the motor values.
  94393. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94394. * @param {number} force the force to apply
  94395. * @param {number} maxForce max force for this motor.
  94396. * @param {motorIndex} the motor's index, 0 or 1.
  94397. */
  94398. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94399. if (motorIndex === void 0) { motorIndex = 0; }
  94400. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94401. };
  94402. /**
  94403. * Set the motor limits.
  94404. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94405. * @param {number} upperLimit the upper limit
  94406. * @param {number} lowerLimit lower limit
  94407. * @param {motorIndex} the motor's index, 0 or 1.
  94408. */
  94409. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94410. if (motorIndex === void 0) { motorIndex = 0; }
  94411. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94412. };
  94413. return Hinge2Joint;
  94414. }(MotorEnabledJoint));
  94415. BABYLON.Hinge2Joint = Hinge2Joint;
  94416. })(BABYLON || (BABYLON = {}));
  94417. //# sourceMappingURL=babylon.physicsJoint.js.map
  94418. var BABYLON;
  94419. (function (BABYLON) {
  94420. /**
  94421. * Represents a physics imposter
  94422. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94423. */
  94424. var PhysicsImpostor = /** @class */ (function () {
  94425. /**
  94426. * Initializes the physics imposter
  94427. * @param object The physics-enabled object used as the physics imposter
  94428. * @param type The type of the physics imposter
  94429. * @param _options The options for the physics imposter
  94430. * @param _scene The Babylon scene
  94431. */
  94432. function PhysicsImpostor(
  94433. /**
  94434. * The physics-enabled object used as the physics imposter
  94435. */
  94436. object,
  94437. /**
  94438. * The type of the physics imposter
  94439. */
  94440. type, _options, _scene) {
  94441. if (_options === void 0) { _options = { mass: 0 }; }
  94442. var _this = this;
  94443. this.object = object;
  94444. this.type = type;
  94445. this._options = _options;
  94446. this._scene = _scene;
  94447. this._bodyUpdateRequired = false;
  94448. this._onBeforePhysicsStepCallbacks = new Array();
  94449. this._onAfterPhysicsStepCallbacks = new Array();
  94450. this._onPhysicsCollideCallbacks = [];
  94451. this._deltaPosition = BABYLON.Vector3.Zero();
  94452. this._isDisposed = false;
  94453. //temp variables for parent rotation calculations
  94454. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94455. this._tmpQuat = new BABYLON.Quaternion();
  94456. this._tmpQuat2 = new BABYLON.Quaternion();
  94457. /**
  94458. * this function is executed by the physics engine.
  94459. */
  94460. this.beforeStep = function () {
  94461. if (!_this._physicsEngine) {
  94462. return;
  94463. }
  94464. _this.object.translate(_this._deltaPosition, -1);
  94465. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94466. _this.object.computeWorldMatrix(false);
  94467. if (_this.object.parent && _this.object.rotationQuaternion) {
  94468. _this.getParentsRotation();
  94469. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94470. }
  94471. else {
  94472. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94473. }
  94474. if (!_this._options.disableBidirectionalTransformation) {
  94475. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94476. }
  94477. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94478. func(_this);
  94479. });
  94480. };
  94481. /**
  94482. * this function is executed by the physics engine
  94483. */
  94484. this.afterStep = function () {
  94485. if (!_this._physicsEngine) {
  94486. return;
  94487. }
  94488. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94489. func(_this);
  94490. });
  94491. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94492. // object has now its world rotation. needs to be converted to local.
  94493. if (_this.object.parent && _this.object.rotationQuaternion) {
  94494. _this.getParentsRotation();
  94495. _this._tmpQuat.conjugateInPlace();
  94496. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94497. }
  94498. // take the position set and make it the absolute position of this object.
  94499. _this.object.setAbsolutePosition(_this.object.position);
  94500. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94501. _this.object.translate(_this._deltaPosition, 1);
  94502. };
  94503. /**
  94504. * Legacy collision detection event support
  94505. */
  94506. this.onCollideEvent = null;
  94507. /**
  94508. * event and body object due to cannon's event-based architecture.
  94509. */
  94510. this.onCollide = function (e) {
  94511. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94512. return;
  94513. }
  94514. if (!_this._physicsEngine) {
  94515. return;
  94516. }
  94517. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94518. if (otherImpostor) {
  94519. // Legacy collision detection event support
  94520. if (_this.onCollideEvent) {
  94521. _this.onCollideEvent(_this, otherImpostor);
  94522. }
  94523. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94524. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94525. }).forEach(function (obj) {
  94526. obj.callback(_this, otherImpostor);
  94527. });
  94528. }
  94529. };
  94530. //sanity check!
  94531. if (!this.object) {
  94532. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94533. return;
  94534. }
  94535. //legacy support for old syntax.
  94536. if (!this._scene && object.getScene) {
  94537. this._scene = object.getScene();
  94538. }
  94539. if (!this._scene) {
  94540. return;
  94541. }
  94542. this._physicsEngine = this._scene.getPhysicsEngine();
  94543. if (!this._physicsEngine) {
  94544. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94545. }
  94546. else {
  94547. //set the object's quaternion, if not set
  94548. if (!this.object.rotationQuaternion) {
  94549. if (this.object.rotation) {
  94550. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94551. }
  94552. else {
  94553. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94554. }
  94555. }
  94556. //default options params
  94557. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94558. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94559. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94560. this._joints = [];
  94561. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94562. if (!this.object.parent || this._options.ignoreParent) {
  94563. this._init();
  94564. }
  94565. else if (this.object.parent.physicsImpostor) {
  94566. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94567. }
  94568. }
  94569. }
  94570. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94571. /**
  94572. * Specifies if the physics imposter is disposed
  94573. */
  94574. get: function () {
  94575. return this._isDisposed;
  94576. },
  94577. enumerable: true,
  94578. configurable: true
  94579. });
  94580. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94581. /**
  94582. * Gets the mass of the physics imposter
  94583. */
  94584. get: function () {
  94585. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94586. },
  94587. set: function (value) {
  94588. this.setMass(value);
  94589. },
  94590. enumerable: true,
  94591. configurable: true
  94592. });
  94593. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94594. /**
  94595. * Gets the coefficient of friction
  94596. */
  94597. get: function () {
  94598. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94599. },
  94600. /**
  94601. * Sets the coefficient of friction
  94602. */
  94603. set: function (value) {
  94604. if (!this._physicsEngine) {
  94605. return;
  94606. }
  94607. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94608. },
  94609. enumerable: true,
  94610. configurable: true
  94611. });
  94612. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94613. /**
  94614. * Gets the coefficient of restitution
  94615. */
  94616. get: function () {
  94617. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94618. },
  94619. /**
  94620. * Sets the coefficient of restitution
  94621. */
  94622. set: function (value) {
  94623. if (!this._physicsEngine) {
  94624. return;
  94625. }
  94626. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94627. },
  94628. enumerable: true,
  94629. configurable: true
  94630. });
  94631. /**
  94632. * This function will completly initialize this impostor.
  94633. * It will create a new body - but only if this mesh has no parent.
  94634. * If it has, this impostor will not be used other than to define the impostor
  94635. * of the child mesh.
  94636. * @hidden
  94637. */
  94638. PhysicsImpostor.prototype._init = function () {
  94639. if (!this._physicsEngine) {
  94640. return;
  94641. }
  94642. this._physicsEngine.removeImpostor(this);
  94643. this.physicsBody = null;
  94644. this._parent = this._parent || this._getPhysicsParent();
  94645. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94646. this._physicsEngine.addImpostor(this);
  94647. }
  94648. };
  94649. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94650. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94651. var parentMesh = this.object.parent;
  94652. return parentMesh.physicsImpostor;
  94653. }
  94654. return null;
  94655. };
  94656. /**
  94657. * Should a new body be generated.
  94658. * @returns boolean specifying if body initialization is required
  94659. */
  94660. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  94661. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  94662. };
  94663. /**
  94664. * Sets the updated scaling
  94665. * @param updated Specifies if the scaling is updated
  94666. */
  94667. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  94668. this.forceUpdate();
  94669. };
  94670. /**
  94671. * Force a regeneration of this or the parent's impostor's body.
  94672. * Use under cautious - This will remove all joints already implemented.
  94673. */
  94674. PhysicsImpostor.prototype.forceUpdate = function () {
  94675. this._init();
  94676. if (this.parent && !this._options.ignoreParent) {
  94677. this.parent.forceUpdate();
  94678. }
  94679. };
  94680. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  94681. /*public get mesh(): AbstractMesh {
  94682. return this._mesh;
  94683. }*/
  94684. /**
  94685. * Gets the body that holds this impostor. Either its own, or its parent.
  94686. */
  94687. get: function () {
  94688. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  94689. },
  94690. /**
  94691. * Set the physics body. Used mainly by the physics engine/plugin
  94692. */
  94693. set: function (physicsBody) {
  94694. if (this._physicsBody && this._physicsEngine) {
  94695. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  94696. }
  94697. this._physicsBody = physicsBody;
  94698. this.resetUpdateFlags();
  94699. },
  94700. enumerable: true,
  94701. configurable: true
  94702. });
  94703. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  94704. /**
  94705. * Get the parent of the physics imposter
  94706. * @returns Physics imposter or null
  94707. */
  94708. get: function () {
  94709. return !this._options.ignoreParent && this._parent ? this._parent : null;
  94710. },
  94711. /**
  94712. * Sets the parent of the physics imposter
  94713. */
  94714. set: function (value) {
  94715. this._parent = value;
  94716. },
  94717. enumerable: true,
  94718. configurable: true
  94719. });
  94720. /**
  94721. * Resets the update flags
  94722. */
  94723. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  94724. this._bodyUpdateRequired = false;
  94725. };
  94726. /**
  94727. * Gets the object extend size
  94728. * @returns the object extend size
  94729. */
  94730. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  94731. if (this.object.getBoundingInfo) {
  94732. var q = this.object.rotationQuaternion;
  94733. //reset rotation
  94734. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  94735. //calculate the world matrix with no rotation
  94736. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  94737. var boundingInfo = this.object.getBoundingInfo();
  94738. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  94739. //bring back the rotation
  94740. this.object.rotationQuaternion = q;
  94741. //calculate the world matrix with the new rotation
  94742. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  94743. return size;
  94744. }
  94745. else {
  94746. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  94747. }
  94748. };
  94749. /**
  94750. * Gets the object center
  94751. * @returns The object center
  94752. */
  94753. PhysicsImpostor.prototype.getObjectCenter = function () {
  94754. if (this.object.getBoundingInfo) {
  94755. var boundingInfo = this.object.getBoundingInfo();
  94756. return boundingInfo.boundingBox.centerWorld;
  94757. }
  94758. else {
  94759. return this.object.position;
  94760. }
  94761. };
  94762. /**
  94763. * Get a specific parametes from the options parameter
  94764. * @param paramName The object parameter name
  94765. * @returns The object parameter
  94766. */
  94767. PhysicsImpostor.prototype.getParam = function (paramName) {
  94768. return this._options[paramName];
  94769. };
  94770. /**
  94771. * Sets a specific parameter in the options given to the physics plugin
  94772. * @param paramName The parameter name
  94773. * @param value The value of the parameter
  94774. */
  94775. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  94776. this._options[paramName] = value;
  94777. this._bodyUpdateRequired = true;
  94778. };
  94779. /**
  94780. * Specifically change the body's mass option. Won't recreate the physics body object
  94781. * @param mass The mass of the physics imposter
  94782. */
  94783. PhysicsImpostor.prototype.setMass = function (mass) {
  94784. if (this.getParam("mass") !== mass) {
  94785. this.setParam("mass", mass);
  94786. }
  94787. if (this._physicsEngine) {
  94788. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  94789. }
  94790. };
  94791. /**
  94792. * Gets the linear velocity
  94793. * @returns linear velocity or null
  94794. */
  94795. PhysicsImpostor.prototype.getLinearVelocity = function () {
  94796. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  94797. };
  94798. /**
  94799. * Sets the linear velocity
  94800. * @param velocity linear velocity or null
  94801. */
  94802. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  94803. if (this._physicsEngine) {
  94804. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  94805. }
  94806. };
  94807. /**
  94808. * Gets the angular velocity
  94809. * @returns angular velocity or null
  94810. */
  94811. PhysicsImpostor.prototype.getAngularVelocity = function () {
  94812. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  94813. };
  94814. /**
  94815. * Sets the angular velocity
  94816. * @param velocity The velocity or null
  94817. */
  94818. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  94819. if (this._physicsEngine) {
  94820. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  94821. }
  94822. };
  94823. /**
  94824. * Execute a function with the physics plugin native code
  94825. * Provide a function the will have two variables - the world object and the physics body object
  94826. * @param func The function to execute with the physics plugin native code
  94827. */
  94828. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  94829. if (this._physicsEngine) {
  94830. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  94831. }
  94832. };
  94833. /**
  94834. * Register a function that will be executed before the physics world is stepping forward
  94835. * @param func The function to execute before the physics world is stepped forward
  94836. */
  94837. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  94838. this._onBeforePhysicsStepCallbacks.push(func);
  94839. };
  94840. /**
  94841. * Unregister a function that will be executed before the physics world is stepping forward
  94842. * @param func The function to execute before the physics world is stepped forward
  94843. */
  94844. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  94845. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  94846. if (index > -1) {
  94847. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  94848. }
  94849. else {
  94850. BABYLON.Tools.Warn("Function to remove was not found");
  94851. }
  94852. };
  94853. /**
  94854. * Register a function that will be executed after the physics step
  94855. * @param func The function to execute after physics step
  94856. */
  94857. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  94858. this._onAfterPhysicsStepCallbacks.push(func);
  94859. };
  94860. /**
  94861. * Unregisters a function that will be executed after the physics step
  94862. * @param func The function to execute after physics step
  94863. */
  94864. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  94865. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  94866. if (index > -1) {
  94867. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  94868. }
  94869. else {
  94870. BABYLON.Tools.Warn("Function to remove was not found");
  94871. }
  94872. };
  94873. /**
  94874. * register a function that will be executed when this impostor collides against a different body
  94875. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  94876. * @param func Callback that is executed on collision
  94877. */
  94878. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  94879. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  94880. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  94881. };
  94882. /**
  94883. * Unregisters the physics imposter on contact
  94884. * @param collideAgainst The physics object to collide against
  94885. * @param func Callback to execute on collision
  94886. */
  94887. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  94888. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  94889. var index = -1;
  94890. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  94891. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  94892. // chcek the arrays match
  94893. var sameList = cbDef.otherImpostors.every(function (impostor) {
  94894. return collidedAgainstList.indexOf(impostor) > -1;
  94895. });
  94896. if (sameList) {
  94897. index = idx;
  94898. }
  94899. return sameList;
  94900. }
  94901. return false;
  94902. });
  94903. if (found) {
  94904. this._onPhysicsCollideCallbacks.splice(index, 1);
  94905. }
  94906. else {
  94907. BABYLON.Tools.Warn("Function to remove was not found");
  94908. }
  94909. };
  94910. /**
  94911. * Get the parent rotation
  94912. * @returns The parent rotation
  94913. */
  94914. PhysicsImpostor.prototype.getParentsRotation = function () {
  94915. var parent = this.object.parent;
  94916. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  94917. while (parent) {
  94918. if (parent.rotationQuaternion) {
  94919. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  94920. }
  94921. else {
  94922. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  94923. }
  94924. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  94925. parent = parent.parent;
  94926. }
  94927. return this._tmpQuat;
  94928. };
  94929. /**
  94930. * Apply a force
  94931. * @param force The force to apply
  94932. * @param contactPoint The contact point for the force
  94933. * @returns The physics imposter
  94934. */
  94935. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  94936. if (this._physicsEngine) {
  94937. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  94938. }
  94939. return this;
  94940. };
  94941. /**
  94942. * Apply an impulse
  94943. * @param force The impulse force
  94944. * @param contactPoint The contact point for the impulse force
  94945. * @returns The physics imposter
  94946. */
  94947. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  94948. if (this._physicsEngine) {
  94949. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  94950. }
  94951. return this;
  94952. };
  94953. /**
  94954. * A help function to create a joint
  94955. * @param otherImpostor A physics imposter used to create a joint
  94956. * @param jointType The type of joint
  94957. * @param jointData The data for the joint
  94958. * @returns The physics imposter
  94959. */
  94960. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  94961. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  94962. this.addJoint(otherImpostor, joint);
  94963. return this;
  94964. };
  94965. /**
  94966. * Add a joint to this impostor with a different impostor
  94967. * @param otherImpostor A physics imposter used to add a joint
  94968. * @param joint The joint to add
  94969. * @returns The physics imposter
  94970. */
  94971. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  94972. this._joints.push({
  94973. otherImpostor: otherImpostor,
  94974. joint: joint
  94975. });
  94976. if (this._physicsEngine) {
  94977. this._physicsEngine.addJoint(this, otherImpostor, joint);
  94978. }
  94979. return this;
  94980. };
  94981. /**
  94982. * Will keep this body still, in a sleep mode.
  94983. * @returns the physics imposter
  94984. */
  94985. PhysicsImpostor.prototype.sleep = function () {
  94986. if (this._physicsEngine) {
  94987. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  94988. }
  94989. return this;
  94990. };
  94991. /**
  94992. * Wake the body up.
  94993. * @returns The physics imposter
  94994. */
  94995. PhysicsImpostor.prototype.wakeUp = function () {
  94996. if (this._physicsEngine) {
  94997. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  94998. }
  94999. return this;
  95000. };
  95001. /**
  95002. * Clones the physics imposter
  95003. * @param newObject The physics imposter clones to this physics-enabled object
  95004. * @returns A nullable physics imposter
  95005. */
  95006. PhysicsImpostor.prototype.clone = function (newObject) {
  95007. if (!newObject)
  95008. return null;
  95009. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  95010. };
  95011. /**
  95012. * Disposes the physics imposter
  95013. */
  95014. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  95015. var _this = this;
  95016. //no dispose if no physics engine is available.
  95017. if (!this._physicsEngine) {
  95018. return;
  95019. }
  95020. this._joints.forEach(function (j) {
  95021. if (_this._physicsEngine) {
  95022. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95023. }
  95024. });
  95025. //dispose the physics body
  95026. this._physicsEngine.removeImpostor(this);
  95027. if (this.parent) {
  95028. this.parent.forceUpdate();
  95029. }
  95030. else {
  95031. /*this._object.getChildMeshes().forEach(function(mesh) {
  95032. if (mesh.physicsImpostor) {
  95033. if (disposeChildren) {
  95034. mesh.physicsImpostor.dispose();
  95035. mesh.physicsImpostor = null;
  95036. }
  95037. }
  95038. })*/
  95039. }
  95040. this._isDisposed = true;
  95041. };
  95042. /**
  95043. * Sets the delta position
  95044. * @param position The delta position amount
  95045. */
  95046. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95047. this._deltaPosition.copyFrom(position);
  95048. };
  95049. /**
  95050. * Sets the delta rotation
  95051. * @param rotation The delta rotation amount
  95052. */
  95053. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95054. if (!this._deltaRotation) {
  95055. this._deltaRotation = new BABYLON.Quaternion();
  95056. }
  95057. this._deltaRotation.copyFrom(rotation);
  95058. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95059. };
  95060. /**
  95061. * Gets the box size of the physics imposter and stores the result in the input parameter
  95062. * @param result Stores the box size
  95063. * @returns The physics imposter
  95064. */
  95065. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95066. if (this._physicsEngine) {
  95067. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95068. }
  95069. return this;
  95070. };
  95071. /**
  95072. * Gets the radius of the physics imposter
  95073. * @returns Radius of the physics imposter
  95074. */
  95075. PhysicsImpostor.prototype.getRadius = function () {
  95076. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95077. };
  95078. /**
  95079. * Sync a bone with this impostor
  95080. * @param bone The bone to sync to the impostor.
  95081. * @param boneMesh The mesh that the bone is influencing.
  95082. * @param jointPivot The pivot of the joint / bone in local space.
  95083. * @param distToJoint Optional distance from the impostor to the joint.
  95084. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95085. */
  95086. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95087. var tempVec = PhysicsImpostor._tmpVecs[0];
  95088. var mesh = this.object;
  95089. if (mesh.rotationQuaternion) {
  95090. if (adjustRotation) {
  95091. var tempQuat = PhysicsImpostor._tmpQuat;
  95092. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95093. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95094. }
  95095. else {
  95096. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95097. }
  95098. }
  95099. tempVec.x = 0;
  95100. tempVec.y = 0;
  95101. tempVec.z = 0;
  95102. if (jointPivot) {
  95103. tempVec.x = jointPivot.x;
  95104. tempVec.y = jointPivot.y;
  95105. tempVec.z = jointPivot.z;
  95106. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95107. if (distToJoint === undefined || distToJoint === null) {
  95108. distToJoint = jointPivot.length();
  95109. }
  95110. tempVec.x *= distToJoint;
  95111. tempVec.y *= distToJoint;
  95112. tempVec.z *= distToJoint;
  95113. }
  95114. if (bone.getParent()) {
  95115. tempVec.addInPlace(mesh.getAbsolutePosition());
  95116. bone.setAbsolutePosition(tempVec, boneMesh);
  95117. }
  95118. else {
  95119. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95120. boneMesh.position.x -= tempVec.x;
  95121. boneMesh.position.y -= tempVec.y;
  95122. boneMesh.position.z -= tempVec.z;
  95123. }
  95124. };
  95125. /**
  95126. * Sync impostor to a bone
  95127. * @param bone The bone that the impostor will be synced to.
  95128. * @param boneMesh The mesh that the bone is influencing.
  95129. * @param jointPivot The pivot of the joint / bone in local space.
  95130. * @param distToJoint Optional distance from the impostor to the joint.
  95131. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95132. * @param boneAxis Optional vector3 axis the bone is aligned with
  95133. */
  95134. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95135. var mesh = this.object;
  95136. if (mesh.rotationQuaternion) {
  95137. if (adjustRotation) {
  95138. var tempQuat = PhysicsImpostor._tmpQuat;
  95139. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95140. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95141. }
  95142. else {
  95143. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95144. }
  95145. }
  95146. var pos = PhysicsImpostor._tmpVecs[0];
  95147. var boneDir = PhysicsImpostor._tmpVecs[1];
  95148. if (!boneAxis) {
  95149. boneAxis = PhysicsImpostor._tmpVecs[2];
  95150. boneAxis.x = 0;
  95151. boneAxis.y = 1;
  95152. boneAxis.z = 0;
  95153. }
  95154. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95155. bone.getAbsolutePositionToRef(boneMesh, pos);
  95156. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95157. distToJoint = jointPivot.length();
  95158. }
  95159. if (distToJoint !== undefined && distToJoint !== null) {
  95160. pos.x += boneDir.x * distToJoint;
  95161. pos.y += boneDir.y * distToJoint;
  95162. pos.z += boneDir.z * distToJoint;
  95163. }
  95164. mesh.setAbsolutePosition(pos);
  95165. };
  95166. /**
  95167. * The default object size of the imposter
  95168. */
  95169. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95170. /**
  95171. * The identity quaternion of the imposter
  95172. */
  95173. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95174. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95175. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95176. //Impostor types
  95177. /**
  95178. * No-Imposter type
  95179. */
  95180. PhysicsImpostor.NoImpostor = 0;
  95181. /**
  95182. * Sphere-Imposter type
  95183. */
  95184. PhysicsImpostor.SphereImpostor = 1;
  95185. /**
  95186. * Box-Imposter type
  95187. */
  95188. PhysicsImpostor.BoxImpostor = 2;
  95189. /**
  95190. * Plane-Imposter type
  95191. */
  95192. PhysicsImpostor.PlaneImpostor = 3;
  95193. /**
  95194. * Mesh-imposter type
  95195. */
  95196. PhysicsImpostor.MeshImpostor = 4;
  95197. /**
  95198. * Cylinder-Imposter type
  95199. */
  95200. PhysicsImpostor.CylinderImpostor = 7;
  95201. /**
  95202. * Particle-Imposter type
  95203. */
  95204. PhysicsImpostor.ParticleImpostor = 8;
  95205. /**
  95206. * Heightmap-Imposter type
  95207. */
  95208. PhysicsImpostor.HeightmapImpostor = 9;
  95209. return PhysicsImpostor;
  95210. }());
  95211. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95212. })(BABYLON || (BABYLON = {}));
  95213. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95214. var BABYLON;
  95215. (function (BABYLON) {
  95216. /**
  95217. * Class used to control physics engine
  95218. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95219. */
  95220. var PhysicsEngine = /** @class */ (function () {
  95221. /**
  95222. * Creates a new Physics Engine
  95223. * @param gravity defines the gravity vector used by the simulation
  95224. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95225. */
  95226. function PhysicsEngine(gravity, _physicsPlugin) {
  95227. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95228. this._physicsPlugin = _physicsPlugin;
  95229. this._impostors = [];
  95230. this._joints = [];
  95231. if (!this._physicsPlugin.isSupported()) {
  95232. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95233. + "Please make sure it is included.");
  95234. }
  95235. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95236. this.setGravity(gravity);
  95237. this.setTimeStep();
  95238. }
  95239. /**
  95240. * Sets the gravity vector used by the simulation
  95241. * @param gravity defines the gravity vector to use
  95242. */
  95243. PhysicsEngine.prototype.setGravity = function (gravity) {
  95244. this.gravity = gravity;
  95245. this._physicsPlugin.setGravity(this.gravity);
  95246. };
  95247. /**
  95248. * Set the time step of the physics engine.
  95249. * Default is 1/60.
  95250. * To slow it down, enter 1/600 for example.
  95251. * To speed it up, 1/30
  95252. * @param newTimeStep defines the new timestep to apply to this world.
  95253. */
  95254. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95255. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95256. this._physicsPlugin.setTimeStep(newTimeStep);
  95257. };
  95258. /**
  95259. * Get the time step of the physics engine.
  95260. * @returns the current time step
  95261. */
  95262. PhysicsEngine.prototype.getTimeStep = function () {
  95263. return this._physicsPlugin.getTimeStep();
  95264. };
  95265. /**
  95266. * Release all resources
  95267. */
  95268. PhysicsEngine.prototype.dispose = function () {
  95269. this._impostors.forEach(function (impostor) {
  95270. impostor.dispose();
  95271. });
  95272. this._physicsPlugin.dispose();
  95273. };
  95274. /**
  95275. * Gets the name of the current physics plugin
  95276. * @returns the name of the plugin
  95277. */
  95278. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95279. return this._physicsPlugin.name;
  95280. };
  95281. /**
  95282. * Adding a new impostor for the impostor tracking.
  95283. * This will be done by the impostor itself.
  95284. * @param impostor the impostor to add
  95285. */
  95286. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95287. impostor.uniqueId = this._impostors.push(impostor);
  95288. //if no parent, generate the body
  95289. if (!impostor.parent) {
  95290. this._physicsPlugin.generatePhysicsBody(impostor);
  95291. }
  95292. };
  95293. /**
  95294. * Remove an impostor from the engine.
  95295. * This impostor and its mesh will not longer be updated by the physics engine.
  95296. * @param impostor the impostor to remove
  95297. */
  95298. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95299. var index = this._impostors.indexOf(impostor);
  95300. if (index > -1) {
  95301. var removed = this._impostors.splice(index, 1);
  95302. //Is it needed?
  95303. if (removed.length) {
  95304. //this will also remove it from the world.
  95305. removed[0].physicsBody = null;
  95306. }
  95307. }
  95308. };
  95309. /**
  95310. * Add a joint to the physics engine
  95311. * @param mainImpostor defines the main impostor to which the joint is added.
  95312. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95313. * @param joint defines the joint that will connect both impostors.
  95314. */
  95315. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95316. var impostorJoint = {
  95317. mainImpostor: mainImpostor,
  95318. connectedImpostor: connectedImpostor,
  95319. joint: joint
  95320. };
  95321. joint.physicsPlugin = this._physicsPlugin;
  95322. this._joints.push(impostorJoint);
  95323. this._physicsPlugin.generateJoint(impostorJoint);
  95324. };
  95325. /**
  95326. * Removes a joint from the simulation
  95327. * @param mainImpostor defines the impostor used with the joint
  95328. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95329. * @param joint defines the joint to remove
  95330. */
  95331. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95332. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95333. return (impostorJoint.connectedImpostor === connectedImpostor
  95334. && impostorJoint.joint === joint
  95335. && impostorJoint.mainImpostor === mainImpostor);
  95336. });
  95337. if (matchingJoints.length) {
  95338. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95339. //TODO remove it from the list as well
  95340. }
  95341. };
  95342. /**
  95343. * Called by the scene. No need to call it.
  95344. * @param delta defines the timespam between frames
  95345. */
  95346. PhysicsEngine.prototype._step = function (delta) {
  95347. var _this = this;
  95348. //check if any mesh has no body / requires an update
  95349. this._impostors.forEach(function (impostor) {
  95350. if (impostor.isBodyInitRequired()) {
  95351. _this._physicsPlugin.generatePhysicsBody(impostor);
  95352. }
  95353. });
  95354. if (delta > 0.1) {
  95355. delta = 0.1;
  95356. }
  95357. else if (delta <= 0) {
  95358. delta = 1.0 / 60.0;
  95359. }
  95360. this._physicsPlugin.executeStep(delta, this._impostors);
  95361. };
  95362. /**
  95363. * Gets the current plugin used to run the simulation
  95364. * @returns current plugin
  95365. */
  95366. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95367. return this._physicsPlugin;
  95368. };
  95369. /**
  95370. * Gets the list of physic impostors
  95371. * @returns an array of PhysicsImpostor
  95372. */
  95373. PhysicsEngine.prototype.getImpostors = function () {
  95374. return this._impostors;
  95375. };
  95376. /**
  95377. * Gets the impostor for a physics enabled object
  95378. * @param object defines the object impersonated by the impostor
  95379. * @returns the PhysicsImpostor or null if not found
  95380. */
  95381. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95382. for (var i = 0; i < this._impostors.length; ++i) {
  95383. if (this._impostors[i].object === object) {
  95384. return this._impostors[i];
  95385. }
  95386. }
  95387. return null;
  95388. };
  95389. /**
  95390. * Gets the impostor for a physics body object
  95391. * @param body defines physics body used by the impostor
  95392. * @returns the PhysicsImpostor or null if not found
  95393. */
  95394. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95395. for (var i = 0; i < this._impostors.length; ++i) {
  95396. if (this._impostors[i].physicsBody === body) {
  95397. return this._impostors[i];
  95398. }
  95399. }
  95400. return null;
  95401. };
  95402. /**
  95403. * Global value used to control the smallest number supported by the simulation
  95404. */
  95405. PhysicsEngine.Epsilon = 0.001;
  95406. return PhysicsEngine;
  95407. }());
  95408. BABYLON.PhysicsEngine = PhysicsEngine;
  95409. })(BABYLON || (BABYLON = {}));
  95410. //# sourceMappingURL=babylon.physicsEngine.js.map
  95411. var BABYLON;
  95412. (function (BABYLON) {
  95413. /**
  95414. * A helper for physics simulations
  95415. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95416. */
  95417. var PhysicsHelper = /** @class */ (function () {
  95418. /**
  95419. * Initializes the Physics helper
  95420. * @param scene Babylon.js scene
  95421. */
  95422. function PhysicsHelper(scene) {
  95423. this._scene = scene;
  95424. this._physicsEngine = this._scene.getPhysicsEngine();
  95425. if (!this._physicsEngine) {
  95426. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95427. }
  95428. }
  95429. /**
  95430. * Applies a radial explosion impulse
  95431. * @param origin the origin of the explosion
  95432. * @param radius the explosion radius
  95433. * @param strength the explosion strength
  95434. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95435. * @returns A physics radial explosion event, or null
  95436. */
  95437. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95438. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95439. if (!this._physicsEngine) {
  95440. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95441. return null;
  95442. }
  95443. var impostors = this._physicsEngine.getImpostors();
  95444. if (impostors.length === 0) {
  95445. return null;
  95446. }
  95447. var event = new PhysicsRadialExplosionEvent(this._scene);
  95448. impostors.forEach(function (impostor) {
  95449. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95450. if (!impostorForceAndContactPoint) {
  95451. return;
  95452. }
  95453. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95454. });
  95455. event.dispose(false);
  95456. return event;
  95457. };
  95458. /**
  95459. * Applies a radial explosion force
  95460. * @param origin the origin of the explosion
  95461. * @param radius the explosion radius
  95462. * @param strength the explosion strength
  95463. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95464. * @returns A physics radial explosion event, or null
  95465. */
  95466. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95467. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95468. if (!this._physicsEngine) {
  95469. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95470. return null;
  95471. }
  95472. var impostors = this._physicsEngine.getImpostors();
  95473. if (impostors.length === 0) {
  95474. return null;
  95475. }
  95476. var event = new PhysicsRadialExplosionEvent(this._scene);
  95477. impostors.forEach(function (impostor) {
  95478. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95479. if (!impostorForceAndContactPoint) {
  95480. return;
  95481. }
  95482. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95483. });
  95484. event.dispose(false);
  95485. return event;
  95486. };
  95487. /**
  95488. * Creates a gravitational field
  95489. * @param origin the origin of the explosion
  95490. * @param radius the explosion radius
  95491. * @param strength the explosion strength
  95492. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95493. * @returns A physics gravitational field event, or null
  95494. */
  95495. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95496. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95497. if (!this._physicsEngine) {
  95498. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95499. return null;
  95500. }
  95501. var impostors = this._physicsEngine.getImpostors();
  95502. if (impostors.length === 0) {
  95503. return null;
  95504. }
  95505. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95506. event.dispose(false);
  95507. return event;
  95508. };
  95509. /**
  95510. * Creates a physics updraft event
  95511. * @param origin the origin of the updraft
  95512. * @param radius the radius of the updraft
  95513. * @param strength the strength of the updraft
  95514. * @param height the height of the updraft
  95515. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95516. * @returns A physics updraft event, or null
  95517. */
  95518. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95519. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95520. if (!this._physicsEngine) {
  95521. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95522. return null;
  95523. }
  95524. if (this._physicsEngine.getImpostors().length === 0) {
  95525. return null;
  95526. }
  95527. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95528. event.dispose(false);
  95529. return event;
  95530. };
  95531. /**
  95532. * Creates a physics vortex event
  95533. * @param origin the of the vortex
  95534. * @param radius the radius of the vortex
  95535. * @param strength the strength of the vortex
  95536. * @param height the height of the vortex
  95537. * @returns a Physics vortex event, or null
  95538. * A physics vortex event or null
  95539. */
  95540. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95541. if (!this._physicsEngine) {
  95542. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95543. return null;
  95544. }
  95545. if (this._physicsEngine.getImpostors().length === 0) {
  95546. return null;
  95547. }
  95548. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95549. event.dispose(false);
  95550. return event;
  95551. };
  95552. return PhysicsHelper;
  95553. }());
  95554. BABYLON.PhysicsHelper = PhysicsHelper;
  95555. /**
  95556. * Represents a physics radial explosion event
  95557. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95558. */
  95559. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95560. /**
  95561. * Initializes a radial explosioin event
  95562. * @param scene BabylonJS scene
  95563. */
  95564. function PhysicsRadialExplosionEvent(scene) {
  95565. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95566. this._rays = [];
  95567. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95568. this._scene = scene;
  95569. }
  95570. /**
  95571. * Returns the data related to the radial explosion event (sphere & rays).
  95572. * @returns The radial explosion event data
  95573. */
  95574. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95575. this._dataFetched = true;
  95576. return {
  95577. sphere: this._sphere,
  95578. rays: this._rays,
  95579. };
  95580. };
  95581. /**
  95582. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95583. * @param impostor A physics imposter
  95584. * @param origin the origin of the explosion
  95585. * @param radius the explosion radius
  95586. * @param strength the explosion strength
  95587. * @param falloff possible options: Constant & Linear
  95588. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95589. */
  95590. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95591. if (impostor.mass === 0) {
  95592. return null;
  95593. }
  95594. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95595. return null;
  95596. }
  95597. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95598. return null;
  95599. }
  95600. var impostorObjectCenter = impostor.getObjectCenter();
  95601. var direction = impostorObjectCenter.subtract(origin);
  95602. var ray = new BABYLON.Ray(origin, direction, radius);
  95603. this._rays.push(ray);
  95604. var hit = ray.intersectsMesh(impostor.object);
  95605. var contactPoint = hit.pickedPoint;
  95606. if (!contactPoint) {
  95607. return null;
  95608. }
  95609. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95610. if (distanceFromOrigin > radius) {
  95611. return null;
  95612. }
  95613. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95614. ? strength
  95615. : strength * (1 - (distanceFromOrigin / radius));
  95616. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95617. return { force: force, contactPoint: contactPoint };
  95618. };
  95619. /**
  95620. * Disposes the sphere.
  95621. * @param force Specifies if the sphere should be disposed by force
  95622. */
  95623. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95624. var _this = this;
  95625. if (force === void 0) { force = true; }
  95626. if (force) {
  95627. this._sphere.dispose();
  95628. }
  95629. else {
  95630. setTimeout(function () {
  95631. if (!_this._dataFetched) {
  95632. _this._sphere.dispose();
  95633. }
  95634. }, 0);
  95635. }
  95636. };
  95637. /*** Helpers ***/
  95638. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95639. if (!this._sphere) {
  95640. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95641. this._sphere.isVisible = false;
  95642. }
  95643. };
  95644. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95645. var impostorObject = impostor.object;
  95646. this._prepareSphere();
  95647. this._sphere.position = origin;
  95648. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95649. this._sphere._updateBoundingInfo();
  95650. this._sphere.computeWorldMatrix(true);
  95651. return this._sphere.intersectsMesh(impostorObject, true);
  95652. };
  95653. return PhysicsRadialExplosionEvent;
  95654. }());
  95655. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  95656. /**
  95657. * Represents a gravitational field event
  95658. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95659. */
  95660. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  95661. /**
  95662. * Initializes the physics gravitational field event
  95663. * @param physicsHelper A physics helper
  95664. * @param scene BabylonJS scene
  95665. * @param origin The origin position of the gravitational field event
  95666. * @param radius The radius of the gravitational field event
  95667. * @param strength The strength of the gravitational field event
  95668. * @param falloff The falloff for the gravitational field event
  95669. */
  95670. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  95671. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95672. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95673. this._physicsHelper = physicsHelper;
  95674. this._scene = scene;
  95675. this._origin = origin;
  95676. this._radius = radius;
  95677. this._strength = strength;
  95678. this._falloff = falloff;
  95679. this._tickCallback = this._tick.bind(this);
  95680. }
  95681. /**
  95682. * Returns the data related to the gravitational field event (sphere).
  95683. * @returns A gravitational field event
  95684. */
  95685. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  95686. this._dataFetched = true;
  95687. return {
  95688. sphere: this._sphere,
  95689. };
  95690. };
  95691. /**
  95692. * Enables the gravitational field.
  95693. */
  95694. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  95695. this._tickCallback.call(this);
  95696. this._scene.registerBeforeRender(this._tickCallback);
  95697. };
  95698. /**
  95699. * Disables the gravitational field.
  95700. */
  95701. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  95702. this._scene.unregisterBeforeRender(this._tickCallback);
  95703. };
  95704. /**
  95705. * Disposes the sphere.
  95706. * @param force The force to dispose from the gravitational field event
  95707. */
  95708. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  95709. var _this = this;
  95710. if (force === void 0) { force = true; }
  95711. if (force) {
  95712. this._sphere.dispose();
  95713. }
  95714. else {
  95715. setTimeout(function () {
  95716. if (!_this._dataFetched) {
  95717. _this._sphere.dispose();
  95718. }
  95719. }, 0);
  95720. }
  95721. };
  95722. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  95723. // Since the params won't change, we fetch the event only once
  95724. if (this._sphere) {
  95725. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  95726. }
  95727. else {
  95728. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  95729. if (radialExplosionEvent) {
  95730. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  95731. }
  95732. }
  95733. };
  95734. return PhysicsGravitationalFieldEvent;
  95735. }());
  95736. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  95737. /**
  95738. * Represents a physics updraft event
  95739. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95740. */
  95741. var PhysicsUpdraftEvent = /** @class */ (function () {
  95742. /**
  95743. * Initializes the physics updraft event
  95744. * @param _scene BabylonJS scene
  95745. * @param _origin The origin position of the updraft
  95746. * @param _radius The radius of the updraft
  95747. * @param _strength The strength of the updraft
  95748. * @param _height The height of the updraft
  95749. * @param _updraftMode The mode of the updraft
  95750. */
  95751. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  95752. this._scene = _scene;
  95753. this._origin = _origin;
  95754. this._radius = _radius;
  95755. this._strength = _strength;
  95756. this._height = _height;
  95757. this._updraftMode = _updraftMode;
  95758. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  95759. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  95760. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  95761. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95762. this._physicsEngine = this._scene.getPhysicsEngine();
  95763. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  95764. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  95765. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  95766. this._originDirection = this._origin.subtract(this._originTop).normalize();
  95767. }
  95768. this._tickCallback = this._tick.bind(this);
  95769. }
  95770. /**
  95771. * Returns the data related to the updraft event (cylinder).
  95772. * @returns A physics updraft event
  95773. */
  95774. PhysicsUpdraftEvent.prototype.getData = function () {
  95775. this._dataFetched = true;
  95776. return {
  95777. cylinder: this._cylinder,
  95778. };
  95779. };
  95780. /**
  95781. * Enables the updraft.
  95782. */
  95783. PhysicsUpdraftEvent.prototype.enable = function () {
  95784. this._tickCallback.call(this);
  95785. this._scene.registerBeforeRender(this._tickCallback);
  95786. };
  95787. /**
  95788. * Disables the cortex.
  95789. */
  95790. PhysicsUpdraftEvent.prototype.disable = function () {
  95791. this._scene.unregisterBeforeRender(this._tickCallback);
  95792. };
  95793. /**
  95794. * Disposes the sphere.
  95795. * @param force Specifies if the updraft should be disposed by force
  95796. */
  95797. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  95798. var _this = this;
  95799. if (force === void 0) { force = true; }
  95800. if (force) {
  95801. this._cylinder.dispose();
  95802. }
  95803. else {
  95804. setTimeout(function () {
  95805. if (!_this._dataFetched) {
  95806. _this._cylinder.dispose();
  95807. }
  95808. }, 0);
  95809. }
  95810. };
  95811. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  95812. if (impostor.mass === 0) {
  95813. return null;
  95814. }
  95815. if (!this._intersectsWithCylinder(impostor)) {
  95816. return null;
  95817. }
  95818. var impostorObjectCenter = impostor.getObjectCenter();
  95819. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  95820. var direction = this._originDirection;
  95821. }
  95822. else {
  95823. var direction = impostorObjectCenter.subtract(this._originTop);
  95824. }
  95825. var multiplier = this._strength * -1;
  95826. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95827. return { force: force, contactPoint: impostorObjectCenter };
  95828. };
  95829. PhysicsUpdraftEvent.prototype._tick = function () {
  95830. var _this = this;
  95831. this._physicsEngine.getImpostors().forEach(function (impostor) {
  95832. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  95833. if (!impostorForceAndContactPoint) {
  95834. return;
  95835. }
  95836. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95837. });
  95838. };
  95839. /*** Helpers ***/
  95840. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  95841. if (!this._cylinder) {
  95842. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  95843. height: this._height,
  95844. diameter: this._radius * 2,
  95845. }, this._scene);
  95846. this._cylinder.isVisible = false;
  95847. }
  95848. };
  95849. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  95850. var impostorObject = impostor.object;
  95851. this._prepareCylinder();
  95852. this._cylinder.position = this._cylinderPosition;
  95853. return this._cylinder.intersectsMesh(impostorObject, true);
  95854. };
  95855. return PhysicsUpdraftEvent;
  95856. }());
  95857. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  95858. /**
  95859. * Represents a physics vortex event
  95860. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95861. */
  95862. var PhysicsVortexEvent = /** @class */ (function () {
  95863. /**
  95864. * Initializes the physics vortex event
  95865. * @param _scene The BabylonJS scene
  95866. * @param _origin The origin position of the vortex
  95867. * @param _radius The radius of the vortex
  95868. * @param _strength The strength of the vortex
  95869. * @param _height The height of the vortex
  95870. */
  95871. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  95872. this._scene = _scene;
  95873. this._origin = _origin;
  95874. this._radius = _radius;
  95875. this._strength = _strength;
  95876. this._height = _height;
  95877. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  95878. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  95879. this._updraftMultiplier = 0.02;
  95880. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  95881. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95882. this._physicsEngine = this._scene.getPhysicsEngine();
  95883. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  95884. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  95885. this._tickCallback = this._tick.bind(this);
  95886. }
  95887. /**
  95888. * Returns the data related to the vortex event (cylinder).
  95889. * @returns The physics vortex event data
  95890. */
  95891. PhysicsVortexEvent.prototype.getData = function () {
  95892. this._dataFetched = true;
  95893. return {
  95894. cylinder: this._cylinder,
  95895. };
  95896. };
  95897. /**
  95898. * Enables the vortex.
  95899. */
  95900. PhysicsVortexEvent.prototype.enable = function () {
  95901. this._tickCallback.call(this);
  95902. this._scene.registerBeforeRender(this._tickCallback);
  95903. };
  95904. /**
  95905. * Disables the cortex.
  95906. */
  95907. PhysicsVortexEvent.prototype.disable = function () {
  95908. this._scene.unregisterBeforeRender(this._tickCallback);
  95909. };
  95910. /**
  95911. * Disposes the sphere.
  95912. * @param force
  95913. */
  95914. PhysicsVortexEvent.prototype.dispose = function (force) {
  95915. var _this = this;
  95916. if (force === void 0) { force = true; }
  95917. if (force) {
  95918. this._cylinder.dispose();
  95919. }
  95920. else {
  95921. setTimeout(function () {
  95922. if (!_this._dataFetched) {
  95923. _this._cylinder.dispose();
  95924. }
  95925. }, 0);
  95926. }
  95927. };
  95928. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  95929. if (impostor.mass === 0) {
  95930. return null;
  95931. }
  95932. if (!this._intersectsWithCylinder(impostor)) {
  95933. return null;
  95934. }
  95935. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95936. return null;
  95937. }
  95938. var impostorObjectCenter = impostor.getObjectCenter();
  95939. 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)
  95940. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  95941. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  95942. var hit = ray.intersectsMesh(impostor.object);
  95943. var contactPoint = hit.pickedPoint;
  95944. if (!contactPoint) {
  95945. return null;
  95946. }
  95947. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  95948. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  95949. var directionToOrigin = contactPoint.normalize();
  95950. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  95951. directionToOrigin = directionToOrigin.negate();
  95952. }
  95953. // TODO: find a more physically based solution
  95954. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  95955. var forceX = directionToOrigin.x * this._strength / 8;
  95956. var forceY = directionToOrigin.y * this._updraftMultiplier;
  95957. var forceZ = directionToOrigin.z * this._strength / 8;
  95958. }
  95959. else {
  95960. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  95961. var forceY = this._originTop.y * this._updraftMultiplier;
  95962. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  95963. }
  95964. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  95965. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  95966. return { force: force, contactPoint: impostorObjectCenter };
  95967. };
  95968. PhysicsVortexEvent.prototype._tick = function () {
  95969. var _this = this;
  95970. this._physicsEngine.getImpostors().forEach(function (impostor) {
  95971. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  95972. if (!impostorForceAndContactPoint) {
  95973. return;
  95974. }
  95975. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95976. });
  95977. };
  95978. /*** Helpers ***/
  95979. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  95980. if (!this._cylinder) {
  95981. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  95982. height: this._height,
  95983. diameter: this._radius * 2,
  95984. }, this._scene);
  95985. this._cylinder.isVisible = false;
  95986. }
  95987. };
  95988. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  95989. var impostorObject = impostor.object;
  95990. this._prepareCylinder();
  95991. this._cylinder.position = this._cylinderPosition;
  95992. return this._cylinder.intersectsMesh(impostorObject, true);
  95993. };
  95994. return PhysicsVortexEvent;
  95995. }());
  95996. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  95997. /**
  95998. * The strenght of the force in correspondence to the distance of the affected object
  95999. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96000. */
  96001. var PhysicsRadialImpulseFalloff;
  96002. (function (PhysicsRadialImpulseFalloff) {
  96003. /** Defines that impulse is constant in strength across it's whole radius */
  96004. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  96005. /** DEfines that impulse gets weaker if it's further from the origin */
  96006. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  96007. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  96008. /**
  96009. * The strength of the force in correspondence to the distance of the affected object
  96010. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96011. */
  96012. var PhysicsUpdraftMode;
  96013. (function (PhysicsUpdraftMode) {
  96014. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  96015. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96016. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96017. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96018. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96019. })(BABYLON || (BABYLON = {}));
  96020. //# sourceMappingURL=babylon.physicsHelper.js.map
  96021. var BABYLON;
  96022. (function (BABYLON) {
  96023. /** @hidden */
  96024. var CannonJSPlugin = /** @class */ (function () {
  96025. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96026. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96027. if (iterations === void 0) { iterations = 10; }
  96028. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96029. this.name = "CannonJSPlugin";
  96030. this._physicsMaterials = new Array();
  96031. this._fixedTimeStep = 1 / 60;
  96032. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96033. this.BJSCANNON = CANNON;
  96034. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96035. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96036. this._tmpPosition = BABYLON.Vector3.Zero();
  96037. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96038. this._tmpUnityRotation = new BABYLON.Quaternion();
  96039. if (!this.isSupported()) {
  96040. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96041. return;
  96042. }
  96043. this._extendNamespace();
  96044. this.world = new this.BJSCANNON.World();
  96045. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96046. this.world.solver.iterations = iterations;
  96047. }
  96048. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96049. this.world.gravity.copy(gravity);
  96050. };
  96051. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96052. this._fixedTimeStep = timeStep;
  96053. };
  96054. CannonJSPlugin.prototype.getTimeStep = function () {
  96055. return this._fixedTimeStep;
  96056. };
  96057. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96058. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96059. };
  96060. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96061. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96062. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96063. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96064. };
  96065. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96066. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96067. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96068. impostor.physicsBody.applyForce(impulse, worldPoint);
  96069. };
  96070. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96071. //parent-child relationship. Does this impostor has a parent impostor?
  96072. if (impostor.parent) {
  96073. if (impostor.physicsBody) {
  96074. this.removePhysicsBody(impostor);
  96075. //TODO is that needed?
  96076. impostor.forceUpdate();
  96077. }
  96078. return;
  96079. }
  96080. //should a new body be created for this impostor?
  96081. if (impostor.isBodyInitRequired()) {
  96082. var shape = this._createShape(impostor);
  96083. //unregister events, if body is being changed
  96084. var oldBody = impostor.physicsBody;
  96085. if (oldBody) {
  96086. this.removePhysicsBody(impostor);
  96087. }
  96088. //create the body and material
  96089. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96090. var bodyCreationObject = {
  96091. mass: impostor.getParam("mass"),
  96092. material: material
  96093. };
  96094. // A simple extend, in case native options were used.
  96095. var nativeOptions = impostor.getParam("nativeOptions");
  96096. for (var key in nativeOptions) {
  96097. if (nativeOptions.hasOwnProperty(key)) {
  96098. bodyCreationObject[key] = nativeOptions[key];
  96099. }
  96100. }
  96101. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96102. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96103. this.world.addEventListener("preStep", impostor.beforeStep);
  96104. this.world.addEventListener("postStep", impostor.afterStep);
  96105. impostor.physicsBody.addShape(shape);
  96106. this.world.add(impostor.physicsBody);
  96107. //try to keep the body moving in the right direction by taking old properties.
  96108. //Should be tested!
  96109. if (oldBody) {
  96110. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96111. impostor.physicsBody[param].copy(oldBody[param]);
  96112. });
  96113. }
  96114. this._processChildMeshes(impostor);
  96115. }
  96116. //now update the body's transformation
  96117. this._updatePhysicsBodyTransformation(impostor);
  96118. };
  96119. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96120. var _this = this;
  96121. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96122. var currentRotation = mainImpostor.object.rotationQuaternion;
  96123. if (meshChildren.length) {
  96124. var processMesh = function (localPosition, mesh) {
  96125. if (!currentRotation || !mesh.rotationQuaternion) {
  96126. return;
  96127. }
  96128. var childImpostor = mesh.getPhysicsImpostor();
  96129. if (childImpostor) {
  96130. var parent = childImpostor.parent;
  96131. if (parent !== mainImpostor) {
  96132. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96133. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96134. if (childImpostor.physicsBody) {
  96135. _this.removePhysicsBody(childImpostor);
  96136. childImpostor.physicsBody = null;
  96137. }
  96138. childImpostor.parent = mainImpostor;
  96139. childImpostor.resetUpdateFlags();
  96140. 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));
  96141. //Add the mass of the children.
  96142. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96143. }
  96144. }
  96145. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96146. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96147. };
  96148. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96149. }
  96150. };
  96151. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96152. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96153. this.world.removeEventListener("preStep", impostor.beforeStep);
  96154. this.world.removeEventListener("postStep", impostor.afterStep);
  96155. this.world.remove(impostor.physicsBody);
  96156. };
  96157. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96158. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96159. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96160. if (!mainBody || !connectedBody) {
  96161. return;
  96162. }
  96163. var constraint;
  96164. var jointData = impostorJoint.joint.jointData;
  96165. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96166. var constraintData = {
  96167. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96168. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96169. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96170. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96171. maxForce: jointData.nativeParams.maxForce,
  96172. collideConnected: !!jointData.collision
  96173. };
  96174. switch (impostorJoint.joint.type) {
  96175. case BABYLON.PhysicsJoint.HingeJoint:
  96176. case BABYLON.PhysicsJoint.Hinge2Joint:
  96177. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96178. break;
  96179. case BABYLON.PhysicsJoint.DistanceJoint:
  96180. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96181. break;
  96182. case BABYLON.PhysicsJoint.SpringJoint:
  96183. var springData = jointData;
  96184. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96185. restLength: springData.length,
  96186. stiffness: springData.stiffness,
  96187. damping: springData.damping,
  96188. localAnchorA: constraintData.pivotA,
  96189. localAnchorB: constraintData.pivotB
  96190. });
  96191. break;
  96192. case BABYLON.PhysicsJoint.LockJoint:
  96193. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96194. break;
  96195. case BABYLON.PhysicsJoint.PointToPointJoint:
  96196. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96197. default:
  96198. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96199. break;
  96200. }
  96201. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96202. constraint.collideConnected = !!jointData.collision;
  96203. impostorJoint.joint.physicsJoint = constraint;
  96204. //don't add spring as constraint, as it is not one.
  96205. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96206. this.world.addConstraint(constraint);
  96207. }
  96208. else {
  96209. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96210. constraint.applyForce();
  96211. };
  96212. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96213. }
  96214. };
  96215. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96216. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96217. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96218. }
  96219. else {
  96220. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96221. }
  96222. };
  96223. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96224. var index;
  96225. var mat;
  96226. for (index = 0; index < this._physicsMaterials.length; index++) {
  96227. mat = this._physicsMaterials[index];
  96228. if (mat.friction === friction && mat.restitution === restitution) {
  96229. return mat;
  96230. }
  96231. }
  96232. var currentMat = new this.BJSCANNON.Material(name);
  96233. currentMat.friction = friction;
  96234. currentMat.restitution = restitution;
  96235. this._physicsMaterials.push(currentMat);
  96236. return currentMat;
  96237. };
  96238. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96239. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96240. };
  96241. CannonJSPlugin.prototype._createShape = function (impostor) {
  96242. var object = impostor.object;
  96243. var returnValue;
  96244. var extendSize = impostor.getObjectExtendSize();
  96245. switch (impostor.type) {
  96246. case BABYLON.PhysicsImpostor.SphereImpostor:
  96247. var radiusX = extendSize.x;
  96248. var radiusY = extendSize.y;
  96249. var radiusZ = extendSize.z;
  96250. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96251. break;
  96252. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96253. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96254. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96255. break;
  96256. case BABYLON.PhysicsImpostor.BoxImpostor:
  96257. var box = extendSize.scale(0.5);
  96258. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96259. break;
  96260. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96261. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96262. returnValue = new this.BJSCANNON.Plane();
  96263. break;
  96264. case BABYLON.PhysicsImpostor.MeshImpostor:
  96265. // should transform the vertex data to world coordinates!!
  96266. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96267. var rawFaces = object.getIndices ? object.getIndices() : [];
  96268. if (!rawVerts)
  96269. return;
  96270. // get only scale! so the object could transform correctly.
  96271. var oldPosition = object.position.clone();
  96272. var oldRotation = object.rotation && object.rotation.clone();
  96273. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96274. object.position.copyFromFloats(0, 0, 0);
  96275. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96276. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96277. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96278. var transform = object.computeWorldMatrix(true);
  96279. // convert rawVerts to object space
  96280. var temp = new Array();
  96281. var index;
  96282. for (index = 0; index < rawVerts.length; index += 3) {
  96283. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96284. }
  96285. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96286. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96287. //now set back the transformation!
  96288. object.position.copyFrom(oldPosition);
  96289. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96290. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96291. break;
  96292. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96293. var oldPosition2 = object.position.clone();
  96294. var oldRotation2 = object.rotation && object.rotation.clone();
  96295. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96296. object.position.copyFromFloats(0, 0, 0);
  96297. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96298. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96299. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96300. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96301. returnValue = this._createHeightmap(object);
  96302. object.position.copyFrom(oldPosition2);
  96303. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96304. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96305. object.computeWorldMatrix(true);
  96306. break;
  96307. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96308. returnValue = new this.BJSCANNON.Particle();
  96309. break;
  96310. }
  96311. return returnValue;
  96312. };
  96313. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96314. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96315. var transform = object.computeWorldMatrix(true);
  96316. // convert rawVerts to object space
  96317. var temp = new Array();
  96318. var index;
  96319. for (index = 0; index < pos.length; index += 3) {
  96320. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96321. }
  96322. pos = temp;
  96323. var matrix = new Array();
  96324. //For now pointDepth will not be used and will be automatically calculated.
  96325. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96326. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96327. var boundingInfo = object.getBoundingInfo();
  96328. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96329. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96330. var elementSize = dim * 2 / arraySize;
  96331. for (var i = 0; i < pos.length; i = i + 3) {
  96332. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96333. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96334. var y = -pos[i + 2] + minY;
  96335. if (!matrix[x]) {
  96336. matrix[x] = [];
  96337. }
  96338. if (!matrix[x][z]) {
  96339. matrix[x][z] = y;
  96340. }
  96341. matrix[x][z] = Math.max(y, matrix[x][z]);
  96342. }
  96343. for (var x = 0; x <= arraySize; ++x) {
  96344. if (!matrix[x]) {
  96345. var loc = 1;
  96346. while (!matrix[(x + loc) % arraySize]) {
  96347. loc++;
  96348. }
  96349. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96350. //console.log("missing x", x);
  96351. }
  96352. for (var z = 0; z <= arraySize; ++z) {
  96353. if (!matrix[x][z]) {
  96354. var loc = 1;
  96355. var newValue;
  96356. while (newValue === undefined) {
  96357. newValue = matrix[x][(z + loc++) % arraySize];
  96358. }
  96359. matrix[x][z] = newValue;
  96360. }
  96361. }
  96362. }
  96363. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96364. elementSize: elementSize
  96365. });
  96366. //For future reference, needed for body transformation
  96367. shape.minY = minY;
  96368. return shape;
  96369. };
  96370. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96371. var object = impostor.object;
  96372. //make sure it is updated...
  96373. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96374. // The delta between the mesh position and the mesh bounding box center
  96375. var bInfo = object.getBoundingInfo();
  96376. if (!bInfo)
  96377. return;
  96378. var center = impostor.getObjectCenter();
  96379. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96380. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96381. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96382. this._tmpPosition.copyFrom(center);
  96383. var quaternion = object.rotationQuaternion;
  96384. if (!quaternion) {
  96385. return;
  96386. }
  96387. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96388. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96389. //-90 DEG in X, precalculated
  96390. quaternion = quaternion.multiply(this._minus90X);
  96391. //Invert! (Precalculated, 90 deg in X)
  96392. //No need to clone. this will never change.
  96393. impostor.setDeltaRotation(this._plus90X);
  96394. }
  96395. //If it is a heightfield, if should be centered.
  96396. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96397. var mesh = object;
  96398. var boundingInfo = mesh.getBoundingInfo();
  96399. //calculate the correct body position:
  96400. var rotationQuaternion = mesh.rotationQuaternion;
  96401. mesh.rotationQuaternion = this._tmpUnityRotation;
  96402. mesh.computeWorldMatrix(true);
  96403. //get original center with no rotation
  96404. var c = center.clone();
  96405. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96406. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96407. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96408. mesh.setPreTransformMatrix(p);
  96409. mesh.computeWorldMatrix(true);
  96410. //calculate the translation
  96411. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96412. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96413. //add it inverted to the delta
  96414. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96415. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96416. //rotation is back
  96417. mesh.rotationQuaternion = rotationQuaternion;
  96418. mesh.setPreTransformMatrix(oldPivot);
  96419. mesh.computeWorldMatrix(true);
  96420. }
  96421. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96422. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96423. //this._tmpPosition.copyFrom(object.position);
  96424. }
  96425. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96426. //Now update the impostor object
  96427. impostor.physicsBody.position.copy(this._tmpPosition);
  96428. impostor.physicsBody.quaternion.copy(quaternion);
  96429. };
  96430. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96431. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96432. if (impostor.object.rotationQuaternion) {
  96433. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96434. }
  96435. };
  96436. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96437. impostor.physicsBody.position.copy(newPosition);
  96438. impostor.physicsBody.quaternion.copy(newRotation);
  96439. };
  96440. CannonJSPlugin.prototype.isSupported = function () {
  96441. return this.BJSCANNON !== undefined;
  96442. };
  96443. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96444. impostor.physicsBody.velocity.copy(velocity);
  96445. };
  96446. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96447. impostor.physicsBody.angularVelocity.copy(velocity);
  96448. };
  96449. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96450. var v = impostor.physicsBody.velocity;
  96451. if (!v) {
  96452. return null;
  96453. }
  96454. return new BABYLON.Vector3(v.x, v.y, v.z);
  96455. };
  96456. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96457. var v = impostor.physicsBody.angularVelocity;
  96458. if (!v) {
  96459. return null;
  96460. }
  96461. return new BABYLON.Vector3(v.x, v.y, v.z);
  96462. };
  96463. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96464. impostor.physicsBody.mass = mass;
  96465. impostor.physicsBody.updateMassProperties();
  96466. };
  96467. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96468. return impostor.physicsBody.mass;
  96469. };
  96470. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96471. return impostor.physicsBody.material.friction;
  96472. };
  96473. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96474. impostor.physicsBody.material.friction = friction;
  96475. };
  96476. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96477. return impostor.physicsBody.material.restitution;
  96478. };
  96479. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96480. impostor.physicsBody.material.restitution = restitution;
  96481. };
  96482. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96483. impostor.physicsBody.sleep();
  96484. };
  96485. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96486. impostor.physicsBody.wakeUp();
  96487. };
  96488. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96489. joint.physicsJoint.distance = maxDistance;
  96490. };
  96491. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96492. // if (!motorIndex) {
  96493. // joint.physicsJoint.enableMotor();
  96494. // }
  96495. // }
  96496. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96497. // if (!motorIndex) {
  96498. // joint.physicsJoint.disableMotor();
  96499. // }
  96500. // }
  96501. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96502. if (!motorIndex) {
  96503. joint.physicsJoint.enableMotor();
  96504. joint.physicsJoint.setMotorSpeed(speed);
  96505. if (maxForce) {
  96506. this.setLimit(joint, maxForce);
  96507. }
  96508. }
  96509. };
  96510. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96511. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96512. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96513. };
  96514. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96515. var body = impostor.physicsBody;
  96516. mesh.position.x = body.position.x;
  96517. mesh.position.y = body.position.y;
  96518. mesh.position.z = body.position.z;
  96519. if (mesh.rotationQuaternion) {
  96520. mesh.rotationQuaternion.x = body.quaternion.x;
  96521. mesh.rotationQuaternion.y = body.quaternion.y;
  96522. mesh.rotationQuaternion.z = body.quaternion.z;
  96523. mesh.rotationQuaternion.w = body.quaternion.w;
  96524. }
  96525. };
  96526. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96527. var shape = impostor.physicsBody.shapes[0];
  96528. return shape.boundingSphereRadius;
  96529. };
  96530. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96531. var shape = impostor.physicsBody.shapes[0];
  96532. result.x = shape.halfExtents.x * 2;
  96533. result.y = shape.halfExtents.y * 2;
  96534. result.z = shape.halfExtents.z * 2;
  96535. };
  96536. CannonJSPlugin.prototype.dispose = function () {
  96537. };
  96538. CannonJSPlugin.prototype._extendNamespace = function () {
  96539. //this will force cannon to execute at least one step when using interpolation
  96540. var step_tmp1 = new this.BJSCANNON.Vec3();
  96541. var Engine = this.BJSCANNON;
  96542. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96543. maxSubSteps = maxSubSteps || 10;
  96544. timeSinceLastCalled = timeSinceLastCalled || 0;
  96545. if (timeSinceLastCalled === 0) {
  96546. this.internalStep(dt);
  96547. this.time += dt;
  96548. }
  96549. else {
  96550. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96551. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96552. var t0 = performance.now();
  96553. for (var i = 0; i !== internalSteps; i++) {
  96554. this.internalStep(dt);
  96555. if (performance.now() - t0 > dt * 1000) {
  96556. break;
  96557. }
  96558. }
  96559. this.time += timeSinceLastCalled;
  96560. var h = this.time % dt;
  96561. var h_div_dt = h / dt;
  96562. var interpvelo = step_tmp1;
  96563. var bodies = this.bodies;
  96564. for (var j = 0; j !== bodies.length; j++) {
  96565. var b = bodies[j];
  96566. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96567. b.position.vsub(b.previousPosition, interpvelo);
  96568. interpvelo.scale(h_div_dt, interpvelo);
  96569. b.position.vadd(interpvelo, b.interpolatedPosition);
  96570. }
  96571. else {
  96572. b.interpolatedPosition.copy(b.position);
  96573. b.interpolatedQuaternion.copy(b.quaternion);
  96574. }
  96575. }
  96576. }
  96577. };
  96578. };
  96579. return CannonJSPlugin;
  96580. }());
  96581. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96582. })(BABYLON || (BABYLON = {}));
  96583. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96584. var BABYLON;
  96585. (function (BABYLON) {
  96586. /** @hidden */
  96587. var OimoJSPlugin = /** @class */ (function () {
  96588. function OimoJSPlugin(iterations) {
  96589. this.name = "OimoJSPlugin";
  96590. this._tmpImpostorsArray = [];
  96591. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96592. this.BJSOIMO = OIMO;
  96593. this.world = new this.BJSOIMO.World({
  96594. iterations: iterations
  96595. });
  96596. this.world.clear();
  96597. }
  96598. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96599. this.world.gravity.copy(gravity);
  96600. };
  96601. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96602. this.world.timeStep = timeStep;
  96603. };
  96604. OimoJSPlugin.prototype.getTimeStep = function () {
  96605. return this.world.timeStep;
  96606. };
  96607. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96608. var _this = this;
  96609. impostors.forEach(function (impostor) {
  96610. impostor.beforeStep();
  96611. });
  96612. this.world.step();
  96613. impostors.forEach(function (impostor) {
  96614. impostor.afterStep();
  96615. //update the ordered impostors array
  96616. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96617. });
  96618. //check for collisions
  96619. var contact = this.world.contacts;
  96620. while (contact !== null) {
  96621. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96622. contact = contact.next;
  96623. continue;
  96624. }
  96625. //is this body colliding with any other? get the impostor
  96626. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96627. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96628. if (!mainImpostor || !collidingImpostor) {
  96629. contact = contact.next;
  96630. continue;
  96631. }
  96632. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96633. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96634. contact = contact.next;
  96635. }
  96636. };
  96637. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96638. var mass = impostor.physicsBody.mass;
  96639. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96640. };
  96641. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96642. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96643. this.applyImpulse(impostor, force, contactPoint);
  96644. };
  96645. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96646. var _this = this;
  96647. //parent-child relationship. Does this impostor has a parent impostor?
  96648. if (impostor.parent) {
  96649. if (impostor.physicsBody) {
  96650. this.removePhysicsBody(impostor);
  96651. //TODO is that needed?
  96652. impostor.forceUpdate();
  96653. }
  96654. return;
  96655. }
  96656. if (impostor.isBodyInitRequired()) {
  96657. var bodyConfig = {
  96658. name: impostor.uniqueId,
  96659. //Oimo must have mass, also for static objects.
  96660. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  96661. size: [],
  96662. type: [],
  96663. pos: [],
  96664. posShape: [],
  96665. rot: [],
  96666. rotShape: [],
  96667. move: impostor.getParam("mass") !== 0,
  96668. density: impostor.getParam("mass"),
  96669. friction: impostor.getParam("friction"),
  96670. restitution: impostor.getParam("restitution"),
  96671. //Supporting older versions of Oimo
  96672. world: this.world
  96673. };
  96674. var impostors = [impostor];
  96675. var addToArray = function (parent) {
  96676. if (!parent.getChildMeshes)
  96677. return;
  96678. parent.getChildMeshes().forEach(function (m) {
  96679. if (m.physicsImpostor) {
  96680. impostors.push(m.physicsImpostor);
  96681. //m.physicsImpostor._init();
  96682. }
  96683. });
  96684. };
  96685. addToArray(impostor.object);
  96686. var checkWithEpsilon_1 = function (value) {
  96687. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  96688. };
  96689. var globalQuaternion_1 = new BABYLON.Quaternion();
  96690. impostors.forEach(function (i) {
  96691. if (!i.object.rotationQuaternion) {
  96692. return;
  96693. }
  96694. //get the correct bounding box
  96695. var oldQuaternion = i.object.rotationQuaternion;
  96696. globalQuaternion_1 = oldQuaternion.clone();
  96697. var rot = oldQuaternion.toEulerAngles();
  96698. var extendSize = i.getObjectExtendSize();
  96699. var radToDeg = 57.295779513082320876;
  96700. if (i === impostor) {
  96701. var center = impostor.getObjectCenter();
  96702. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  96703. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  96704. //Can also use Array.prototype.push.apply
  96705. bodyConfig.pos.push(center.x);
  96706. bodyConfig.pos.push(center.y);
  96707. bodyConfig.pos.push(center.z);
  96708. bodyConfig.posShape.push(0, 0, 0);
  96709. //tmp solution
  96710. bodyConfig.rot.push(0);
  96711. bodyConfig.rot.push(0);
  96712. bodyConfig.rot.push(0);
  96713. bodyConfig.rotShape.push(0, 0, 0);
  96714. }
  96715. else {
  96716. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  96717. bodyConfig.posShape.push(localPosition.x);
  96718. bodyConfig.posShape.push(localPosition.y);
  96719. bodyConfig.posShape.push(localPosition.z);
  96720. bodyConfig.pos.push(0, 0, 0);
  96721. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  96722. bodyConfig.rot.push(0);
  96723. bodyConfig.rot.push(0);
  96724. bodyConfig.rot.push(0);
  96725. bodyConfig.rotShape.push(rot.x * radToDeg);
  96726. bodyConfig.rotShape.push(rot.y * radToDeg);
  96727. bodyConfig.rotShape.push(rot.z * radToDeg);
  96728. }
  96729. // register mesh
  96730. switch (i.type) {
  96731. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96732. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  96733. case BABYLON.PhysicsImpostor.SphereImpostor:
  96734. var radiusX = extendSize.x;
  96735. var radiusY = extendSize.y;
  96736. var radiusZ = extendSize.z;
  96737. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  96738. bodyConfig.type.push('sphere');
  96739. //due to the way oimo works with compounds, add 3 times
  96740. bodyConfig.size.push(size);
  96741. bodyConfig.size.push(size);
  96742. bodyConfig.size.push(size);
  96743. break;
  96744. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96745. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  96746. var sizeY = checkWithEpsilon_1(extendSize.y);
  96747. bodyConfig.type.push('cylinder');
  96748. bodyConfig.size.push(sizeX);
  96749. bodyConfig.size.push(sizeY);
  96750. //due to the way oimo works with compounds, add one more value.
  96751. bodyConfig.size.push(sizeY);
  96752. break;
  96753. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96754. case BABYLON.PhysicsImpostor.BoxImpostor:
  96755. default:
  96756. var sizeX = checkWithEpsilon_1(extendSize.x);
  96757. var sizeY = checkWithEpsilon_1(extendSize.y);
  96758. var sizeZ = checkWithEpsilon_1(extendSize.z);
  96759. bodyConfig.type.push('box');
  96760. //if (i === impostor) {
  96761. bodyConfig.size.push(sizeX);
  96762. bodyConfig.size.push(sizeY);
  96763. bodyConfig.size.push(sizeZ);
  96764. //} else {
  96765. // bodyConfig.size.push(0,0,0);
  96766. //}
  96767. break;
  96768. }
  96769. //actually not needed, but hey...
  96770. i.object.rotationQuaternion = oldQuaternion;
  96771. });
  96772. impostor.physicsBody = this.world.add(bodyConfig);
  96773. // set the quaternion, ignoring the previously defined (euler) rotation
  96774. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  96775. // update with delta 0, so the body will reveive the new rotation.
  96776. impostor.physicsBody.updatePosition(0);
  96777. }
  96778. else {
  96779. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  96780. }
  96781. impostor.setDeltaPosition(this._tmpPositionVector);
  96782. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  96783. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  96784. };
  96785. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96786. //impostor.physicsBody.dispose();
  96787. //Same as : (older oimo versions)
  96788. this.world.removeRigidBody(impostor.physicsBody);
  96789. };
  96790. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96791. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96792. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96793. if (!mainBody || !connectedBody) {
  96794. return;
  96795. }
  96796. var jointData = impostorJoint.joint.jointData;
  96797. var options = jointData.nativeParams || {};
  96798. var type;
  96799. var nativeJointData = {
  96800. body1: mainBody,
  96801. body2: connectedBody,
  96802. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  96803. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  96804. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  96805. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  96806. min: options.min,
  96807. max: options.max,
  96808. collision: options.collision || jointData.collision,
  96809. spring: options.spring,
  96810. //supporting older version of Oimo
  96811. world: this.world
  96812. };
  96813. switch (impostorJoint.joint.type) {
  96814. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96815. type = "jointBall";
  96816. break;
  96817. case BABYLON.PhysicsJoint.SpringJoint:
  96818. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  96819. var springData = jointData;
  96820. nativeJointData.min = springData.length || nativeJointData.min;
  96821. //Max should also be set, just make sure it is at least min
  96822. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  96823. case BABYLON.PhysicsJoint.DistanceJoint:
  96824. type = "jointDistance";
  96825. nativeJointData.max = jointData.maxDistance;
  96826. break;
  96827. case BABYLON.PhysicsJoint.PrismaticJoint:
  96828. type = "jointPrisme";
  96829. break;
  96830. case BABYLON.PhysicsJoint.SliderJoint:
  96831. type = "jointSlide";
  96832. break;
  96833. case BABYLON.PhysicsJoint.WheelJoint:
  96834. type = "jointWheel";
  96835. break;
  96836. case BABYLON.PhysicsJoint.HingeJoint:
  96837. default:
  96838. type = "jointHinge";
  96839. break;
  96840. }
  96841. nativeJointData.type = type;
  96842. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  96843. };
  96844. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96845. //Bug in Oimo prevents us from disposing a joint in the playground
  96846. //joint.joint.physicsJoint.dispose();
  96847. //So we will bruteforce it!
  96848. try {
  96849. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  96850. }
  96851. catch (e) {
  96852. BABYLON.Tools.Warn(e);
  96853. }
  96854. };
  96855. OimoJSPlugin.prototype.isSupported = function () {
  96856. return this.BJSOIMO !== undefined;
  96857. };
  96858. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96859. if (!impostor.physicsBody.sleeping) {
  96860. //TODO check that
  96861. /*if (impostor.physicsBody.shapes.next) {
  96862. var parentShape = this._getLastShape(impostor.physicsBody);
  96863. impostor.object.position.copyFrom(parentShape.position);
  96864. console.log(parentShape.position);
  96865. } else {*/
  96866. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  96867. //}
  96868. if (impostor.object.rotationQuaternion) {
  96869. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  96870. }
  96871. }
  96872. };
  96873. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96874. var body = impostor.physicsBody;
  96875. body.position.copy(newPosition);
  96876. body.orientation.copy(newRotation);
  96877. body.syncShapes();
  96878. body.awake();
  96879. };
  96880. /*private _getLastShape(body: any): any {
  96881. var lastShape = body.shapes;
  96882. while (lastShape.next) {
  96883. lastShape = lastShape.next;
  96884. }
  96885. return lastShape;
  96886. }*/
  96887. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96888. impostor.physicsBody.linearVelocity.copy(velocity);
  96889. };
  96890. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96891. impostor.physicsBody.angularVelocity.copy(velocity);
  96892. };
  96893. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96894. var v = impostor.physicsBody.linearVelocity;
  96895. if (!v) {
  96896. return null;
  96897. }
  96898. return new BABYLON.Vector3(v.x, v.y, v.z);
  96899. };
  96900. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96901. var v = impostor.physicsBody.angularVelocity;
  96902. if (!v) {
  96903. return null;
  96904. }
  96905. return new BABYLON.Vector3(v.x, v.y, v.z);
  96906. };
  96907. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96908. var staticBody = mass === 0;
  96909. //this will actually set the body's density and not its mass.
  96910. //But this is how oimo treats the mass variable.
  96911. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  96912. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  96913. };
  96914. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  96915. return impostor.physicsBody.shapes.density;
  96916. };
  96917. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  96918. return impostor.physicsBody.shapes.friction;
  96919. };
  96920. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96921. impostor.physicsBody.shapes.friction = friction;
  96922. };
  96923. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96924. return impostor.physicsBody.shapes.restitution;
  96925. };
  96926. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96927. impostor.physicsBody.shapes.restitution = restitution;
  96928. };
  96929. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  96930. impostor.physicsBody.sleep();
  96931. };
  96932. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  96933. impostor.physicsBody.awake();
  96934. };
  96935. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96936. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  96937. if (minDistance !== void 0) {
  96938. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  96939. }
  96940. };
  96941. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96942. //TODO separate rotational and transational motors.
  96943. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  96944. if (motor) {
  96945. motor.setMotor(speed, maxForce);
  96946. }
  96947. };
  96948. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  96949. //TODO separate rotational and transational motors.
  96950. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  96951. if (motor) {
  96952. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  96953. }
  96954. };
  96955. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96956. var body = impostor.physicsBody;
  96957. mesh.position.x = body.position.x;
  96958. mesh.position.y = body.position.y;
  96959. mesh.position.z = body.position.z;
  96960. if (mesh.rotationQuaternion) {
  96961. mesh.rotationQuaternion.x = body.orientation.x;
  96962. mesh.rotationQuaternion.y = body.orientation.y;
  96963. mesh.rotationQuaternion.z = body.orientation.z;
  96964. mesh.rotationQuaternion.w = body.orientation.s;
  96965. }
  96966. };
  96967. OimoJSPlugin.prototype.getRadius = function (impostor) {
  96968. return impostor.physicsBody.shapes.radius;
  96969. };
  96970. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96971. var shape = impostor.physicsBody.shapes;
  96972. result.x = shape.halfWidth * 2;
  96973. result.y = shape.halfHeight * 2;
  96974. result.z = shape.halfDepth * 2;
  96975. };
  96976. OimoJSPlugin.prototype.dispose = function () {
  96977. this.world.clear();
  96978. };
  96979. return OimoJSPlugin;
  96980. }());
  96981. BABYLON.OimoJSPlugin = OimoJSPlugin;
  96982. })(BABYLON || (BABYLON = {}));
  96983. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  96984. var BABYLON;
  96985. (function (BABYLON) {
  96986. /**
  96987. * Gets the current physics engine
  96988. * @returns a IPhysicsEngine or null if none attached
  96989. */
  96990. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  96991. return this._physicsEngine;
  96992. };
  96993. /**
  96994. * Enables physics to the current scene
  96995. * @param gravity defines the scene's gravity for the physics engine
  96996. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  96997. * @return a boolean indicating if the physics engine was initialized
  96998. */
  96999. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  97000. if (gravity === void 0) { gravity = null; }
  97001. if (this._physicsEngine) {
  97002. return true;
  97003. }
  97004. // Register the component to the scene
  97005. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  97006. if (!component) {
  97007. component = new PhysicsEngineSceneComponent(this);
  97008. this._addComponent(component);
  97009. }
  97010. try {
  97011. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  97012. return true;
  97013. }
  97014. catch (e) {
  97015. BABYLON.Tools.Error(e.message);
  97016. return false;
  97017. }
  97018. };
  97019. /**
  97020. * Disables and disposes the physics engine associated with the scene
  97021. */
  97022. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97023. if (!this._physicsEngine) {
  97024. return;
  97025. }
  97026. this._physicsEngine.dispose();
  97027. this._physicsEngine = null;
  97028. };
  97029. /**
  97030. * Gets a boolean indicating if there is an active physics engine
  97031. * @returns a boolean indicating if there is an active physics engine
  97032. */
  97033. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97034. return this._physicsEngine !== undefined;
  97035. };
  97036. /**
  97037. * Deletes a physics compound impostor
  97038. * @param compound defines the compound to delete
  97039. */
  97040. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97041. var mesh = compound.parts[0].mesh;
  97042. if (mesh.physicsImpostor) {
  97043. mesh.physicsImpostor.dispose( /*true*/);
  97044. mesh.physicsImpostor = null;
  97045. }
  97046. };
  97047. /** @hidden */
  97048. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97049. if (this._physicsEngine) {
  97050. this.onBeforePhysicsObservable.notifyObservers(this);
  97051. this._physicsEngine._step(step / 1000);
  97052. this.onAfterPhysicsObservable.notifyObservers(this);
  97053. }
  97054. };
  97055. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97056. get: function () {
  97057. return this._physicsImpostor;
  97058. },
  97059. set: function (value) {
  97060. var _this = this;
  97061. if (this._physicsImpostor === value) {
  97062. return;
  97063. }
  97064. if (this._disposePhysicsObserver) {
  97065. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97066. }
  97067. this._physicsImpostor = value;
  97068. if (value) {
  97069. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97070. // Physics
  97071. if (_this.physicsImpostor) {
  97072. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97073. _this.physicsImpostor = null;
  97074. }
  97075. });
  97076. }
  97077. },
  97078. enumerable: true,
  97079. configurable: true
  97080. });
  97081. /**
  97082. * Gets the current physics impostor
  97083. * @see http://doc.babylonjs.com/features/physics_engine
  97084. * @returns a physics impostor or null
  97085. */
  97086. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97087. return this.physicsImpostor;
  97088. };
  97089. /**
  97090. * Apply a physic impulse to the mesh
  97091. * @param force defines the force to apply
  97092. * @param contactPoint defines where to apply the force
  97093. * @returns the current mesh
  97094. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97095. */
  97096. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97097. if (!this.physicsImpostor) {
  97098. return this;
  97099. }
  97100. this.physicsImpostor.applyImpulse(force, contactPoint);
  97101. return this;
  97102. };
  97103. /**
  97104. * Creates a physic joint between two meshes
  97105. * @param otherMesh defines the other mesh to use
  97106. * @param pivot1 defines the pivot to use on this mesh
  97107. * @param pivot2 defines the pivot to use on the other mesh
  97108. * @param options defines additional options (can be plugin dependent)
  97109. * @returns the current mesh
  97110. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97111. */
  97112. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97113. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97114. return this;
  97115. }
  97116. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97117. mainPivot: pivot1,
  97118. connectedPivot: pivot2,
  97119. nativeParams: options
  97120. });
  97121. return this;
  97122. };
  97123. /**
  97124. * Defines the physics engine scene component responsible to manage a physics engine
  97125. */
  97126. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97127. /**
  97128. * Creates a new instance of the component for the given scene
  97129. * @param scene Defines the scene to register the component in
  97130. */
  97131. function PhysicsEngineSceneComponent(scene) {
  97132. var _this = this;
  97133. /**
  97134. * The component name helpful to identify the component in the list of scene components.
  97135. */
  97136. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97137. this.scene = scene;
  97138. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97139. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97140. // Replace the function used to get the deterministic frame time
  97141. this.scene.getDeterministicFrameTime = function () {
  97142. if (_this.scene._physicsEngine) {
  97143. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97144. }
  97145. return 1000.0 / 60.0;
  97146. };
  97147. }
  97148. /**
  97149. * Registers the component in a given scene
  97150. */
  97151. PhysicsEngineSceneComponent.prototype.register = function () {
  97152. };
  97153. /**
  97154. * Rebuilds the elements related to this component in case of
  97155. * context lost for instance.
  97156. */
  97157. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97158. // Nothing to do for this component
  97159. };
  97160. /**
  97161. * Disposes the component and the associated ressources
  97162. */
  97163. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97164. this.scene.onBeforePhysicsObservable.clear();
  97165. this.scene.onAfterPhysicsObservable.clear();
  97166. if (this.scene._physicsEngine) {
  97167. this.scene.disablePhysicsEngine();
  97168. }
  97169. };
  97170. return PhysicsEngineSceneComponent;
  97171. }());
  97172. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97173. })(BABYLON || (BABYLON = {}));
  97174. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97175. var BABYLON;
  97176. (function (BABYLON) {
  97177. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97178. // All values and structures referenced from:
  97179. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97180. var DDS_MAGIC = 0x20534444;
  97181. var
  97182. //DDSD_CAPS = 0x1,
  97183. //DDSD_HEIGHT = 0x2,
  97184. //DDSD_WIDTH = 0x4,
  97185. //DDSD_PITCH = 0x8,
  97186. //DDSD_PIXELFORMAT = 0x1000,
  97187. DDSD_MIPMAPCOUNT = 0x20000;
  97188. //DDSD_LINEARSIZE = 0x80000,
  97189. //DDSD_DEPTH = 0x800000;
  97190. // var DDSCAPS_COMPLEX = 0x8,
  97191. // DDSCAPS_MIPMAP = 0x400000,
  97192. // DDSCAPS_TEXTURE = 0x1000;
  97193. var DDSCAPS2_CUBEMAP = 0x200;
  97194. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97195. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97196. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97197. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97198. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97199. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97200. // DDSCAPS2_VOLUME = 0x200000;
  97201. var
  97202. //DDPF_ALPHAPIXELS = 0x1,
  97203. //DDPF_ALPHA = 0x2,
  97204. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97205. //DDPF_YUV = 0x200,
  97206. DDPF_LUMINANCE = 0x20000;
  97207. function FourCCToInt32(value) {
  97208. return value.charCodeAt(0) +
  97209. (value.charCodeAt(1) << 8) +
  97210. (value.charCodeAt(2) << 16) +
  97211. (value.charCodeAt(3) << 24);
  97212. }
  97213. function Int32ToFourCC(value) {
  97214. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97215. }
  97216. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97217. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97218. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97219. var FOURCC_DX10 = FourCCToInt32("DX10");
  97220. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97221. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97222. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97223. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97224. var headerLengthInt = 31; // The header length in 32 bit ints
  97225. // Offsets into the header array
  97226. var off_magic = 0;
  97227. var off_size = 1;
  97228. var off_flags = 2;
  97229. var off_height = 3;
  97230. var off_width = 4;
  97231. var off_mipmapCount = 7;
  97232. var off_pfFlags = 20;
  97233. var off_pfFourCC = 21;
  97234. var off_RGBbpp = 22;
  97235. var off_RMask = 23;
  97236. var off_GMask = 24;
  97237. var off_BMask = 25;
  97238. var off_AMask = 26;
  97239. // var off_caps1 = 27;
  97240. var off_caps2 = 28;
  97241. // var off_caps3 = 29;
  97242. // var off_caps4 = 30;
  97243. var off_dxgiFormat = 32;
  97244. ;
  97245. /**
  97246. * Class used to provide DDS decompression tools
  97247. */
  97248. var DDSTools = /** @class */ (function () {
  97249. function DDSTools() {
  97250. }
  97251. /**
  97252. * Gets DDS information from an array buffer
  97253. * @param arrayBuffer defines the array buffer to read data from
  97254. * @returns the DDS information
  97255. */
  97256. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97257. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97258. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97259. var mipmapCount = 1;
  97260. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97261. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97262. }
  97263. var fourCC = header[off_pfFourCC];
  97264. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97265. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97266. switch (fourCC) {
  97267. case FOURCC_D3DFMT_R16G16B16A16F:
  97268. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97269. break;
  97270. case FOURCC_D3DFMT_R32G32B32A32F:
  97271. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97272. break;
  97273. case FOURCC_DX10:
  97274. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97275. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97276. break;
  97277. }
  97278. }
  97279. return {
  97280. width: header[off_width],
  97281. height: header[off_height],
  97282. mipmapCount: mipmapCount,
  97283. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97284. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97285. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97286. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97287. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97288. dxgiFormat: dxgiFormat,
  97289. textureType: textureType
  97290. };
  97291. };
  97292. DDSTools._ToHalfFloat = function (value) {
  97293. if (!DDSTools._FloatView) {
  97294. DDSTools._FloatView = new Float32Array(1);
  97295. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97296. }
  97297. DDSTools._FloatView[0] = value;
  97298. var x = DDSTools._Int32View[0];
  97299. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97300. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97301. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97302. /* If zero, or denormal, or exponent underflows too much for a denormal
  97303. * half, return signed zero. */
  97304. if (e < 103) {
  97305. return bits;
  97306. }
  97307. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97308. if (e > 142) {
  97309. bits |= 0x7c00;
  97310. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97311. * not Inf, so make sure we set one mantissa bit too. */
  97312. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97313. return bits;
  97314. }
  97315. /* If exponent underflows but not too much, return a denormal */
  97316. if (e < 113) {
  97317. m |= 0x0800;
  97318. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97319. * to 1, which is OK. */
  97320. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97321. return bits;
  97322. }
  97323. bits |= ((e - 112) << 10) | (m >> 1);
  97324. bits += m & 1;
  97325. return bits;
  97326. };
  97327. DDSTools._FromHalfFloat = function (value) {
  97328. var s = (value & 0x8000) >> 15;
  97329. var e = (value & 0x7C00) >> 10;
  97330. var f = value & 0x03FF;
  97331. if (e === 0) {
  97332. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97333. }
  97334. else if (e == 0x1F) {
  97335. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97336. }
  97337. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97338. };
  97339. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97340. var destArray = new Float32Array(dataLength);
  97341. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97342. var index = 0;
  97343. for (var y = 0; y < height; y++) {
  97344. for (var x = 0; x < width; x++) {
  97345. var srcPos = (x + y * width) * 4;
  97346. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97347. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97348. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97349. if (DDSTools.StoreLODInAlphaChannel) {
  97350. destArray[index + 3] = lod;
  97351. }
  97352. else {
  97353. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97354. }
  97355. index += 4;
  97356. }
  97357. }
  97358. return destArray;
  97359. };
  97360. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97361. if (DDSTools.StoreLODInAlphaChannel) {
  97362. var destArray = new Uint16Array(dataLength);
  97363. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97364. var index = 0;
  97365. for (var y = 0; y < height; y++) {
  97366. for (var x = 0; x < width; x++) {
  97367. var srcPos = (x + y * width) * 4;
  97368. destArray[index] = srcData[srcPos];
  97369. destArray[index + 1] = srcData[srcPos + 1];
  97370. destArray[index + 2] = srcData[srcPos + 2];
  97371. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97372. index += 4;
  97373. }
  97374. }
  97375. return destArray;
  97376. }
  97377. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97378. };
  97379. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97380. if (DDSTools.StoreLODInAlphaChannel) {
  97381. var destArray = new Float32Array(dataLength);
  97382. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97383. var index = 0;
  97384. for (var y = 0; y < height; y++) {
  97385. for (var x = 0; x < width; x++) {
  97386. var srcPos = (x + y * width) * 4;
  97387. destArray[index] = srcData[srcPos];
  97388. destArray[index + 1] = srcData[srcPos + 1];
  97389. destArray[index + 2] = srcData[srcPos + 2];
  97390. destArray[index + 3] = lod;
  97391. index += 4;
  97392. }
  97393. }
  97394. return destArray;
  97395. }
  97396. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97397. };
  97398. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97399. var destArray = new Uint8Array(dataLength);
  97400. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97401. var index = 0;
  97402. for (var y = 0; y < height; y++) {
  97403. for (var x = 0; x < width; x++) {
  97404. var srcPos = (x + y * width) * 4;
  97405. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97406. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97407. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97408. if (DDSTools.StoreLODInAlphaChannel) {
  97409. destArray[index + 3] = lod;
  97410. }
  97411. else {
  97412. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97413. }
  97414. index += 4;
  97415. }
  97416. }
  97417. return destArray;
  97418. };
  97419. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97420. var destArray = new Uint8Array(dataLength);
  97421. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97422. var index = 0;
  97423. for (var y = 0; y < height; y++) {
  97424. for (var x = 0; x < width; x++) {
  97425. var srcPos = (x + y * width) * 4;
  97426. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97427. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97428. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97429. if (DDSTools.StoreLODInAlphaChannel) {
  97430. destArray[index + 3] = lod;
  97431. }
  97432. else {
  97433. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97434. }
  97435. index += 4;
  97436. }
  97437. }
  97438. return destArray;
  97439. };
  97440. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97441. var byteArray = new Uint8Array(dataLength);
  97442. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97443. var index = 0;
  97444. for (var y = 0; y < height; y++) {
  97445. for (var x = 0; x < width; x++) {
  97446. var srcPos = (x + y * width) * 4;
  97447. byteArray[index] = srcData[srcPos + rOffset];
  97448. byteArray[index + 1] = srcData[srcPos + gOffset];
  97449. byteArray[index + 2] = srcData[srcPos + bOffset];
  97450. byteArray[index + 3] = srcData[srcPos + aOffset];
  97451. index += 4;
  97452. }
  97453. }
  97454. return byteArray;
  97455. };
  97456. DDSTools._ExtractLongWordOrder = function (value) {
  97457. if (value === 0 || value === 255 || value === -16777216) {
  97458. return 0;
  97459. }
  97460. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97461. };
  97462. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97463. var byteArray = new Uint8Array(dataLength);
  97464. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97465. var index = 0;
  97466. for (var y = 0; y < height; y++) {
  97467. for (var x = 0; x < width; x++) {
  97468. var srcPos = (x + y * width) * 3;
  97469. byteArray[index] = srcData[srcPos + rOffset];
  97470. byteArray[index + 1] = srcData[srcPos + gOffset];
  97471. byteArray[index + 2] = srcData[srcPos + bOffset];
  97472. index += 3;
  97473. }
  97474. }
  97475. return byteArray;
  97476. };
  97477. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97478. var byteArray = new Uint8Array(dataLength);
  97479. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97480. var index = 0;
  97481. for (var y = 0; y < height; y++) {
  97482. for (var x = 0; x < width; x++) {
  97483. var srcPos = (x + y * width);
  97484. byteArray[index] = srcData[srcPos];
  97485. index++;
  97486. }
  97487. }
  97488. return byteArray;
  97489. };
  97490. /**
  97491. * Uploads DDS Levels to a Babylon Texture
  97492. * @hidden
  97493. */
  97494. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97495. if (lodIndex === void 0) { lodIndex = -1; }
  97496. var sphericalPolynomialFaces = null;
  97497. if (info.sphericalPolynomial) {
  97498. sphericalPolynomialFaces = new Array();
  97499. }
  97500. var ext = engine.getCaps().s3tc;
  97501. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97502. var fourCC, width, height, dataLength = 0, dataOffset;
  97503. var byteArray, mipmapCount, mip;
  97504. var internalCompressedFormat = 0;
  97505. var blockBytes = 1;
  97506. if (header[off_magic] !== DDS_MAGIC) {
  97507. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97508. return;
  97509. }
  97510. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97511. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97512. return;
  97513. }
  97514. if (info.isCompressed && !ext) {
  97515. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97516. return;
  97517. }
  97518. var bpp = header[off_RGBbpp];
  97519. dataOffset = header[off_size] + 4;
  97520. var computeFormats = false;
  97521. if (info.isFourCC) {
  97522. fourCC = header[off_pfFourCC];
  97523. switch (fourCC) {
  97524. case FOURCC_DXT1:
  97525. blockBytes = 8;
  97526. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97527. break;
  97528. case FOURCC_DXT3:
  97529. blockBytes = 16;
  97530. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97531. break;
  97532. case FOURCC_DXT5:
  97533. blockBytes = 16;
  97534. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97535. break;
  97536. case FOURCC_D3DFMT_R16G16B16A16F:
  97537. computeFormats = true;
  97538. break;
  97539. case FOURCC_D3DFMT_R32G32B32A32F:
  97540. computeFormats = true;
  97541. break;
  97542. case FOURCC_DX10:
  97543. // There is an additionnal header so dataOffset need to be changed
  97544. dataOffset += 5 * 4; // 5 uints
  97545. var supported = false;
  97546. switch (info.dxgiFormat) {
  97547. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97548. computeFormats = true;
  97549. supported = true;
  97550. break;
  97551. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97552. info.isRGB = true;
  97553. info.isFourCC = false;
  97554. bpp = 32;
  97555. supported = true;
  97556. break;
  97557. }
  97558. if (supported) {
  97559. break;
  97560. }
  97561. default:
  97562. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97563. return;
  97564. }
  97565. }
  97566. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97567. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97568. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97569. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97570. if (computeFormats) {
  97571. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97572. }
  97573. mipmapCount = 1;
  97574. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97575. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97576. }
  97577. for (var face = 0; face < faces; face++) {
  97578. width = header[off_width];
  97579. height = header[off_height];
  97580. for (mip = 0; mip < mipmapCount; ++mip) {
  97581. if (lodIndex === -1 || lodIndex === mip) {
  97582. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97583. var i = (lodIndex === -1) ? mip : 0;
  97584. if (!info.isCompressed && info.isFourCC) {
  97585. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97586. dataLength = width * height * 4;
  97587. var floatArray = null;
  97588. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97589. if (bpp === 128) {
  97590. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97591. if (sphericalPolynomialFaces && i == 0) {
  97592. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97593. }
  97594. }
  97595. else if (bpp === 64) {
  97596. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97597. if (sphericalPolynomialFaces && i == 0) {
  97598. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97599. }
  97600. }
  97601. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97602. }
  97603. else {
  97604. if (bpp === 128) {
  97605. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97606. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97607. if (sphericalPolynomialFaces && i == 0) {
  97608. sphericalPolynomialFaces.push(floatArray);
  97609. }
  97610. }
  97611. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97612. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97613. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97614. if (sphericalPolynomialFaces && i == 0) {
  97615. sphericalPolynomialFaces.push(floatArray);
  97616. }
  97617. }
  97618. else { // 64
  97619. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97620. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97621. if (sphericalPolynomialFaces && i == 0) {
  97622. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97623. }
  97624. }
  97625. }
  97626. if (floatArray) {
  97627. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97628. }
  97629. }
  97630. else if (info.isRGB) {
  97631. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97632. if (bpp === 24) {
  97633. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97634. dataLength = width * height * 3;
  97635. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97636. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97637. }
  97638. else { // 32
  97639. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97640. dataLength = width * height * 4;
  97641. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97642. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97643. }
  97644. }
  97645. else if (info.isLuminance) {
  97646. var unpackAlignment = engine._getUnpackAlignement();
  97647. var unpaddedRowSize = width;
  97648. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97649. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97650. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97651. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97652. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97653. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97654. }
  97655. else {
  97656. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  97657. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  97658. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97659. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  97660. }
  97661. }
  97662. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  97663. width *= 0.5;
  97664. height *= 0.5;
  97665. width = Math.max(1.0, width);
  97666. height = Math.max(1.0, height);
  97667. }
  97668. if (currentFace !== undefined) {
  97669. // Loading a single face
  97670. break;
  97671. }
  97672. }
  97673. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  97674. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  97675. size: header[off_width],
  97676. right: sphericalPolynomialFaces[0],
  97677. left: sphericalPolynomialFaces[1],
  97678. up: sphericalPolynomialFaces[2],
  97679. down: sphericalPolynomialFaces[3],
  97680. front: sphericalPolynomialFaces[4],
  97681. back: sphericalPolynomialFaces[5],
  97682. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  97683. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  97684. gammaSpace: false,
  97685. });
  97686. }
  97687. else {
  97688. info.sphericalPolynomial = undefined;
  97689. }
  97690. };
  97691. /**
  97692. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  97693. */
  97694. DDSTools.StoreLODInAlphaChannel = false;
  97695. return DDSTools;
  97696. }());
  97697. BABYLON.DDSTools = DDSTools;
  97698. })(BABYLON || (BABYLON = {}));
  97699. //# sourceMappingURL=babylon.dds.js.map
  97700. var BABYLON;
  97701. (function (BABYLON) {
  97702. /**
  97703. * Implementation of the DDS Texture Loader.
  97704. */
  97705. var DDSTextureLoader = /** @class */ (function () {
  97706. function DDSTextureLoader() {
  97707. /**
  97708. * Defines wether the loader supports cascade loading the different faces.
  97709. */
  97710. this.supportCascades = true;
  97711. }
  97712. /**
  97713. * This returns if the loader support the current file information.
  97714. * @param extension defines the file extension of the file being loaded
  97715. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97716. * @param fallback defines the fallback internal texture if any
  97717. * @param isBase64 defines whether the texture is encoded as a base64
  97718. * @param isBuffer defines whether the texture data are stored as a buffer
  97719. * @returns true if the loader can load the specified file
  97720. */
  97721. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97722. return extension.indexOf(".dds") === 0;
  97723. };
  97724. /**
  97725. * Transform the url before loading if required.
  97726. * @param rootUrl the url of the texture
  97727. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97728. * @returns the transformed texture
  97729. */
  97730. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97731. return rootUrl;
  97732. };
  97733. /**
  97734. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97735. * @param rootUrl the url of the texture
  97736. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97737. * @returns the fallback texture
  97738. */
  97739. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97740. return null;
  97741. };
  97742. /**
  97743. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97744. * @param data contains the texture data
  97745. * @param texture defines the BabylonJS internal texture
  97746. * @param createPolynomials will be true if polynomials have been requested
  97747. * @param onLoad defines the callback to trigger once the texture is ready
  97748. * @param onError defines the callback to trigger in case of error
  97749. */
  97750. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  97751. var engine = texture.getEngine();
  97752. var info;
  97753. var loadMipmap = false;
  97754. if (Array.isArray(imgs)) {
  97755. for (var index = 0; index < imgs.length; index++) {
  97756. var data_1 = imgs[index];
  97757. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  97758. texture.width = info.width;
  97759. texture.height = info.height;
  97760. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  97761. engine._unpackFlipY(info.isCompressed);
  97762. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  97763. if (!info.isFourCC && info.mipmapCount === 1) {
  97764. engine.generateMipMapsForCubemap(texture);
  97765. }
  97766. }
  97767. }
  97768. else {
  97769. var data = imgs;
  97770. info = BABYLON.DDSTools.GetDDSInfo(data);
  97771. texture.width = info.width;
  97772. texture.height = info.height;
  97773. if (createPolynomials) {
  97774. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  97775. }
  97776. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  97777. engine._unpackFlipY(info.isCompressed);
  97778. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  97779. if (!info.isFourCC && info.mipmapCount === 1) {
  97780. engine.generateMipMapsForCubemap(texture);
  97781. }
  97782. }
  97783. engine._setCubeMapTextureParams(loadMipmap);
  97784. texture.isReady = true;
  97785. if (onLoad) {
  97786. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  97787. }
  97788. };
  97789. /**
  97790. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97791. * @param data contains the texture data
  97792. * @param texture defines the BabylonJS internal texture
  97793. * @param callback defines the method to call once ready to upload
  97794. */
  97795. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  97796. var info = BABYLON.DDSTools.GetDDSInfo(data);
  97797. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  97798. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  97799. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  97800. });
  97801. };
  97802. return DDSTextureLoader;
  97803. }());
  97804. // Register the loader.
  97805. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  97806. })(BABYLON || (BABYLON = {}));
  97807. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  97808. var BABYLON;
  97809. (function (BABYLON) {
  97810. /**
  97811. * Based on jsTGALoader - Javascript loader for TGA file
  97812. * By Vincent Thibault
  97813. * @see http://blog.robrowser.com/javascript-tga-loader.html
  97814. */
  97815. var TGATools = /** @class */ (function () {
  97816. function TGATools() {
  97817. }
  97818. /**
  97819. * Gets the header of a TGA file
  97820. * @param data defines the TGA data
  97821. * @returns the header
  97822. */
  97823. TGATools.GetTGAHeader = function (data) {
  97824. var offset = 0;
  97825. var header = {
  97826. id_length: data[offset++],
  97827. colormap_type: data[offset++],
  97828. image_type: data[offset++],
  97829. colormap_index: data[offset++] | data[offset++] << 8,
  97830. colormap_length: data[offset++] | data[offset++] << 8,
  97831. colormap_size: data[offset++],
  97832. origin: [
  97833. data[offset++] | data[offset++] << 8,
  97834. data[offset++] | data[offset++] << 8
  97835. ],
  97836. width: data[offset++] | data[offset++] << 8,
  97837. height: data[offset++] | data[offset++] << 8,
  97838. pixel_size: data[offset++],
  97839. flags: data[offset++]
  97840. };
  97841. return header;
  97842. };
  97843. /**
  97844. * Uploads TGA content to a Babylon Texture
  97845. * @hidden
  97846. */
  97847. TGATools.UploadContent = function (texture, data) {
  97848. // Not enough data to contain header ?
  97849. if (data.length < 19) {
  97850. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  97851. return;
  97852. }
  97853. // Read Header
  97854. var offset = 18;
  97855. var header = TGATools.GetTGAHeader(data);
  97856. // Assume it's a valid Targa file.
  97857. if (header.id_length + offset > data.length) {
  97858. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  97859. return;
  97860. }
  97861. // Skip not needed data
  97862. offset += header.id_length;
  97863. var use_rle = false;
  97864. var use_pal = false;
  97865. var use_grey = false;
  97866. // Get some informations.
  97867. switch (header.image_type) {
  97868. case TGATools._TYPE_RLE_INDEXED:
  97869. use_rle = true;
  97870. case TGATools._TYPE_INDEXED:
  97871. use_pal = true;
  97872. break;
  97873. case TGATools._TYPE_RLE_RGB:
  97874. use_rle = true;
  97875. case TGATools._TYPE_RGB:
  97876. // use_rgb = true;
  97877. break;
  97878. case TGATools._TYPE_RLE_GREY:
  97879. use_rle = true;
  97880. case TGATools._TYPE_GREY:
  97881. use_grey = true;
  97882. break;
  97883. }
  97884. var pixel_data;
  97885. // var numAlphaBits = header.flags & 0xf;
  97886. var pixel_size = header.pixel_size >> 3;
  97887. var pixel_total = header.width * header.height * pixel_size;
  97888. // Read palettes
  97889. var palettes;
  97890. if (use_pal) {
  97891. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  97892. }
  97893. // Read LRE
  97894. if (use_rle) {
  97895. pixel_data = new Uint8Array(pixel_total);
  97896. var c, count, i;
  97897. var localOffset = 0;
  97898. var pixels = new Uint8Array(pixel_size);
  97899. while (offset < pixel_total && localOffset < pixel_total) {
  97900. c = data[offset++];
  97901. count = (c & 0x7f) + 1;
  97902. // RLE pixels
  97903. if (c & 0x80) {
  97904. // Bind pixel tmp array
  97905. for (i = 0; i < pixel_size; ++i) {
  97906. pixels[i] = data[offset++];
  97907. }
  97908. // Copy pixel array
  97909. for (i = 0; i < count; ++i) {
  97910. pixel_data.set(pixels, localOffset + i * pixel_size);
  97911. }
  97912. localOffset += pixel_size * count;
  97913. }
  97914. // Raw pixels
  97915. else {
  97916. count *= pixel_size;
  97917. for (i = 0; i < count; ++i) {
  97918. pixel_data[localOffset + i] = data[offset++];
  97919. }
  97920. localOffset += count;
  97921. }
  97922. }
  97923. }
  97924. // RAW Pixels
  97925. else {
  97926. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  97927. }
  97928. // Load to texture
  97929. var x_start, y_start, x_step, y_step, y_end, x_end;
  97930. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  97931. default:
  97932. case TGATools._ORIGIN_UL:
  97933. x_start = 0;
  97934. x_step = 1;
  97935. x_end = header.width;
  97936. y_start = 0;
  97937. y_step = 1;
  97938. y_end = header.height;
  97939. break;
  97940. case TGATools._ORIGIN_BL:
  97941. x_start = 0;
  97942. x_step = 1;
  97943. x_end = header.width;
  97944. y_start = header.height - 1;
  97945. y_step = -1;
  97946. y_end = -1;
  97947. break;
  97948. case TGATools._ORIGIN_UR:
  97949. x_start = header.width - 1;
  97950. x_step = -1;
  97951. x_end = -1;
  97952. y_start = 0;
  97953. y_step = 1;
  97954. y_end = header.height;
  97955. break;
  97956. case TGATools._ORIGIN_BR:
  97957. x_start = header.width - 1;
  97958. x_step = -1;
  97959. x_end = -1;
  97960. y_start = header.height - 1;
  97961. y_step = -1;
  97962. y_end = -1;
  97963. break;
  97964. }
  97965. // Load the specify method
  97966. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  97967. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  97968. var engine = texture.getEngine();
  97969. engine._uploadDataToTextureDirectly(texture, imageData);
  97970. };
  97971. /** @hidden */
  97972. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  97973. var image = pixel_data, colormap = palettes;
  97974. var width = header.width, height = header.height;
  97975. var color, i = 0, x, y;
  97976. var imageData = new Uint8Array(width * height * 4);
  97977. for (y = y_start; y !== y_end; y += y_step) {
  97978. for (x = x_start; x !== x_end; x += x_step, i++) {
  97979. color = image[i];
  97980. imageData[(x + width * y) * 4 + 3] = 255;
  97981. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  97982. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  97983. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  97984. }
  97985. }
  97986. return imageData;
  97987. };
  97988. /** @hidden */
  97989. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  97990. var image = pixel_data;
  97991. var width = header.width, height = header.height;
  97992. var color, i = 0, x, y;
  97993. var imageData = new Uint8Array(width * height * 4);
  97994. for (y = y_start; y !== y_end; y += y_step) {
  97995. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  97996. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  97997. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  97998. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  97999. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  98000. imageData[(x + width * y) * 4 + 0] = r;
  98001. imageData[(x + width * y) * 4 + 1] = g;
  98002. imageData[(x + width * y) * 4 + 2] = b;
  98003. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  98004. }
  98005. }
  98006. return imageData;
  98007. };
  98008. /** @hidden */
  98009. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98010. var image = pixel_data;
  98011. var width = header.width, height = header.height;
  98012. var i = 0, x, y;
  98013. var imageData = new Uint8Array(width * height * 4);
  98014. for (y = y_start; y !== y_end; y += y_step) {
  98015. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98016. imageData[(x + width * y) * 4 + 3] = 255;
  98017. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98018. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98019. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98020. }
  98021. }
  98022. return imageData;
  98023. };
  98024. /** @hidden */
  98025. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98026. var image = pixel_data;
  98027. var width = header.width, height = header.height;
  98028. var i = 0, x, y;
  98029. var imageData = new Uint8Array(width * height * 4);
  98030. for (y = y_start; y !== y_end; y += y_step) {
  98031. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98032. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98033. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98034. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98035. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98036. }
  98037. }
  98038. return imageData;
  98039. };
  98040. /** @hidden */
  98041. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98042. var image = pixel_data;
  98043. var width = header.width, height = header.height;
  98044. var color, i = 0, x, y;
  98045. var imageData = new Uint8Array(width * height * 4);
  98046. for (y = y_start; y !== y_end; y += y_step) {
  98047. for (x = x_start; x !== x_end; x += x_step, i++) {
  98048. color = image[i];
  98049. imageData[(x + width * y) * 4 + 0] = color;
  98050. imageData[(x + width * y) * 4 + 1] = color;
  98051. imageData[(x + width * y) * 4 + 2] = color;
  98052. imageData[(x + width * y) * 4 + 3] = 255;
  98053. }
  98054. }
  98055. return imageData;
  98056. };
  98057. /** @hidden */
  98058. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98059. var image = pixel_data;
  98060. var width = header.width, height = header.height;
  98061. var i = 0, x, y;
  98062. var imageData = new Uint8Array(width * height * 4);
  98063. for (y = y_start; y !== y_end; y += y_step) {
  98064. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98065. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98066. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98067. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98068. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98069. }
  98070. }
  98071. return imageData;
  98072. };
  98073. //private static _TYPE_NO_DATA = 0;
  98074. TGATools._TYPE_INDEXED = 1;
  98075. TGATools._TYPE_RGB = 2;
  98076. TGATools._TYPE_GREY = 3;
  98077. TGATools._TYPE_RLE_INDEXED = 9;
  98078. TGATools._TYPE_RLE_RGB = 10;
  98079. TGATools._TYPE_RLE_GREY = 11;
  98080. TGATools._ORIGIN_MASK = 0x30;
  98081. TGATools._ORIGIN_SHIFT = 0x04;
  98082. TGATools._ORIGIN_BL = 0x00;
  98083. TGATools._ORIGIN_BR = 0x01;
  98084. TGATools._ORIGIN_UL = 0x02;
  98085. TGATools._ORIGIN_UR = 0x03;
  98086. return TGATools;
  98087. }());
  98088. BABYLON.TGATools = TGATools;
  98089. })(BABYLON || (BABYLON = {}));
  98090. //# sourceMappingURL=babylon.tga.js.map
  98091. var BABYLON;
  98092. (function (BABYLON) {
  98093. /**
  98094. * Implementation of the TGA Texture Loader.
  98095. */
  98096. var TGATextureLoader = /** @class */ (function () {
  98097. function TGATextureLoader() {
  98098. /**
  98099. * Defines wether the loader supports cascade loading the different faces.
  98100. */
  98101. this.supportCascades = false;
  98102. }
  98103. /**
  98104. * This returns if the loader support the current file information.
  98105. * @param extension defines the file extension of the file being loaded
  98106. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98107. * @param fallback defines the fallback internal texture if any
  98108. * @param isBase64 defines whether the texture is encoded as a base64
  98109. * @param isBuffer defines whether the texture data are stored as a buffer
  98110. * @returns true if the loader can load the specified file
  98111. */
  98112. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98113. return extension.indexOf(".tga") === 0;
  98114. };
  98115. /**
  98116. * Transform the url before loading if required.
  98117. * @param rootUrl the url of the texture
  98118. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98119. * @returns the transformed texture
  98120. */
  98121. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98122. return rootUrl;
  98123. };
  98124. /**
  98125. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98126. * @param rootUrl the url of the texture
  98127. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98128. * @returns the fallback texture
  98129. */
  98130. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98131. return null;
  98132. };
  98133. /**
  98134. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98135. * @param data contains the texture data
  98136. * @param texture defines the BabylonJS internal texture
  98137. * @param createPolynomials will be true if polynomials have been requested
  98138. * @param onLoad defines the callback to trigger once the texture is ready
  98139. * @param onError defines the callback to trigger in case of error
  98140. */
  98141. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98142. throw ".env not supported in Cube.";
  98143. };
  98144. /**
  98145. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98146. * @param data contains the texture data
  98147. * @param texture defines the BabylonJS internal texture
  98148. * @param callback defines the method to call once ready to upload
  98149. */
  98150. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98151. var uintData = new Uint8Array(data);
  98152. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98153. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98154. BABYLON.TGATools.UploadContent(texture, uintData);
  98155. });
  98156. };
  98157. return TGATextureLoader;
  98158. }());
  98159. // Register the loader.
  98160. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98161. })(BABYLON || (BABYLON = {}));
  98162. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98163. var BABYLON;
  98164. (function (BABYLON) {
  98165. /**
  98166. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98167. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98168. */
  98169. var KhronosTextureContainer = /** @class */ (function () {
  98170. /**
  98171. * Creates a new KhronosTextureContainer
  98172. * @param arrayBuffer contents of the KTX container file
  98173. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98174. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98175. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98176. */
  98177. function KhronosTextureContainer(
  98178. /** contents of the KTX container file */
  98179. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98180. this.arrayBuffer = arrayBuffer;
  98181. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98182. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98183. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98184. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98185. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98186. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98187. BABYLON.Tools.Error("texture missing KTX identifier");
  98188. return;
  98189. }
  98190. // load the reset of the header in native 32 bit int
  98191. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98192. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98193. var oppositeEndianess = header[0] === 0x01020304;
  98194. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98195. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98196. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98197. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98198. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98199. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98200. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98201. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98202. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98203. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98204. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98205. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98206. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98207. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98208. if (this.glType !== 0) {
  98209. BABYLON.Tools.Error("only compressed formats currently supported");
  98210. return;
  98211. }
  98212. else {
  98213. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98214. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98215. }
  98216. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98217. BABYLON.Tools.Error("only 2D textures currently supported");
  98218. return;
  98219. }
  98220. if (this.numberOfArrayElements !== 0) {
  98221. BABYLON.Tools.Error("texture arrays not currently supported");
  98222. return;
  98223. }
  98224. if (this.numberOfFaces !== facesExpected) {
  98225. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98226. return;
  98227. }
  98228. // we now have a completely validated file, so could use existence of loadType as success
  98229. // would need to make this more elaborate & adjust checks above to support more than one load type
  98230. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98231. }
  98232. //
  98233. /**
  98234. * Revert the endianness of a value.
  98235. * Not as fast hardware based, but will probably never need to use
  98236. * @param val defines the value to convert
  98237. * @returns the new value
  98238. */
  98239. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98240. return ((val & 0xFF) << 24)
  98241. | ((val & 0xFF00) << 8)
  98242. | ((val >> 8) & 0xFF00)
  98243. | ((val >> 24) & 0xFF);
  98244. };
  98245. /**
  98246. * Uploads KTX content to a Babylon Texture.
  98247. * It is assumed that the texture has already been created & is currently bound
  98248. * @hidden
  98249. */
  98250. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98251. switch (this.loadType) {
  98252. case KhronosTextureContainer.COMPRESSED_2D:
  98253. this._upload2DCompressedLevels(texture, loadMipmaps);
  98254. break;
  98255. case KhronosTextureContainer.TEX_2D:
  98256. case KhronosTextureContainer.COMPRESSED_3D:
  98257. case KhronosTextureContainer.TEX_3D:
  98258. }
  98259. };
  98260. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98261. // initialize width & height for level 1
  98262. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98263. var width = this.pixelWidth;
  98264. var height = this.pixelHeight;
  98265. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98266. for (var level = 0; level < mipmapCount; level++) {
  98267. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98268. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98269. for (var face = 0; face < this.numberOfFaces; face++) {
  98270. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98271. var engine = texture.getEngine();
  98272. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98273. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98274. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98275. }
  98276. width = Math.max(1.0, width * 0.5);
  98277. height = Math.max(1.0, height * 0.5);
  98278. }
  98279. };
  98280. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98281. // load types
  98282. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98283. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98284. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98285. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98286. return KhronosTextureContainer;
  98287. }());
  98288. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98289. })(BABYLON || (BABYLON = {}));
  98290. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98291. var BABYLON;
  98292. (function (BABYLON) {
  98293. /**
  98294. * Implementation of the KTX Texture Loader.
  98295. */
  98296. var KTXTextureLoader = /** @class */ (function () {
  98297. function KTXTextureLoader() {
  98298. /**
  98299. * Defines wether the loader supports cascade loading the different faces.
  98300. */
  98301. this.supportCascades = false;
  98302. }
  98303. /**
  98304. * This returns if the loader support the current file information.
  98305. * @param extension defines the file extension of the file being loaded
  98306. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98307. * @param fallback defines the fallback internal texture if any
  98308. * @param isBase64 defines whether the texture is encoded as a base64
  98309. * @param isBuffer defines whether the texture data are stored as a buffer
  98310. * @returns true if the loader can load the specified file
  98311. */
  98312. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98313. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98314. return true;
  98315. }
  98316. return false;
  98317. };
  98318. /**
  98319. * Transform the url before loading if required.
  98320. * @param rootUrl the url of the texture
  98321. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98322. * @returns the transformed texture
  98323. */
  98324. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98325. var lastDot = rootUrl.lastIndexOf('.');
  98326. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98327. };
  98328. /**
  98329. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98330. * @param rootUrl the url of the texture
  98331. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98332. * @returns the fallback texture
  98333. */
  98334. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98335. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98336. var exp = new RegExp("" + textureFormatInUse + "$");
  98337. return rootUrl.replace(exp, "");
  98338. };
  98339. /**
  98340. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98341. * @param data contains the texture data
  98342. * @param texture defines the BabylonJS internal texture
  98343. * @param createPolynomials will be true if polynomials have been requested
  98344. * @param onLoad defines the callback to trigger once the texture is ready
  98345. * @param onError defines the callback to trigger in case of error
  98346. */
  98347. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98348. if (Array.isArray(data)) {
  98349. return;
  98350. }
  98351. var engine = texture.getEngine();
  98352. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98353. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98354. engine._unpackFlipY(true);
  98355. ktx.uploadLevels(texture, texture.generateMipMaps);
  98356. texture.width = ktx.pixelWidth;
  98357. texture.height = ktx.pixelHeight;
  98358. engine._setCubeMapTextureParams(loadMipmap);
  98359. texture.isReady = true;
  98360. };
  98361. /**
  98362. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98363. * @param data contains the texture data
  98364. * @param texture defines the BabylonJS internal texture
  98365. * @param callback defines the method to call once ready to upload
  98366. */
  98367. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98368. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98369. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98370. ktx.uploadLevels(texture, texture.generateMipMaps);
  98371. });
  98372. };
  98373. return KTXTextureLoader;
  98374. }());
  98375. // Register the loader.
  98376. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98377. })(BABYLON || (BABYLON = {}));
  98378. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98379. var BABYLON;
  98380. (function (BABYLON) {
  98381. /**
  98382. * Sets of helpers addressing the serialization and deserialization of environment texture
  98383. * stored in a BabylonJS env file.
  98384. * Those files are usually stored as .env files.
  98385. */
  98386. var EnvironmentTextureTools = /** @class */ (function () {
  98387. function EnvironmentTextureTools() {
  98388. }
  98389. /**
  98390. * Gets the environment info from an env file.
  98391. * @param data The array buffer containing the .env bytes.
  98392. * @returns the environment file info (the json header) if successfully parsed.
  98393. */
  98394. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98395. var dataView = new DataView(data);
  98396. var pos = 0;
  98397. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98398. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98399. BABYLON.Tools.Error('Not a babylon environment map');
  98400. return null;
  98401. }
  98402. }
  98403. // Read json manifest - collect characters up to null terminator
  98404. var manifestString = '';
  98405. var charCode = 0x00;
  98406. while ((charCode = dataView.getUint8(pos++))) {
  98407. manifestString += String.fromCharCode(charCode);
  98408. }
  98409. var manifest = JSON.parse(manifestString);
  98410. if (manifest.specular) {
  98411. // Extend the header with the position of the payload.
  98412. manifest.specular.specularDataPosition = pos;
  98413. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98414. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98415. }
  98416. return manifest;
  98417. };
  98418. /**
  98419. * Creates an environment texture from a loaded cube texture.
  98420. * @param texture defines the cube texture to convert in env file
  98421. * @return a promise containing the environment data if succesfull.
  98422. */
  98423. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98424. var _this = this;
  98425. var internalTexture = texture.getInternalTexture();
  98426. if (!internalTexture) {
  98427. return Promise.reject("The cube texture is invalid.");
  98428. }
  98429. if (!texture._prefiltered) {
  98430. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98431. }
  98432. var engine = internalTexture.getEngine();
  98433. if (engine && engine.premultipliedAlpha) {
  98434. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98435. }
  98436. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98437. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98438. }
  98439. var canvas = engine.getRenderingCanvas();
  98440. if (!canvas) {
  98441. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98442. }
  98443. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98444. if (!engine.getCaps().textureFloatRender) {
  98445. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98446. if (!engine.getCaps().textureHalfFloatRender) {
  98447. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98448. }
  98449. }
  98450. var cubeWidth = internalTexture.width;
  98451. var hostingScene = new BABYLON.Scene(engine);
  98452. var specularTextures = {};
  98453. var promises = [];
  98454. // Read and collect all mipmaps data from the cube.
  98455. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98456. mipmapsCount = Math.round(mipmapsCount);
  98457. var _loop_1 = function (i) {
  98458. var faceWidth = Math.pow(2, mipmapsCount - i);
  98459. var _loop_2 = function (face) {
  98460. var data = texture.readPixels(face, i);
  98461. // Creates a temp texture with the face data.
  98462. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98463. // And rgbdEncode them.
  98464. var promise = new Promise(function (resolve, reject) {
  98465. 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);
  98466. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98467. rgbdPostProcess.onApply = function (effect) {
  98468. effect._bindTexture("textureSampler", tempTexture);
  98469. };
  98470. // As the process needs to happen on the main canvas, keep track of the current size
  98471. var currentW = engine.getRenderWidth();
  98472. var currentH = engine.getRenderHeight();
  98473. // Set the desired size for the texture
  98474. engine.setSize(faceWidth, faceWidth);
  98475. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98476. // Reading datas from WebGL
  98477. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98478. var fileReader = new FileReader();
  98479. fileReader.onload = function (event) {
  98480. var arrayBuffer = event.target.result;
  98481. specularTextures[i * 6 + face] = arrayBuffer;
  98482. resolve();
  98483. };
  98484. fileReader.readAsArrayBuffer(blob);
  98485. });
  98486. // Reapply the previous canvas size
  98487. engine.setSize(currentW, currentH);
  98488. });
  98489. });
  98490. promises.push(promise);
  98491. };
  98492. // All faces of the cube.
  98493. for (var face = 0; face < 6; face++) {
  98494. _loop_2(face);
  98495. }
  98496. };
  98497. for (var i = 0; i <= mipmapsCount; i++) {
  98498. _loop_1(i);
  98499. }
  98500. // Once all the textures haves been collected as RGBD stored in PNGs
  98501. return Promise.all(promises).then(function () {
  98502. // We can delete the hosting scene keeping track of all the creation objects
  98503. hostingScene.dispose();
  98504. // Creates the json header for the env texture
  98505. var info = {
  98506. version: 1,
  98507. width: cubeWidth,
  98508. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98509. specular: {
  98510. mipmaps: [],
  98511. lodGenerationScale: texture.lodGenerationScale
  98512. }
  98513. };
  98514. // Sets the specular image data information
  98515. var position = 0;
  98516. for (var i = 0; i <= mipmapsCount; i++) {
  98517. for (var face = 0; face < 6; face++) {
  98518. var byteLength = specularTextures[i * 6 + face].byteLength;
  98519. info.specular.mipmaps.push({
  98520. length: byteLength,
  98521. position: position
  98522. });
  98523. position += byteLength;
  98524. }
  98525. }
  98526. // Encode the JSON as an array buffer
  98527. var infoString = JSON.stringify(info);
  98528. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98529. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98530. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98531. infoView[i] = infoString.charCodeAt(i);
  98532. }
  98533. // Ends up with a null terminator for easier parsing
  98534. infoView[infoString.length] = 0x00;
  98535. // Computes the final required size and creates the storage
  98536. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98537. var finalBuffer = new ArrayBuffer(totalSize);
  98538. var finalBufferView = new Uint8Array(finalBuffer);
  98539. var dataView = new DataView(finalBuffer);
  98540. // Copy the magic bytes identifying the file in
  98541. var pos = 0;
  98542. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98543. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98544. }
  98545. // Add the json info
  98546. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98547. pos += infoBuffer.byteLength;
  98548. // Finally inserts the texture data
  98549. for (var i = 0; i <= mipmapsCount; i++) {
  98550. for (var face = 0; face < 6; face++) {
  98551. var dataBuffer = specularTextures[i * 6 + face];
  98552. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98553. pos += dataBuffer.byteLength;
  98554. }
  98555. }
  98556. // Voila
  98557. return finalBuffer;
  98558. });
  98559. };
  98560. /**
  98561. * Creates a JSON representation of the spherical data.
  98562. * @param texture defines the texture containing the polynomials
  98563. * @return the JSON representation of the spherical info
  98564. */
  98565. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98566. var polynmials = texture.sphericalPolynomial;
  98567. if (polynmials == null) {
  98568. return null;
  98569. }
  98570. return {
  98571. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98572. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98573. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98574. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98575. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98576. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98577. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98578. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98579. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98580. };
  98581. };
  98582. /**
  98583. * Uploads the texture info contained in the env file to the GPU.
  98584. * @param texture defines the internal texture to upload to
  98585. * @param arrayBuffer defines the buffer cotaining the data to load
  98586. * @param info defines the texture info retrieved through the GetEnvInfo method
  98587. * @returns a promise
  98588. */
  98589. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98590. if (info.version !== 1) {
  98591. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98592. }
  98593. var specularInfo = info.specular;
  98594. if (!specularInfo) {
  98595. // Nothing else parsed so far
  98596. return Promise.resolve();
  98597. }
  98598. // Double checks the enclosed info
  98599. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98600. mipmapsCount = Math.round(mipmapsCount) + 1;
  98601. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98602. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98603. }
  98604. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98605. var imageData = new Array(mipmapsCount);
  98606. for (var i = 0; i < mipmapsCount; i++) {
  98607. imageData[i] = new Array(6);
  98608. for (var face = 0; face < 6; face++) {
  98609. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98610. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98611. }
  98612. }
  98613. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98614. };
  98615. /**
  98616. * Uploads the levels of image data to the GPU.
  98617. * @param texture defines the internal texture to upload to
  98618. * @param imageData defines the array buffer views of image data [mipmap][face]
  98619. * @returns a promise
  98620. */
  98621. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98622. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98623. throw new Error("Texture size must be a power of two");
  98624. }
  98625. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98626. // Gets everything ready.
  98627. var engine = texture.getEngine();
  98628. var expandTexture = false;
  98629. var generateNonLODTextures = false;
  98630. var rgbdPostProcess = null;
  98631. var cubeRtt = null;
  98632. var lodTextures = null;
  98633. var caps = engine.getCaps();
  98634. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98635. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98636. texture.generateMipMaps = true;
  98637. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98638. // Add extra process if texture lod is not supported
  98639. if (!caps.textureLOD) {
  98640. expandTexture = false;
  98641. generateNonLODTextures = true;
  98642. lodTextures = {};
  98643. }
  98644. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98645. else if (engine.webGLVersion < 2) {
  98646. expandTexture = false;
  98647. }
  98648. // If half float available we can uncompress the texture
  98649. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98650. expandTexture = true;
  98651. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98652. }
  98653. // If full float available we can uncompress the texture
  98654. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  98655. expandTexture = true;
  98656. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98657. }
  98658. // Expand the texture if possible
  98659. if (expandTexture) {
  98660. // Simply run through the decode PP
  98661. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  98662. texture._isRGBD = false;
  98663. texture.invertY = false;
  98664. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  98665. generateDepthBuffer: false,
  98666. generateMipMaps: true,
  98667. generateStencilBuffer: false,
  98668. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  98669. type: texture.type,
  98670. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  98671. });
  98672. }
  98673. else {
  98674. texture._isRGBD = true;
  98675. texture.invertY = true;
  98676. // In case of missing support, applies the same patch than DDS files.
  98677. if (generateNonLODTextures) {
  98678. var mipSlices = 3;
  98679. var scale = texture._lodGenerationScale;
  98680. var offset = texture._lodGenerationOffset;
  98681. for (var i = 0; i < mipSlices; i++) {
  98682. //compute LOD from even spacing in smoothness (matching shader calculation)
  98683. var smoothness = i / (mipSlices - 1);
  98684. var roughness = 1 - smoothness;
  98685. var minLODIndex = offset; // roughness = 0
  98686. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  98687. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  98688. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  98689. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  98690. glTextureFromLod.isCube = true;
  98691. glTextureFromLod.invertY = true;
  98692. glTextureFromLod.generateMipMaps = false;
  98693. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  98694. // Wrap in a base texture for easy binding.
  98695. var lodTexture = new BABYLON.BaseTexture(null);
  98696. lodTexture.isCube = true;
  98697. lodTexture._texture = glTextureFromLod;
  98698. lodTextures[mipmapIndex] = lodTexture;
  98699. switch (i) {
  98700. case 0:
  98701. texture._lodTextureLow = lodTexture;
  98702. break;
  98703. case 1:
  98704. texture._lodTextureMid = lodTexture;
  98705. break;
  98706. case 2:
  98707. texture._lodTextureHigh = lodTexture;
  98708. break;
  98709. }
  98710. }
  98711. }
  98712. }
  98713. var promises = [];
  98714. var _loop_3 = function (i) {
  98715. var _loop_4 = function (face) {
  98716. // Constructs an image element from image data
  98717. var bytes = imageData[i][face];
  98718. var blob = new Blob([bytes], { type: 'image/png' });
  98719. var url = URL.createObjectURL(blob);
  98720. var image = new Image();
  98721. image.src = url;
  98722. // Enqueue promise to upload to the texture.
  98723. var promise = new Promise(function (resolve, reject) {
  98724. image.onload = function () {
  98725. if (expandTexture) {
  98726. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  98727. reject(message);
  98728. }, image);
  98729. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98730. // Uncompress the data to a RTT
  98731. rgbdPostProcess.onApply = function (effect) {
  98732. effect._bindTexture("textureSampler", tempTexture_1);
  98733. effect.setFloat2("scale", 1, 1);
  98734. };
  98735. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  98736. // Cleanup
  98737. engine.restoreDefaultFramebuffer();
  98738. tempTexture_1.dispose();
  98739. window.URL.revokeObjectURL(url);
  98740. resolve();
  98741. });
  98742. }
  98743. else {
  98744. engine._uploadImageToTexture(texture, image, face, i);
  98745. // Upload the face to the non lod texture support
  98746. if (generateNonLODTextures) {
  98747. var lodTexture = lodTextures[i];
  98748. if (lodTexture) {
  98749. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  98750. }
  98751. }
  98752. resolve();
  98753. }
  98754. };
  98755. image.onerror = function (error) {
  98756. reject(error);
  98757. };
  98758. });
  98759. promises.push(promise);
  98760. };
  98761. // All faces
  98762. for (var face = 0; face < 6; face++) {
  98763. _loop_4(face);
  98764. }
  98765. };
  98766. // All mipmaps up to provided number of images
  98767. for (var i = 0; i < imageData.length; i++) {
  98768. _loop_3(i);
  98769. }
  98770. // Fill remaining mipmaps with black textures.
  98771. if (imageData.length < mipmapsCount) {
  98772. var data = void 0;
  98773. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  98774. var dataLength = size * size * 4;
  98775. switch (texture.type) {
  98776. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  98777. data = new Uint8Array(dataLength);
  98778. break;
  98779. }
  98780. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  98781. data = new Uint16Array(dataLength);
  98782. break;
  98783. }
  98784. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  98785. data = new Float32Array(dataLength);
  98786. break;
  98787. }
  98788. }
  98789. for (var i = imageData.length; i < mipmapsCount; i++) {
  98790. for (var face = 0; face < 6; face++) {
  98791. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  98792. }
  98793. }
  98794. }
  98795. // Once all done, finishes the cleanup and return
  98796. return Promise.all(promises).then(function () {
  98797. // Release temp RTT.
  98798. if (cubeRtt) {
  98799. engine._releaseFramebufferObjects(cubeRtt);
  98800. cubeRtt._swapAndDie(texture);
  98801. }
  98802. // Release temp Post Process.
  98803. if (rgbdPostProcess) {
  98804. rgbdPostProcess.dispose();
  98805. }
  98806. // Flag internal texture as ready in case they are in use.
  98807. if (generateNonLODTextures) {
  98808. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  98809. texture._lodTextureHigh._texture.isReady = true;
  98810. }
  98811. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  98812. texture._lodTextureMid._texture.isReady = true;
  98813. }
  98814. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  98815. texture._lodTextureLow._texture.isReady = true;
  98816. }
  98817. }
  98818. });
  98819. };
  98820. /**
  98821. * Uploads spherical polynomials information to the texture.
  98822. * @param texture defines the texture we are trying to upload the information to
  98823. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  98824. */
  98825. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  98826. if (info.version !== 1) {
  98827. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  98828. }
  98829. var irradianceInfo = info.irradiance;
  98830. if (!irradianceInfo) {
  98831. return;
  98832. }
  98833. var sp = new BABYLON.SphericalPolynomial();
  98834. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  98835. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  98836. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  98837. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  98838. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  98839. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  98840. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  98841. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  98842. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  98843. texture._sphericalPolynomial = sp;
  98844. };
  98845. /**
  98846. * Magic number identifying the env file.
  98847. */
  98848. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  98849. return EnvironmentTextureTools;
  98850. }());
  98851. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  98852. })(BABYLON || (BABYLON = {}));
  98853. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  98854. var BABYLON;
  98855. (function (BABYLON) {
  98856. /**
  98857. * Implementation of the ENV Texture Loader.
  98858. */
  98859. var ENVTextureLoader = /** @class */ (function () {
  98860. function ENVTextureLoader() {
  98861. /**
  98862. * Defines wether the loader supports cascade loading the different faces.
  98863. */
  98864. this.supportCascades = false;
  98865. }
  98866. /**
  98867. * This returns if the loader support the current file information.
  98868. * @param extension defines the file extension of the file being loaded
  98869. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98870. * @param fallback defines the fallback internal texture if any
  98871. * @param isBase64 defines whether the texture is encoded as a base64
  98872. * @param isBuffer defines whether the texture data are stored as a buffer
  98873. * @returns true if the loader can load the specified file
  98874. */
  98875. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98876. return extension.indexOf(".env") === 0;
  98877. };
  98878. /**
  98879. * Transform the url before loading if required.
  98880. * @param rootUrl the url of the texture
  98881. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98882. * @returns the transformed texture
  98883. */
  98884. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98885. return rootUrl;
  98886. };
  98887. /**
  98888. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98889. * @param rootUrl the url of the texture
  98890. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98891. * @returns the fallback texture
  98892. */
  98893. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98894. return null;
  98895. };
  98896. /**
  98897. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98898. * @param data contains the texture data
  98899. * @param texture defines the BabylonJS internal texture
  98900. * @param createPolynomials will be true if polynomials have been requested
  98901. * @param onLoad defines the callback to trigger once the texture is ready
  98902. * @param onError defines the callback to trigger in case of error
  98903. */
  98904. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98905. if (Array.isArray(data)) {
  98906. return;
  98907. }
  98908. data = data;
  98909. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  98910. if (info) {
  98911. texture.width = info.width;
  98912. texture.height = info.width;
  98913. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  98914. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  98915. texture.isReady = true;
  98916. if (onLoad) {
  98917. onLoad();
  98918. }
  98919. });
  98920. }
  98921. else if (onError) {
  98922. onError("Can not parse the environment file", null);
  98923. }
  98924. };
  98925. /**
  98926. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98927. * @param data contains the texture data
  98928. * @param texture defines the BabylonJS internal texture
  98929. * @param callback defines the method to call once ready to upload
  98930. */
  98931. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  98932. throw ".env not supported in 2d.";
  98933. };
  98934. return ENVTextureLoader;
  98935. }());
  98936. // Register the loader.
  98937. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  98938. })(BABYLON || (BABYLON = {}));
  98939. //# sourceMappingURL=babylon.envTextureLoader.js.map
  98940. var BABYLON;
  98941. (function (BABYLON) {
  98942. /**
  98943. * Renders a layer on top of an existing scene
  98944. */
  98945. var UtilityLayerRenderer = /** @class */ (function () {
  98946. /**
  98947. * Instantiates a UtilityLayerRenderer
  98948. * @param originalScene the original scene that will be rendered on top of
  98949. */
  98950. function UtilityLayerRenderer(
  98951. /** the original scene that will be rendered on top of */
  98952. originalScene) {
  98953. var _this = this;
  98954. this.originalScene = originalScene;
  98955. this._pointerCaptures = {};
  98956. this._lastPointerEvents = {};
  98957. /**
  98958. * If the utility layer should automatically be rendered on top of existing scene
  98959. */
  98960. this.shouldRender = true;
  98961. /**
  98962. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  98963. */
  98964. this.onlyCheckPointerDownEvents = true;
  98965. /**
  98966. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  98967. */
  98968. this.processAllEvents = false;
  98969. /**
  98970. * Observable raised when the pointer move from the utility layer scene to the main scene
  98971. */
  98972. this.onPointerOutObservable = new BABYLON.Observable();
  98973. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  98974. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  98975. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  98976. this.utilityLayerScene._allowPostProcessClearColor = false;
  98977. originalScene.getEngine().scenes.pop();
  98978. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  98979. this.utilityLayerScene.detachControl();
  98980. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  98981. if (!_this.processAllEvents) {
  98982. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  98983. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  98984. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  98985. return;
  98986. }
  98987. }
  98988. var pointerEvent = (prePointerInfo.event);
  98989. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  98990. _this._pointerCaptures[pointerEvent.pointerId] = false;
  98991. return;
  98992. }
  98993. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  98994. if (!prePointerInfo.ray && utilityScenePick) {
  98995. prePointerInfo.ray = utilityScenePick.ray;
  98996. }
  98997. // always fire the prepointer oversvable
  98998. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  98999. // allow every non pointer down event to flow to the utility layer
  99000. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  99001. if (!prePointerInfo.skipOnPointerObservable) {
  99002. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99003. }
  99004. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  99005. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99006. }
  99007. return;
  99008. }
  99009. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  99010. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  99011. if (utilityScenePick && utilityScenePick.hit) {
  99012. if (!prePointerInfo.skipOnPointerObservable) {
  99013. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99014. }
  99015. prePointerInfo.skipOnPointerObservable = true;
  99016. }
  99017. }
  99018. else {
  99019. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99020. var pointerEvent_1 = (prePointerInfo.event);
  99021. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99022. if (originalScenePick && utilityScenePick) {
  99023. // No pick in utility scene
  99024. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99025. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99026. // We touched an utility mesh present in the main scene
  99027. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99028. prePointerInfo.skipOnPointerObservable = true;
  99029. }
  99030. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99031. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99032. }
  99033. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99034. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99035. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99036. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99037. }
  99038. }
  99039. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99040. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99041. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99042. // If a previous utility layer set this, do not unset this
  99043. if (!prePointerInfo.skipOnPointerObservable) {
  99044. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99045. }
  99046. }
  99047. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99048. // We have a pick in both scenes but main is closer than utility
  99049. // We touched an utility mesh present in the main scene
  99050. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99051. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99052. prePointerInfo.skipOnPointerObservable = true;
  99053. }
  99054. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99055. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99056. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99057. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99058. }
  99059. }
  99060. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99061. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99062. }
  99063. }
  99064. }
  99065. });
  99066. // Render directly on top of existing scene without clearing
  99067. this.utilityLayerScene.autoClear = false;
  99068. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99069. if (_this.shouldRender) {
  99070. _this.render();
  99071. }
  99072. });
  99073. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99074. _this.dispose();
  99075. });
  99076. this._updateCamera();
  99077. }
  99078. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99079. /**
  99080. * 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)
  99081. */
  99082. get: function () {
  99083. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99084. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99085. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99086. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99087. });
  99088. }
  99089. return UtilityLayerRenderer._DefaultUtilityLayer;
  99090. },
  99091. enumerable: true,
  99092. configurable: true
  99093. });
  99094. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99095. /**
  99096. * 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)
  99097. */
  99098. get: function () {
  99099. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99100. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99101. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99102. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99103. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99104. });
  99105. }
  99106. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99107. },
  99108. enumerable: true,
  99109. configurable: true
  99110. });
  99111. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99112. if (!prePointerInfo.skipOnPointerObservable) {
  99113. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99114. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99115. }
  99116. };
  99117. /**
  99118. * Renders the utility layers scene on top of the original scene
  99119. */
  99120. UtilityLayerRenderer.prototype.render = function () {
  99121. this._updateCamera();
  99122. if (this.utilityLayerScene.activeCamera) {
  99123. // Set the camera's scene to utility layers scene
  99124. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99125. var camera = this.utilityLayerScene.activeCamera;
  99126. camera._scene = this.utilityLayerScene;
  99127. if (camera.leftCamera) {
  99128. camera.leftCamera._scene = this.utilityLayerScene;
  99129. }
  99130. if (camera.rightCamera) {
  99131. camera.rightCamera._scene = this.utilityLayerScene;
  99132. }
  99133. this.utilityLayerScene.render(false);
  99134. // Reset camera's scene back to original
  99135. camera._scene = oldScene;
  99136. if (camera.leftCamera) {
  99137. camera.leftCamera._scene = oldScene;
  99138. }
  99139. if (camera.rightCamera) {
  99140. camera.rightCamera._scene = oldScene;
  99141. }
  99142. }
  99143. };
  99144. /**
  99145. * Disposes of the renderer
  99146. */
  99147. UtilityLayerRenderer.prototype.dispose = function () {
  99148. this.onPointerOutObservable.clear();
  99149. if (this._afterRenderObserver) {
  99150. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99151. }
  99152. if (this._sceneDisposeObserver) {
  99153. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99154. }
  99155. if (this._originalPointerObserver) {
  99156. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99157. }
  99158. this.utilityLayerScene.dispose();
  99159. };
  99160. UtilityLayerRenderer.prototype._updateCamera = function () {
  99161. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99162. };
  99163. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99164. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99165. return UtilityLayerRenderer;
  99166. }());
  99167. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99168. })(BABYLON || (BABYLON = {}));
  99169. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99170. //# sourceMappingURL=babylon.behavior.js.map
  99171. var BABYLON;
  99172. (function (BABYLON) {
  99173. /**
  99174. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99175. */
  99176. var PointerDragBehavior = /** @class */ (function () {
  99177. /**
  99178. * Creates a pointer drag behavior that can be attached to a mesh
  99179. * @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)
  99180. */
  99181. function PointerDragBehavior(options) {
  99182. /**
  99183. * 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)
  99184. */
  99185. this.maxDragAngle = 0;
  99186. /**
  99187. * @hidden
  99188. */
  99189. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99190. /**
  99191. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99192. */
  99193. this.currentDraggingPointerID = -1;
  99194. /**
  99195. * If the behavior is currently in a dragging state
  99196. */
  99197. this.dragging = false;
  99198. /**
  99199. * 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)
  99200. */
  99201. this.dragDeltaRatio = 0.2;
  99202. /**
  99203. * If the drag plane orientation should be updated during the dragging (Default: true)
  99204. */
  99205. this.updateDragPlane = true;
  99206. // Debug mode will display drag planes to help visualize behavior
  99207. this._debugMode = false;
  99208. this._moving = false;
  99209. /**
  99210. * Fires each time the attached mesh is dragged with the pointer
  99211. * * delta between last drag position and current drag position in world space
  99212. * * dragDistance along the drag axis
  99213. * * dragPlaneNormal normal of the current drag plane used during the drag
  99214. * * dragPlanePoint in world space where the drag intersects the drag plane
  99215. */
  99216. this.onDragObservable = new BABYLON.Observable();
  99217. /**
  99218. * Fires each time a drag begins (eg. mouse down on mesh)
  99219. */
  99220. this.onDragStartObservable = new BABYLON.Observable();
  99221. /**
  99222. * Fires each time a drag ends (eg. mouse release after drag)
  99223. */
  99224. this.onDragEndObservable = new BABYLON.Observable();
  99225. /**
  99226. * If the attached mesh should be moved when dragged
  99227. */
  99228. this.moveAttached = true;
  99229. /**
  99230. * If the drag behavior will react to drag events (Default: true)
  99231. */
  99232. this.enabled = true;
  99233. /**
  99234. * If camera controls should be detached during the drag
  99235. */
  99236. this.detachCameraControls = true;
  99237. /**
  99238. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99239. */
  99240. this.useObjectOrienationForDragging = true;
  99241. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99242. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99243. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99244. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99245. this._attachedElement = null;
  99246. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99247. this._lastPointerRay = {};
  99248. this._dragDelta = new BABYLON.Vector3();
  99249. // Variables to avoid instantiation in the below method
  99250. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99251. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99252. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99253. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99254. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99255. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99256. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99257. this._options = options ? options : {};
  99258. var optionCount = 0;
  99259. if (this._options.dragAxis) {
  99260. optionCount++;
  99261. }
  99262. if (this._options.dragPlaneNormal) {
  99263. optionCount++;
  99264. }
  99265. if (optionCount > 1) {
  99266. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99267. }
  99268. }
  99269. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99270. /**
  99271. * The name of the behavior
  99272. */
  99273. get: function () {
  99274. return "PointerDrag";
  99275. },
  99276. enumerable: true,
  99277. configurable: true
  99278. });
  99279. /**
  99280. * Initializes the behavior
  99281. */
  99282. PointerDragBehavior.prototype.init = function () { };
  99283. /**
  99284. * Attaches the drag behavior the passed in mesh
  99285. * @param ownerNode The mesh that will be dragged around once attached
  99286. */
  99287. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99288. var _this = this;
  99289. this._scene = ownerNode.getScene();
  99290. this._attachedNode = ownerNode;
  99291. // Initialize drag plane to not interfere with existing scene
  99292. if (!PointerDragBehavior._planeScene) {
  99293. if (this._debugMode) {
  99294. PointerDragBehavior._planeScene = this._scene;
  99295. }
  99296. else {
  99297. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99298. PointerDragBehavior._planeScene.detachControl();
  99299. this._scene.getEngine().scenes.pop();
  99300. this._scene.onDisposeObservable.addOnce(function () {
  99301. PointerDragBehavior._planeScene.dispose();
  99302. PointerDragBehavior._planeScene = null;
  99303. });
  99304. }
  99305. }
  99306. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99307. // State of the drag
  99308. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99309. var pickPredicate = function (m) {
  99310. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99311. };
  99312. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99313. if (!_this.enabled) {
  99314. return;
  99315. }
  99316. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99317. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99318. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99319. }
  99320. }
  99321. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99322. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99323. _this.releaseDrag();
  99324. }
  99325. }
  99326. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99327. var pointerId = pointerInfo.event.pointerId;
  99328. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99329. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99330. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99331. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99332. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99333. }
  99334. _this.currentDraggingPointerID = pointerId;
  99335. }
  99336. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99337. if (!_this._lastPointerRay[pointerId]) {
  99338. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99339. }
  99340. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99341. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99342. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99343. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99344. _this._moveDrag(pointerInfo.pickInfo.ray);
  99345. }
  99346. }
  99347. }
  99348. });
  99349. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99350. if (_this._moving && _this.moveAttached) {
  99351. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99352. // Slowly move mesh to avoid jitter
  99353. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99354. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99355. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99356. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99357. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99358. }
  99359. });
  99360. };
  99361. /**
  99362. * Force relase the drag action by code.
  99363. */
  99364. PointerDragBehavior.prototype.releaseDrag = function () {
  99365. this.dragging = false;
  99366. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99367. this.currentDraggingPointerID = -1;
  99368. this._moving = false;
  99369. // Reattach camera controls
  99370. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99371. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99372. }
  99373. };
  99374. /**
  99375. * Simulates the start of a pointer drag event on the behavior
  99376. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99377. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99378. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99379. */
  99380. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99381. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99382. this._startDrag(pointerId, fromRay, startPickedPoint);
  99383. var lastRay = this._lastPointerRay[pointerId];
  99384. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99385. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99386. }
  99387. if (lastRay) {
  99388. // if there was a last pointer ray drag the object there
  99389. this._moveDrag(lastRay);
  99390. }
  99391. };
  99392. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99393. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99394. return;
  99395. }
  99396. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99397. // Create start ray from the camera to the object
  99398. if (fromRay) {
  99399. this._startDragRay.direction.copyFrom(fromRay.direction);
  99400. this._startDragRay.origin.copyFrom(fromRay.origin);
  99401. }
  99402. else {
  99403. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99404. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99405. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99406. }
  99407. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99408. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99409. if (pickedPoint) {
  99410. this.dragging = true;
  99411. this.currentDraggingPointerID = pointerId;
  99412. this.lastDragPosition.copyFrom(pickedPoint);
  99413. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99414. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99415. // Detatch camera controls
  99416. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99417. if (this._scene.activeCamera.inputs.attachedElement) {
  99418. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99419. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99420. }
  99421. else {
  99422. this._attachedElement = null;
  99423. }
  99424. }
  99425. }
  99426. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99427. };
  99428. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99429. this._moving = true;
  99430. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99431. if (pickedPoint) {
  99432. if (this.updateDragPlane) {
  99433. this._updateDragPlanePosition(ray, pickedPoint);
  99434. }
  99435. var dragLength = 0;
  99436. // depending on the drag mode option drag accordingly
  99437. if (this._options.dragAxis) {
  99438. // Convert local drag axis to world
  99439. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99440. // Project delta drag from the drag plane onto the drag axis
  99441. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99442. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99443. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99444. }
  99445. else {
  99446. dragLength = this._dragDelta.length();
  99447. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99448. }
  99449. this._targetPosition.addInPlace(this._dragDelta);
  99450. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99451. this.lastDragPosition.copyFrom(pickedPoint);
  99452. }
  99453. };
  99454. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99455. var _this = this;
  99456. if (!ray) {
  99457. return null;
  99458. }
  99459. // Calculate angle between plane normal and ray
  99460. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99461. // Correct if ray is casted from oposite side
  99462. if (angle > Math.PI / 2) {
  99463. angle = Math.PI - angle;
  99464. }
  99465. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99466. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99467. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99468. // Invert ray direction along the towards object axis
  99469. this._tmpVector.copyFrom(ray.direction);
  99470. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99471. this._alternatePickedPoint.normalize();
  99472. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99473. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99474. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99475. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99476. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99477. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99478. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99479. return this._alternatePickedPoint;
  99480. }
  99481. else {
  99482. return null;
  99483. }
  99484. }
  99485. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99486. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99487. return pickResult.pickedPoint;
  99488. }
  99489. else {
  99490. return null;
  99491. }
  99492. };
  99493. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99494. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99495. this._pointA.copyFrom(dragPlanePosition);
  99496. if (this._options.dragAxis) {
  99497. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99498. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99499. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99500. ray.origin.subtractToRef(this._pointA, this._pointC);
  99501. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99502. // Get perpendicular line from direction to camera and drag axis
  99503. this._pointB.subtractToRef(this._pointA, this._lineA);
  99504. this._pointC.subtractToRef(this._pointA, this._lineB);
  99505. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99506. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99507. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99508. this._lookAt.normalize();
  99509. this._dragPlane.position.copyFrom(this._pointA);
  99510. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99511. this._dragPlane.lookAt(this._lookAt);
  99512. }
  99513. else if (this._options.dragPlaneNormal) {
  99514. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99515. this._dragPlane.position.copyFrom(this._pointA);
  99516. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99517. this._dragPlane.lookAt(this._lookAt);
  99518. }
  99519. else {
  99520. this._dragPlane.position.copyFrom(this._pointA);
  99521. this._dragPlane.lookAt(ray.origin);
  99522. }
  99523. this._dragPlane.computeWorldMatrix(true);
  99524. };
  99525. /**
  99526. * Detaches the behavior from the mesh
  99527. */
  99528. PointerDragBehavior.prototype.detach = function () {
  99529. if (this._pointerObserver) {
  99530. this._scene.onPointerObservable.remove(this._pointerObserver);
  99531. }
  99532. if (this._beforeRenderObserver) {
  99533. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99534. }
  99535. };
  99536. PointerDragBehavior._AnyMouseID = -2;
  99537. return PointerDragBehavior;
  99538. }());
  99539. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99540. })(BABYLON || (BABYLON = {}));
  99541. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99542. var BABYLON;
  99543. (function (BABYLON) {
  99544. /**
  99545. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99546. */
  99547. var MultiPointerScaleBehavior = /** @class */ (function () {
  99548. /**
  99549. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99550. */
  99551. function MultiPointerScaleBehavior() {
  99552. this._startDistance = 0;
  99553. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99554. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99555. this._sceneRenderObserver = null;
  99556. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99557. this._dragBehaviorA.moveAttached = false;
  99558. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99559. this._dragBehaviorB.moveAttached = false;
  99560. }
  99561. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99562. /**
  99563. * The name of the behavior
  99564. */
  99565. get: function () {
  99566. return "MultiPointerScale";
  99567. },
  99568. enumerable: true,
  99569. configurable: true
  99570. });
  99571. /**
  99572. * Initializes the behavior
  99573. */
  99574. MultiPointerScaleBehavior.prototype.init = function () { };
  99575. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99576. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99577. };
  99578. /**
  99579. * Attaches the scale behavior the passed in mesh
  99580. * @param ownerNode The mesh that will be scaled around once attached
  99581. */
  99582. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99583. var _this = this;
  99584. this._ownerNode = ownerNode;
  99585. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99586. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99587. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99588. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99589. _this._dragBehaviorA.releaseDrag();
  99590. }
  99591. else {
  99592. _this._initialScale.copyFrom(ownerNode.scaling);
  99593. _this._startDistance = _this._getCurrentDistance();
  99594. }
  99595. }
  99596. });
  99597. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99598. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99599. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99600. _this._dragBehaviorB.releaseDrag();
  99601. }
  99602. else {
  99603. _this._initialScale.copyFrom(ownerNode.scaling);
  99604. _this._startDistance = _this._getCurrentDistance();
  99605. }
  99606. }
  99607. });
  99608. // Once both drag behaviors are active scale based on the distance between the two pointers
  99609. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99610. behavior.onDragObservable.add(function () {
  99611. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99612. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99613. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99614. }
  99615. });
  99616. });
  99617. ownerNode.addBehavior(this._dragBehaviorA);
  99618. ownerNode.addBehavior(this._dragBehaviorB);
  99619. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99620. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99621. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99622. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99623. if (change.length() > 0.01) {
  99624. ownerNode.scaling.addInPlace(change);
  99625. }
  99626. }
  99627. });
  99628. };
  99629. /**
  99630. * Detaches the behavior from the mesh
  99631. */
  99632. MultiPointerScaleBehavior.prototype.detach = function () {
  99633. var _this = this;
  99634. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99635. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99636. behavior.onDragStartObservable.clear();
  99637. behavior.onDragObservable.clear();
  99638. _this._ownerNode.removeBehavior(behavior);
  99639. });
  99640. };
  99641. return MultiPointerScaleBehavior;
  99642. }());
  99643. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99644. })(BABYLON || (BABYLON = {}));
  99645. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99646. var BABYLON;
  99647. (function (BABYLON) {
  99648. /**
  99649. * 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
  99650. */
  99651. var SixDofDragBehavior = /** @class */ (function () {
  99652. /**
  99653. * 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
  99654. */
  99655. function SixDofDragBehavior() {
  99656. this._sceneRenderObserver = null;
  99657. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99658. this._moving = false;
  99659. this._startingOrientation = new BABYLON.Quaternion();
  99660. /**
  99661. * 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)
  99662. */
  99663. this.zDragFactor = 3;
  99664. /**
  99665. * If the behavior is currently in a dragging state
  99666. */
  99667. this.dragging = false;
  99668. /**
  99669. * 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)
  99670. */
  99671. this.dragDeltaRatio = 0.2;
  99672. /**
  99673. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99674. */
  99675. this.currentDraggingPointerID = -1;
  99676. /**
  99677. * If camera controls should be detached during the drag
  99678. */
  99679. this.detachCameraControls = true;
  99680. /**
  99681. * Fires each time a drag starts
  99682. */
  99683. this.onDragStartObservable = new BABYLON.Observable();
  99684. /**
  99685. * Fires each time a drag ends (eg. mouse release after drag)
  99686. */
  99687. this.onDragEndObservable = new BABYLON.Observable();
  99688. }
  99689. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  99690. /**
  99691. * The name of the behavior
  99692. */
  99693. get: function () {
  99694. return "SixDofDrag";
  99695. },
  99696. enumerable: true,
  99697. configurable: true
  99698. });
  99699. /**
  99700. * Initializes the behavior
  99701. */
  99702. SixDofDragBehavior.prototype.init = function () { };
  99703. /**
  99704. * Attaches the scale behavior the passed in mesh
  99705. * @param ownerNode The mesh that will be scaled around once attached
  99706. */
  99707. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  99708. var _this = this;
  99709. this._ownerNode = ownerNode;
  99710. this._scene = this._ownerNode.getScene();
  99711. if (!SixDofDragBehavior._virtualScene) {
  99712. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  99713. this._scene.getEngine().scenes.pop();
  99714. }
  99715. var pickedMesh = null;
  99716. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  99717. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  99718. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  99719. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  99720. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  99721. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  99722. var pickPredicate = function (m) {
  99723. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  99724. };
  99725. var attachedElement = null;
  99726. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99727. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99728. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99729. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  99730. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  99731. }
  99732. pickedMesh = _this._ownerNode;
  99733. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  99734. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  99735. // Set position and orientation of the controller
  99736. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  99737. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  99738. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  99739. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99740. pickedMesh.computeWorldMatrix();
  99741. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  99742. if (!pickedMesh.rotationQuaternion) {
  99743. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  99744. }
  99745. var oldParent = pickedMesh.parent;
  99746. pickedMesh.setParent(null);
  99747. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  99748. pickedMesh.setParent(oldParent);
  99749. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  99750. // Update state
  99751. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  99752. _this.dragging = true;
  99753. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  99754. // Detatch camera controls
  99755. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  99756. if (_this._scene.activeCamera.inputs.attachedElement) {
  99757. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  99758. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  99759. }
  99760. else {
  99761. attachedElement = null;
  99762. }
  99763. }
  99764. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  99765. _this.onDragStartObservable.notifyObservers({});
  99766. }
  99767. }
  99768. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99769. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99770. _this.dragging = false;
  99771. _this._moving = false;
  99772. _this.currentDraggingPointerID = -1;
  99773. pickedMesh = null;
  99774. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99775. // Reattach camera controls
  99776. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  99777. _this._scene.activeCamera.attachControl(attachedElement, true);
  99778. }
  99779. _this.onDragEndObservable.notifyObservers({});
  99780. }
  99781. }
  99782. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99783. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  99784. var zDragFactor = _this.zDragFactor;
  99785. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  99786. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  99787. zDragFactor = 0;
  99788. }
  99789. // Calculate controller drag distance in controller space
  99790. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  99791. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  99792. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  99793. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  99794. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  99795. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  99796. if (_this._virtualDragMesh.position.z < 0) {
  99797. _this._virtualDragMesh.position.z = 0;
  99798. }
  99799. // Update the controller position
  99800. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  99801. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  99802. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99803. // Move the virtualObjectsPosition into the picked mesh's space if needed
  99804. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  99805. if (pickedMesh.parent) {
  99806. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  99807. }
  99808. if (!_this._moving) {
  99809. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  99810. }
  99811. _this._moving = true;
  99812. }
  99813. }
  99814. });
  99815. var tmpQuaternion = new BABYLON.Quaternion();
  99816. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99817. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99818. if (_this.dragging && _this._moving && pickedMesh) {
  99819. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  99820. // Slowly move mesh to avoid jitter
  99821. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  99822. // Get change in rotation
  99823. tmpQuaternion.copyFrom(_this._startingOrientation);
  99824. tmpQuaternion.x = -tmpQuaternion.x;
  99825. tmpQuaternion.y = -tmpQuaternion.y;
  99826. tmpQuaternion.z = -tmpQuaternion.z;
  99827. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  99828. // Convert change in rotation to only y axis rotation
  99829. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  99830. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  99831. // Slowly move mesh to avoid jitter
  99832. var oldParent = pickedMesh.parent;
  99833. pickedMesh.setParent(null);
  99834. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  99835. pickedMesh.setParent(oldParent);
  99836. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  99837. }
  99838. });
  99839. };
  99840. /**
  99841. * Detaches the behavior from the mesh
  99842. */
  99843. SixDofDragBehavior.prototype.detach = function () {
  99844. if (this._scene) {
  99845. this._scene.onPointerObservable.remove(this._pointerObserver);
  99846. }
  99847. if (this._ownerNode) {
  99848. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99849. }
  99850. if (this._virtualOriginMesh) {
  99851. this._virtualOriginMesh.dispose();
  99852. }
  99853. if (this._virtualDragMesh) {
  99854. this._virtualDragMesh.dispose();
  99855. }
  99856. this.onDragEndObservable.clear();
  99857. this.onDragStartObservable.clear();
  99858. };
  99859. return SixDofDragBehavior;
  99860. }());
  99861. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  99862. })(BABYLON || (BABYLON = {}));
  99863. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  99864. var BABYLON;
  99865. (function (BABYLON) {
  99866. /**
  99867. * @hidden
  99868. */
  99869. var FaceDirectionInfo = /** @class */ (function () {
  99870. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  99871. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  99872. if (diff === void 0) { diff = 0; }
  99873. if (ignore === void 0) { ignore = false; }
  99874. this.direction = direction;
  99875. this.rotatedDirection = rotatedDirection;
  99876. this.diff = diff;
  99877. this.ignore = ignore;
  99878. }
  99879. return FaceDirectionInfo;
  99880. }());
  99881. /**
  99882. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  99883. */
  99884. var AttachToBoxBehavior = /** @class */ (function () {
  99885. /**
  99886. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  99887. * @param ui The transform node that should be attched to the mesh
  99888. */
  99889. function AttachToBoxBehavior(ui) {
  99890. this.ui = ui;
  99891. /**
  99892. * The name of the behavior
  99893. */
  99894. this.name = "AttachToBoxBehavior";
  99895. /**
  99896. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  99897. */
  99898. this.distanceAwayFromFace = 0.15;
  99899. /**
  99900. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  99901. */
  99902. this.distanceAwayFromBottomOfFace = 0.15;
  99903. 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))];
  99904. this._tmpMatrix = new BABYLON.Matrix();
  99905. this._tmpVector = new BABYLON.Vector3();
  99906. this._zeroVector = BABYLON.Vector3.Zero();
  99907. this._lookAtTmpMatrix = new BABYLON.Matrix();
  99908. /* Does nothing */
  99909. }
  99910. /**
  99911. * Initializes the behavior
  99912. */
  99913. AttachToBoxBehavior.prototype.init = function () {
  99914. /* Does nothing */
  99915. };
  99916. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  99917. var _this = this;
  99918. // Go over each face and calculate the angle between the face's normal and targetDirection
  99919. this._faceVectors.forEach(function (v) {
  99920. if (!_this._target.rotationQuaternion) {
  99921. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  99922. }
  99923. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  99924. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  99925. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  99926. });
  99927. // Return the face information of the one with the normal closeset to target direction
  99928. return this._faceVectors.reduce(function (min, p) {
  99929. if (min.ignore) {
  99930. return p;
  99931. }
  99932. else if (p.ignore) {
  99933. return min;
  99934. }
  99935. else {
  99936. return min.diff < p.diff ? min : p;
  99937. }
  99938. }, this._faceVectors[0]);
  99939. };
  99940. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  99941. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  99942. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  99943. this._lookAtTmpMatrix.invert();
  99944. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  99945. };
  99946. /**
  99947. * Attaches the AttachToBoxBehavior to the passed in mesh
  99948. * @param target The mesh that the specified node will be attached to
  99949. */
  99950. AttachToBoxBehavior.prototype.attach = function (target) {
  99951. var _this = this;
  99952. this._target = target;
  99953. this._scene = this._target.getScene();
  99954. // Every frame, update the app bars position
  99955. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99956. if (!_this._scene.activeCamera) {
  99957. return;
  99958. }
  99959. // Find the face closest to the cameras position
  99960. var cameraPos = _this._scene.activeCamera.position;
  99961. if (_this._scene.activeCamera.devicePosition) {
  99962. cameraPos = _this._scene.activeCamera.devicePosition;
  99963. }
  99964. var facing = _this._closestFace(cameraPos.subtract(target.position));
  99965. if (_this._scene.activeCamera.leftCamera) {
  99966. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  99967. }
  99968. else {
  99969. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  99970. }
  99971. // Get camera up direction
  99972. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  99973. // Ignore faces to not select a parrelel face for the up vector of the UI
  99974. _this._faceVectors.forEach(function (v) {
  99975. if (facing.direction.x && v.direction.x) {
  99976. v.ignore = true;
  99977. }
  99978. if (facing.direction.y && v.direction.y) {
  99979. v.ignore = true;
  99980. }
  99981. if (facing.direction.z && v.direction.z) {
  99982. v.ignore = true;
  99983. }
  99984. });
  99985. var facingUp = _this._closestFace(_this._tmpVector);
  99986. // Unignore faces
  99987. _this._faceVectors.forEach(function (v) {
  99988. v.ignore = false;
  99989. });
  99990. // Position the app bar on that face
  99991. _this.ui.position.copyFrom(target.position);
  99992. if (facing.direction.x) {
  99993. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  99994. _this.ui.position.addInPlace(_this._tmpVector);
  99995. }
  99996. if (facing.direction.y) {
  99997. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  99998. _this.ui.position.addInPlace(_this._tmpVector);
  99999. }
  100000. if (facing.direction.z) {
  100001. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100002. _this.ui.position.addInPlace(_this._tmpVector);
  100003. }
  100004. // Rotate to be oriented properly to the camera
  100005. if (!_this.ui.rotationQuaternion) {
  100006. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  100007. }
  100008. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  100009. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  100010. // Place ui the correct distance from the bottom of the mesh
  100011. if (facingUp.direction.x) {
  100012. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  100013. }
  100014. if (facingUp.direction.y) {
  100015. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100016. }
  100017. if (facingUp.direction.z) {
  100018. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100019. }
  100020. _this.ui.position.addInPlace(_this._tmpVector);
  100021. });
  100022. };
  100023. /**
  100024. * Detaches the behavior from the mesh
  100025. */
  100026. AttachToBoxBehavior.prototype.detach = function () {
  100027. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100028. };
  100029. return AttachToBoxBehavior;
  100030. }());
  100031. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100032. })(BABYLON || (BABYLON = {}));
  100033. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100034. var BABYLON;
  100035. (function (BABYLON) {
  100036. /**
  100037. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100038. */
  100039. var FadeInOutBehavior = /** @class */ (function () {
  100040. /**
  100041. * Instatiates the FadeInOutBehavior
  100042. */
  100043. function FadeInOutBehavior() {
  100044. var _this = this;
  100045. /**
  100046. * Time in milliseconds to delay before fading in (Default: 0)
  100047. */
  100048. this.delay = 0;
  100049. /**
  100050. * Time in milliseconds for the mesh to fade in (Default: 300)
  100051. */
  100052. this.fadeInTime = 300;
  100053. this._millisecondsPerFrame = 1000 / 60;
  100054. this._hovered = false;
  100055. this._hoverValue = 0;
  100056. this._ownerNode = null;
  100057. this._update = function () {
  100058. if (_this._ownerNode) {
  100059. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100060. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100061. if (_this._ownerNode.visibility > 1) {
  100062. _this._setAllVisibility(_this._ownerNode, 1);
  100063. _this._hoverValue = _this.fadeInTime + _this.delay;
  100064. return;
  100065. }
  100066. else if (_this._ownerNode.visibility < 0) {
  100067. _this._setAllVisibility(_this._ownerNode, 0);
  100068. if (_this._hoverValue < 0) {
  100069. _this._hoverValue = 0;
  100070. return;
  100071. }
  100072. }
  100073. setTimeout(_this._update, _this._millisecondsPerFrame);
  100074. }
  100075. };
  100076. }
  100077. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100078. /**
  100079. * The name of the behavior
  100080. */
  100081. get: function () {
  100082. return "FadeInOut";
  100083. },
  100084. enumerable: true,
  100085. configurable: true
  100086. });
  100087. /**
  100088. * Initializes the behavior
  100089. */
  100090. FadeInOutBehavior.prototype.init = function () {
  100091. };
  100092. /**
  100093. * Attaches the fade behavior on the passed in mesh
  100094. * @param ownerNode The mesh that will be faded in/out once attached
  100095. */
  100096. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100097. this._ownerNode = ownerNode;
  100098. this._setAllVisibility(this._ownerNode, 0);
  100099. };
  100100. /**
  100101. * Detaches the behavior from the mesh
  100102. */
  100103. FadeInOutBehavior.prototype.detach = function () {
  100104. this._ownerNode = null;
  100105. };
  100106. /**
  100107. * Triggers the mesh to begin fading in or out
  100108. * @param value if the object should fade in or out (true to fade in)
  100109. */
  100110. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100111. this._hovered = value;
  100112. this._update();
  100113. };
  100114. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100115. var _this = this;
  100116. mesh.visibility = value;
  100117. mesh.getChildMeshes().forEach(function (c) {
  100118. _this._setAllVisibility(c, value);
  100119. });
  100120. };
  100121. return FadeInOutBehavior;
  100122. }());
  100123. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100124. })(BABYLON || (BABYLON = {}));
  100125. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100126. var BABYLON;
  100127. (function (BABYLON) {
  100128. /**
  100129. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100130. */
  100131. var Gizmo = /** @class */ (function () {
  100132. /**
  100133. * Creates a gizmo
  100134. * @param gizmoLayer The utility layer the gizmo will be added to
  100135. */
  100136. function Gizmo(
  100137. /** The utility layer the gizmo will be added to */
  100138. gizmoLayer) {
  100139. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100140. var _this = this;
  100141. this.gizmoLayer = gizmoLayer;
  100142. /**
  100143. * Ratio for the scale of the gizmo (Default: 1)
  100144. */
  100145. this.scaleRatio = 1;
  100146. this._tmpMatrix = new BABYLON.Matrix();
  100147. /**
  100148. * If a custom mesh has been set (Default: false)
  100149. */
  100150. this._customMeshSet = false;
  100151. /**
  100152. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100153. */
  100154. this.updateGizmoRotationToMatchAttachedMesh = true;
  100155. /**
  100156. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100157. */
  100158. this.updateGizmoPositionToMatchAttachedMesh = true;
  100159. /**
  100160. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100161. */
  100162. this._updateScale = true;
  100163. this._interactionsEnabled = true;
  100164. this._tempVector = new BABYLON.Vector3();
  100165. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100166. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100167. _this._update();
  100168. });
  100169. this.attachedMesh = null;
  100170. }
  100171. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100172. /**
  100173. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100174. * * When set, interactions will be enabled
  100175. */
  100176. get: function () {
  100177. return this._attachedMesh;
  100178. },
  100179. set: function (value) {
  100180. this._attachedMesh = value;
  100181. this._rootMesh.setEnabled(value ? true : false);
  100182. this._attachedMeshChanged(value);
  100183. },
  100184. enumerable: true,
  100185. configurable: true
  100186. });
  100187. /**
  100188. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100189. * @param mesh The mesh to replace the default mesh of the gizmo
  100190. */
  100191. Gizmo.prototype.setCustomMesh = function (mesh) {
  100192. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100193. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100194. }
  100195. this._rootMesh.getChildMeshes().forEach(function (c) {
  100196. c.dispose();
  100197. });
  100198. mesh.parent = this._rootMesh;
  100199. this._customMeshSet = true;
  100200. };
  100201. Gizmo.prototype._attachedMeshChanged = function (value) {
  100202. };
  100203. /**
  100204. * @hidden
  100205. * Updates the gizmo to match the attached mesh's position/rotation
  100206. */
  100207. Gizmo.prototype._update = function () {
  100208. if (this.attachedMesh) {
  100209. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100210. if (!this._rootMesh.rotationQuaternion) {
  100211. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100212. }
  100213. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100214. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100215. if (this.attachedMesh.scaling.x < 0) {
  100216. this.attachedMesh.scaling.x *= -1;
  100217. }
  100218. if (this.attachedMesh.scaling.y < 0) {
  100219. this.attachedMesh.scaling.y *= -1;
  100220. }
  100221. if (this.attachedMesh.scaling.z < 0) {
  100222. this.attachedMesh.scaling.z *= -1;
  100223. }
  100224. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100225. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100226. this.attachedMesh.computeWorldMatrix();
  100227. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100228. }
  100229. else if (this._rootMesh.rotationQuaternion) {
  100230. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100231. }
  100232. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100233. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100234. }
  100235. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100236. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100237. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100238. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100239. }
  100240. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100241. var dist = this._tempVector.length() * this.scaleRatio;
  100242. this._rootMesh.scaling.set(dist, dist, dist);
  100243. }
  100244. }
  100245. };
  100246. /**
  100247. * Disposes of the gizmo
  100248. */
  100249. Gizmo.prototype.dispose = function () {
  100250. this._rootMesh.dispose();
  100251. if (this._beforeRenderObserver) {
  100252. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100253. }
  100254. };
  100255. return Gizmo;
  100256. }());
  100257. BABYLON.Gizmo = Gizmo;
  100258. })(BABYLON || (BABYLON = {}));
  100259. //# sourceMappingURL=babylon.gizmo.js.map
  100260. var BABYLON;
  100261. (function (BABYLON) {
  100262. /**
  100263. * Single axis drag gizmo
  100264. */
  100265. var AxisDragGizmo = /** @class */ (function (_super) {
  100266. __extends(AxisDragGizmo, _super);
  100267. /**
  100268. * Creates an AxisDragGizmo
  100269. * @param gizmoLayer The utility layer the gizmo will be added to
  100270. * @param dragAxis The axis which the gizmo will be able to drag on
  100271. * @param color The color of the gizmo
  100272. */
  100273. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100274. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100275. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100276. var _this = _super.call(this, gizmoLayer) || this;
  100277. _this._pointerObserver = null;
  100278. /**
  100279. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100280. */
  100281. _this.snapDistance = 0;
  100282. /**
  100283. * Event that fires each time the gizmo snaps to a new location.
  100284. * * snapDistance is the the change in distance
  100285. */
  100286. _this.onSnapObservable = new BABYLON.Observable();
  100287. // Create Material
  100288. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100289. coloredMaterial.disableLighting = true;
  100290. coloredMaterial.emissiveColor = color;
  100291. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100292. hoverMaterial.disableLighting = true;
  100293. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100294. // Build mesh on root node
  100295. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100296. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100297. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100298. arrowTail.color = coloredMaterial.emissiveColor;
  100299. arrow.addChild(arrowMesh);
  100300. arrow.addChild(arrowTail);
  100301. // Position arrow pointing in its drag axis
  100302. arrowMesh.scaling.scaleInPlace(0.05);
  100303. arrowMesh.material = coloredMaterial;
  100304. arrowMesh.rotation.x = Math.PI / 2;
  100305. arrowMesh.position.z += 0.3;
  100306. arrowTail.scaling.scaleInPlace(0.26);
  100307. arrowTail.rotation.x = Math.PI / 2;
  100308. arrowTail.material = coloredMaterial;
  100309. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100310. arrow.scaling.scaleInPlace(1 / 3);
  100311. _this._rootMesh.addChild(arrow);
  100312. var currentSnapDragDistance = 0;
  100313. var tmpVector = new BABYLON.Vector3();
  100314. var tmpSnapEvent = { snapDistance: 0 };
  100315. // Add drag behavior to handle events when the gizmo is dragged
  100316. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100317. _this.dragBehavior.moveAttached = false;
  100318. _this._rootMesh.addBehavior(_this.dragBehavior);
  100319. var localDelta = new BABYLON.Vector3();
  100320. var tmpMatrix = new BABYLON.Matrix();
  100321. _this.dragBehavior.onDragObservable.add(function (event) {
  100322. if (_this.attachedMesh) {
  100323. // Convert delta to local translation if it has a parent
  100324. if (_this.attachedMesh.parent) {
  100325. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100326. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100327. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100328. }
  100329. else {
  100330. localDelta.copyFrom(event.delta);
  100331. }
  100332. // Snapping logic
  100333. if (_this.snapDistance == 0) {
  100334. _this.attachedMesh.position.addInPlace(localDelta);
  100335. }
  100336. else {
  100337. currentSnapDragDistance += event.dragDistance;
  100338. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100339. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100340. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100341. localDelta.normalizeToRef(tmpVector);
  100342. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100343. _this.attachedMesh.position.addInPlace(tmpVector);
  100344. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100345. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100346. }
  100347. }
  100348. }
  100349. });
  100350. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100351. if (_this._customMeshSet) {
  100352. return;
  100353. }
  100354. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100355. var material = isHovered ? hoverMaterial : coloredMaterial;
  100356. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100357. m.material = material;
  100358. if (m.color) {
  100359. m.color = material.emissiveColor;
  100360. }
  100361. });
  100362. });
  100363. return _this;
  100364. }
  100365. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100366. if (this.dragBehavior) {
  100367. this.dragBehavior.enabled = value ? true : false;
  100368. }
  100369. };
  100370. /**
  100371. * Disposes of the gizmo
  100372. */
  100373. AxisDragGizmo.prototype.dispose = function () {
  100374. this.onSnapObservable.clear();
  100375. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100376. this.dragBehavior.detach();
  100377. _super.prototype.dispose.call(this);
  100378. };
  100379. return AxisDragGizmo;
  100380. }(BABYLON.Gizmo));
  100381. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100382. })(BABYLON || (BABYLON = {}));
  100383. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100384. var BABYLON;
  100385. (function (BABYLON) {
  100386. /**
  100387. * Single axis scale gizmo
  100388. */
  100389. var AxisScaleGizmo = /** @class */ (function (_super) {
  100390. __extends(AxisScaleGizmo, _super);
  100391. /**
  100392. * Creates an AxisScaleGizmo
  100393. * @param gizmoLayer The utility layer the gizmo will be added to
  100394. * @param dragAxis The axis which the gizmo will be able to scale on
  100395. * @param color The color of the gizmo
  100396. */
  100397. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100398. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100399. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100400. var _this = _super.call(this, gizmoLayer) || this;
  100401. _this._pointerObserver = null;
  100402. /**
  100403. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100404. */
  100405. _this.snapDistance = 0;
  100406. /**
  100407. * Event that fires each time the gizmo snaps to a new location.
  100408. * * snapDistance is the the change in distance
  100409. */
  100410. _this.onSnapObservable = new BABYLON.Observable();
  100411. /**
  100412. * If the scaling operation should be done on all axis (default: false)
  100413. */
  100414. _this.uniformScaling = false;
  100415. // Create Material
  100416. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100417. _this._coloredMaterial.disableLighting = true;
  100418. _this._coloredMaterial.emissiveColor = color;
  100419. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100420. hoverMaterial.disableLighting = true;
  100421. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100422. // Build mesh on root node
  100423. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100424. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100425. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100426. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100427. arrow.addChild(arrowMesh);
  100428. arrow.addChild(arrowTail);
  100429. // Position arrow pointing in its drag axis
  100430. arrowMesh.scaling.scaleInPlace(0.1);
  100431. arrowMesh.material = _this._coloredMaterial;
  100432. arrowMesh.rotation.x = Math.PI / 2;
  100433. arrowMesh.position.z += 0.3;
  100434. arrowTail.scaling.scaleInPlace(0.26);
  100435. arrowTail.rotation.x = Math.PI / 2;
  100436. arrowTail.material = _this._coloredMaterial;
  100437. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100438. _this._rootMesh.addChild(arrow);
  100439. arrow.scaling.scaleInPlace(1 / 3);
  100440. // Add drag behavior to handle events when the gizmo is dragged
  100441. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100442. _this.dragBehavior.moveAttached = false;
  100443. _this._rootMesh.addBehavior(_this.dragBehavior);
  100444. var currentSnapDragDistance = 0;
  100445. var tmpVector = new BABYLON.Vector3();
  100446. var tmpSnapEvent = { snapDistance: 0 };
  100447. _this.dragBehavior.onDragObservable.add(function (event) {
  100448. if (_this.attachedMesh) {
  100449. // Snapping logic
  100450. var snapped = false;
  100451. var dragSteps = 0;
  100452. if (_this.uniformScaling) {
  100453. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100454. if (tmpVector.y < 0) {
  100455. tmpVector.scaleInPlace(-1);
  100456. }
  100457. }
  100458. else {
  100459. tmpVector.copyFrom(dragAxis);
  100460. }
  100461. if (_this.snapDistance == 0) {
  100462. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100463. }
  100464. else {
  100465. currentSnapDragDistance += event.dragDistance;
  100466. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100467. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100468. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100469. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100470. snapped = true;
  100471. }
  100472. else {
  100473. tmpVector.scaleInPlace(0);
  100474. }
  100475. }
  100476. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100477. if (snapped) {
  100478. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100479. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100480. }
  100481. }
  100482. });
  100483. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100484. if (_this._customMeshSet) {
  100485. return;
  100486. }
  100487. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100488. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100489. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100490. m.material = material;
  100491. if (m.color) {
  100492. m.color = material.emissiveColor;
  100493. }
  100494. });
  100495. });
  100496. return _this;
  100497. }
  100498. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100499. if (this.dragBehavior) {
  100500. this.dragBehavior.enabled = value ? true : false;
  100501. }
  100502. };
  100503. /**
  100504. * Disposes of the gizmo
  100505. */
  100506. AxisScaleGizmo.prototype.dispose = function () {
  100507. this.onSnapObservable.clear();
  100508. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100509. this.dragBehavior.detach();
  100510. _super.prototype.dispose.call(this);
  100511. };
  100512. /**
  100513. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100514. * @param mesh The mesh to replace the default mesh of the gizmo
  100515. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100516. */
  100517. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100518. var _this = this;
  100519. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100520. _super.prototype.setCustomMesh.call(this, mesh);
  100521. if (useGizmoMaterial) {
  100522. this._rootMesh.getChildMeshes().forEach(function (m) {
  100523. m.material = _this._coloredMaterial;
  100524. if (m.color) {
  100525. m.color = _this._coloredMaterial.emissiveColor;
  100526. }
  100527. });
  100528. this._customMeshSet = false;
  100529. }
  100530. };
  100531. return AxisScaleGizmo;
  100532. }(BABYLON.Gizmo));
  100533. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100534. })(BABYLON || (BABYLON = {}));
  100535. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100536. var BABYLON;
  100537. (function (BABYLON) {
  100538. /**
  100539. * Single plane rotation gizmo
  100540. */
  100541. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100542. __extends(PlaneRotationGizmo, _super);
  100543. /**
  100544. * Creates a PlaneRotationGizmo
  100545. * @param gizmoLayer The utility layer the gizmo will be added to
  100546. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100547. * @param color The color of the gizmo
  100548. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100549. */
  100550. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  100551. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100552. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100553. if (tessellation === void 0) { tessellation = 32; }
  100554. var _this = _super.call(this, gizmoLayer) || this;
  100555. _this._pointerObserver = null;
  100556. /**
  100557. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100558. */
  100559. _this.snapDistance = 0;
  100560. /**
  100561. * Event that fires each time the gizmo snaps to a new location.
  100562. * * snapDistance is the the change in distance
  100563. */
  100564. _this.onSnapObservable = new BABYLON.Observable();
  100565. // Create Material
  100566. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100567. coloredMaterial.disableLighting = true;
  100568. coloredMaterial.emissiveColor = color;
  100569. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100570. hoverMaterial.disableLighting = true;
  100571. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100572. // Build mesh on root node
  100573. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100574. // Create circle out of lines
  100575. var radius = 0.8;
  100576. var points = new Array();
  100577. for (var i = 0; i < tessellation; i++) {
  100578. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100579. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100580. }
  100581. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100582. rotationMesh.color = coloredMaterial.emissiveColor;
  100583. // Position arrow pointing in its drag axis
  100584. rotationMesh.scaling.scaleInPlace(0.26);
  100585. rotationMesh.material = coloredMaterial;
  100586. rotationMesh.rotation.x = Math.PI / 2;
  100587. parentMesh.addChild(rotationMesh);
  100588. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100589. _this._rootMesh.addChild(parentMesh);
  100590. parentMesh.scaling.scaleInPlace(1 / 3);
  100591. // Add drag behavior to handle events when the gizmo is dragged
  100592. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100593. _this.dragBehavior.moveAttached = false;
  100594. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100595. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100596. _this._rootMesh.addBehavior(_this.dragBehavior);
  100597. var lastDragPosition = new BABYLON.Vector3();
  100598. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100599. if (_this.attachedMesh) {
  100600. lastDragPosition.copyFrom(e.dragPlanePoint);
  100601. }
  100602. });
  100603. var rotationMatrix = new BABYLON.Matrix();
  100604. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100605. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100606. var tmpSnapEvent = { snapDistance: 0 };
  100607. var currentSnapDragDistance = 0;
  100608. var tmpMatrix = new BABYLON.Matrix();
  100609. var tmpVector = new BABYLON.Vector3();
  100610. var amountToRotate = new BABYLON.Quaternion();
  100611. _this.dragBehavior.onDragObservable.add(function (event) {
  100612. if (_this.attachedMesh) {
  100613. if (!_this.attachedMesh.rotationQuaternion) {
  100614. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100615. }
  100616. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100617. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100618. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100619. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100620. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100621. var angle = Math.atan2(cross.length(), dot);
  100622. planeNormalTowardsCamera.copyFrom(planeNormal);
  100623. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100624. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100625. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100626. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100627. }
  100628. // Flip up vector depending on which side the camera is on
  100629. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100630. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100631. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100632. planeNormalTowardsCamera.scaleInPlace(-1);
  100633. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100634. }
  100635. }
  100636. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100637. if (halfCircleSide)
  100638. angle = -angle;
  100639. // Snapping logic
  100640. var snapped = false;
  100641. if (_this.snapDistance != 0) {
  100642. currentSnapDragDistance += angle;
  100643. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100644. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100645. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100646. angle = _this.snapDistance * dragSteps;
  100647. snapped = true;
  100648. }
  100649. else {
  100650. angle = 0;
  100651. }
  100652. }
  100653. // If the mesh has a parent, convert needed world rotation to local rotation
  100654. tmpMatrix.reset();
  100655. if (_this.attachedMesh.parent) {
  100656. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100657. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  100658. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  100659. }
  100660. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  100661. var quaternionCoefficient = Math.sin(angle / 2);
  100662. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  100663. // 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
  100664. if (tmpMatrix.determinant() > 0) {
  100665. amountToRotate.toEulerAnglesToRef(tmpVector);
  100666. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  100667. }
  100668. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100669. // Rotate selected mesh quaternion over fixed axis
  100670. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  100671. }
  100672. else {
  100673. // Rotate selected mesh quaternion over rotated axis
  100674. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  100675. }
  100676. lastDragPosition.copyFrom(event.dragPlanePoint);
  100677. if (snapped) {
  100678. tmpSnapEvent.snapDistance = angle;
  100679. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100680. }
  100681. }
  100682. });
  100683. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100684. if (_this._customMeshSet) {
  100685. return;
  100686. }
  100687. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100688. var material = isHovered ? hoverMaterial : coloredMaterial;
  100689. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100690. m.material = material;
  100691. if (m.color) {
  100692. m.color = material.emissiveColor;
  100693. }
  100694. });
  100695. });
  100696. return _this;
  100697. }
  100698. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  100699. if (this.dragBehavior) {
  100700. this.dragBehavior.enabled = value ? true : false;
  100701. }
  100702. };
  100703. /**
  100704. * Disposes of the gizmo
  100705. */
  100706. PlaneRotationGizmo.prototype.dispose = function () {
  100707. this.onSnapObservable.clear();
  100708. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100709. this.dragBehavior.detach();
  100710. _super.prototype.dispose.call(this);
  100711. };
  100712. return PlaneRotationGizmo;
  100713. }(BABYLON.Gizmo));
  100714. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  100715. })(BABYLON || (BABYLON = {}));
  100716. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  100717. var BABYLON;
  100718. (function (BABYLON) {
  100719. /**
  100720. * Gizmo that enables dragging a mesh along 3 axis
  100721. */
  100722. var PositionGizmo = /** @class */ (function (_super) {
  100723. __extends(PositionGizmo, _super);
  100724. /**
  100725. * Creates a PositionGizmo
  100726. * @param gizmoLayer The utility layer the gizmo will be added to
  100727. */
  100728. function PositionGizmo(gizmoLayer) {
  100729. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100730. var _this = _super.call(this, gizmoLayer) || this;
  100731. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100732. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100733. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100734. _this.attachedMesh = null;
  100735. return _this;
  100736. }
  100737. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  100738. set: function (mesh) {
  100739. if (this.xGizmo) {
  100740. this.xGizmo.attachedMesh = mesh;
  100741. this.yGizmo.attachedMesh = mesh;
  100742. this.zGizmo.attachedMesh = mesh;
  100743. }
  100744. },
  100745. enumerable: true,
  100746. configurable: true
  100747. });
  100748. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100749. get: function () {
  100750. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100751. },
  100752. set: function (value) {
  100753. if (this.xGizmo) {
  100754. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100755. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100756. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100757. }
  100758. },
  100759. enumerable: true,
  100760. configurable: true
  100761. });
  100762. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  100763. get: function () {
  100764. return this.xGizmo.snapDistance;
  100765. },
  100766. /**
  100767. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100768. */
  100769. set: function (value) {
  100770. if (this.xGizmo) {
  100771. this.xGizmo.snapDistance = value;
  100772. this.yGizmo.snapDistance = value;
  100773. this.zGizmo.snapDistance = value;
  100774. }
  100775. },
  100776. enumerable: true,
  100777. configurable: true
  100778. });
  100779. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  100780. get: function () {
  100781. return this.xGizmo.scaleRatio;
  100782. },
  100783. /**
  100784. * Ratio for the scale of the gizmo (Default: 1)
  100785. */
  100786. set: function (value) {
  100787. if (this.xGizmo) {
  100788. this.xGizmo.scaleRatio = value;
  100789. this.yGizmo.scaleRatio = value;
  100790. this.zGizmo.scaleRatio = value;
  100791. }
  100792. },
  100793. enumerable: true,
  100794. configurable: true
  100795. });
  100796. /**
  100797. * Disposes of the gizmo
  100798. */
  100799. PositionGizmo.prototype.dispose = function () {
  100800. this.xGizmo.dispose();
  100801. this.yGizmo.dispose();
  100802. this.zGizmo.dispose();
  100803. };
  100804. /**
  100805. * CustomMeshes are not supported by this gizmo
  100806. * @param mesh The mesh to replace the default mesh of the gizmo
  100807. */
  100808. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  100809. 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)");
  100810. };
  100811. return PositionGizmo;
  100812. }(BABYLON.Gizmo));
  100813. BABYLON.PositionGizmo = PositionGizmo;
  100814. })(BABYLON || (BABYLON = {}));
  100815. //# sourceMappingURL=babylon.positionGizmo.js.map
  100816. var BABYLON;
  100817. (function (BABYLON) {
  100818. /**
  100819. * Gizmo that enables rotating a mesh along 3 axis
  100820. */
  100821. var RotationGizmo = /** @class */ (function (_super) {
  100822. __extends(RotationGizmo, _super);
  100823. /**
  100824. * Creates a RotationGizmo
  100825. * @param gizmoLayer The utility layer the gizmo will be added to
  100826. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100827. */
  100828. function RotationGizmo(gizmoLayer, tessellation) {
  100829. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100830. if (tessellation === void 0) { tessellation = 32; }
  100831. var _this = _super.call(this, gizmoLayer) || this;
  100832. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  100833. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  100834. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  100835. _this.attachedMesh = null;
  100836. return _this;
  100837. }
  100838. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  100839. set: function (mesh) {
  100840. if (this.xGizmo) {
  100841. this.xGizmo.attachedMesh = mesh;
  100842. this.yGizmo.attachedMesh = mesh;
  100843. this.zGizmo.attachedMesh = mesh;
  100844. }
  100845. },
  100846. enumerable: true,
  100847. configurable: true
  100848. });
  100849. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100850. get: function () {
  100851. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100852. },
  100853. set: function (value) {
  100854. if (this.xGizmo) {
  100855. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100856. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100857. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100858. }
  100859. },
  100860. enumerable: true,
  100861. configurable: true
  100862. });
  100863. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  100864. get: function () {
  100865. return this.xGizmo.snapDistance;
  100866. },
  100867. /**
  100868. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100869. */
  100870. set: function (value) {
  100871. if (this.xGizmo) {
  100872. this.xGizmo.snapDistance = value;
  100873. this.yGizmo.snapDistance = value;
  100874. this.zGizmo.snapDistance = value;
  100875. }
  100876. },
  100877. enumerable: true,
  100878. configurable: true
  100879. });
  100880. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  100881. get: function () {
  100882. return this.xGizmo.scaleRatio;
  100883. },
  100884. /**
  100885. * Ratio for the scale of the gizmo (Default: 1)
  100886. */
  100887. set: function (value) {
  100888. if (this.xGizmo) {
  100889. this.xGizmo.scaleRatio = value;
  100890. this.yGizmo.scaleRatio = value;
  100891. this.zGizmo.scaleRatio = value;
  100892. }
  100893. },
  100894. enumerable: true,
  100895. configurable: true
  100896. });
  100897. /**
  100898. * Disposes of the gizmo
  100899. */
  100900. RotationGizmo.prototype.dispose = function () {
  100901. this.xGizmo.dispose();
  100902. this.yGizmo.dispose();
  100903. this.zGizmo.dispose();
  100904. };
  100905. /**
  100906. * CustomMeshes are not supported by this gizmo
  100907. * @param mesh The mesh to replace the default mesh of the gizmo
  100908. */
  100909. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  100910. 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)");
  100911. };
  100912. return RotationGizmo;
  100913. }(BABYLON.Gizmo));
  100914. BABYLON.RotationGizmo = RotationGizmo;
  100915. })(BABYLON || (BABYLON = {}));
  100916. //# sourceMappingURL=babylon.rotationGizmo.js.map
  100917. var BABYLON;
  100918. (function (BABYLON) {
  100919. /**
  100920. * Gizmo that enables scaling a mesh along 3 axis
  100921. */
  100922. var ScaleGizmo = /** @class */ (function (_super) {
  100923. __extends(ScaleGizmo, _super);
  100924. /**
  100925. * Creates a ScaleGizmo
  100926. * @param gizmoLayer The utility layer the gizmo will be added to
  100927. */
  100928. function ScaleGizmo(gizmoLayer) {
  100929. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100930. var _this = _super.call(this, gizmoLayer) || this;
  100931. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100932. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100933. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100934. // Create uniform scale gizmo
  100935. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  100936. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100937. _this.uniformScaleGizmo.uniformScaling = true;
  100938. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  100939. uniformScalingMesh.scaling.scaleInPlace(0.02);
  100940. uniformScalingMesh.visibility = 0;
  100941. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  100942. octahedron.scaling.scaleInPlace(0.007);
  100943. uniformScalingMesh.addChild(octahedron);
  100944. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  100945. _this.attachedMesh = null;
  100946. return _this;
  100947. }
  100948. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  100949. set: function (mesh) {
  100950. if (this.xGizmo) {
  100951. this.xGizmo.attachedMesh = mesh;
  100952. this.yGizmo.attachedMesh = mesh;
  100953. this.zGizmo.attachedMesh = mesh;
  100954. this.uniformScaleGizmo.attachedMesh = mesh;
  100955. }
  100956. },
  100957. enumerable: true,
  100958. configurable: true
  100959. });
  100960. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100961. get: function () {
  100962. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100963. },
  100964. set: function (value) {
  100965. if (!value) {
  100966. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  100967. }
  100968. if (this.xGizmo) {
  100969. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100970. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100971. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100972. }
  100973. },
  100974. enumerable: true,
  100975. configurable: true
  100976. });
  100977. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  100978. get: function () {
  100979. return this.xGizmo.snapDistance;
  100980. },
  100981. /**
  100982. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100983. */
  100984. set: function (value) {
  100985. if (this.xGizmo) {
  100986. this.xGizmo.snapDistance = value;
  100987. this.yGizmo.snapDistance = value;
  100988. this.zGizmo.snapDistance = value;
  100989. this.uniformScaleGizmo.snapDistance = value;
  100990. }
  100991. },
  100992. enumerable: true,
  100993. configurable: true
  100994. });
  100995. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  100996. get: function () {
  100997. return this.xGizmo.scaleRatio;
  100998. },
  100999. /**
  101000. * Ratio for the scale of the gizmo (Default: 1)
  101001. */
  101002. set: function (value) {
  101003. if (this.xGizmo) {
  101004. this.xGizmo.scaleRatio = value;
  101005. this.yGizmo.scaleRatio = value;
  101006. this.zGizmo.scaleRatio = value;
  101007. this.uniformScaleGizmo.scaleRatio = value;
  101008. }
  101009. },
  101010. enumerable: true,
  101011. configurable: true
  101012. });
  101013. /**
  101014. * Disposes of the gizmo
  101015. */
  101016. ScaleGizmo.prototype.dispose = function () {
  101017. this.xGizmo.dispose();
  101018. this.yGizmo.dispose();
  101019. this.zGizmo.dispose();
  101020. this.uniformScaleGizmo.dispose();
  101021. };
  101022. return ScaleGizmo;
  101023. }(BABYLON.Gizmo));
  101024. BABYLON.ScaleGizmo = ScaleGizmo;
  101025. })(BABYLON || (BABYLON = {}));
  101026. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101027. var BABYLON;
  101028. (function (BABYLON) {
  101029. /**
  101030. * Bounding box gizmo
  101031. */
  101032. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101033. __extends(BoundingBoxGizmo, _super);
  101034. /**
  101035. * Creates an BoundingBoxGizmo
  101036. * @param gizmoLayer The utility layer the gizmo will be added to
  101037. * @param color The color of the gizmo
  101038. */
  101039. function BoundingBoxGizmo(color, gizmoLayer) {
  101040. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101041. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101042. var _this = _super.call(this, gizmoLayer) || this;
  101043. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101044. _this._renderObserver = null;
  101045. _this._pointerObserver = null;
  101046. _this._scaleDragSpeed = 0.2;
  101047. _this._tmpQuaternion = new BABYLON.Quaternion();
  101048. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101049. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101050. /**
  101051. * 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)
  101052. */
  101053. _this.ignoreChildren = false;
  101054. /**
  101055. * 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)
  101056. */
  101057. _this.includeChildPredicate = null;
  101058. /**
  101059. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101060. */
  101061. _this.rotationSphereSize = 0.1;
  101062. /**
  101063. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101064. */
  101065. _this.scaleBoxSize = 0.1;
  101066. /**
  101067. * 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)
  101068. */
  101069. _this.fixedDragMeshScreenSize = false;
  101070. /**
  101071. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101072. */
  101073. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101074. /**
  101075. * Fired when a rotation sphere or scale box is dragged
  101076. */
  101077. _this.onDragStartObservable = new BABYLON.Observable();
  101078. /**
  101079. * Fired when a scale box is dragged
  101080. */
  101081. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101082. /**
  101083. * Fired when a scale box drag is ended
  101084. */
  101085. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101086. /**
  101087. * Fired when a rotation sphere is dragged
  101088. */
  101089. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101090. /**
  101091. * Fired when a rotation sphere drag is ended
  101092. */
  101093. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101094. /**
  101095. * 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)
  101096. */
  101097. _this.scalePivot = null;
  101098. _this._existingMeshScale = new BABYLON.Vector3();
  101099. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101100. _this._updateScale = false;
  101101. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101102. // Create Materials
  101103. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101104. coloredMaterial.disableLighting = true;
  101105. coloredMaterial.emissiveColor = color;
  101106. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101107. hoverColoredMaterial.disableLighting = true;
  101108. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101109. // Build bounding box out of lines
  101110. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101111. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101112. var lines = [];
  101113. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101114. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101115. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101116. 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));
  101117. 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));
  101118. 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));
  101119. 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));
  101120. 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));
  101121. 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));
  101122. 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));
  101123. 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));
  101124. 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));
  101125. lines.forEach(function (l) {
  101126. l.color = color;
  101127. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101128. l.isPickable = false;
  101129. _this._lineBoundingBox.addChild(l);
  101130. });
  101131. _this._rootMesh.addChild(_this._lineBoundingBox);
  101132. // Create rotation spheres
  101133. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101134. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101135. var _loop_1 = function (i_1) {
  101136. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101137. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101138. sphere.material = coloredMaterial;
  101139. // Drag behavior
  101140. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101141. _dragBehavior.moveAttached = false;
  101142. _dragBehavior.updateDragPlane = false;
  101143. sphere.addBehavior(_dragBehavior);
  101144. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101145. var totalTurnAmountOfDrag = 0;
  101146. _dragBehavior.onDragStartObservable.add(function (event) {
  101147. startingTurnDirection.copyFrom(sphere.forward);
  101148. totalTurnAmountOfDrag = 0;
  101149. });
  101150. _dragBehavior.onDragObservable.add(function (event) {
  101151. _this.onRotationSphereDragObservable.notifyObservers({});
  101152. if (_this.attachedMesh) {
  101153. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101154. var worldDragDirection = startingTurnDirection;
  101155. // Project the world right on to the drag plane
  101156. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101157. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101158. // project drag delta on to the resulting drag axis and rotate based on that
  101159. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101160. // Make rotation relative to size of mesh.
  101161. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101162. // Rotate based on axis
  101163. if (!_this.attachedMesh.rotationQuaternion) {
  101164. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101165. }
  101166. if (!_this._anchorMesh.rotationQuaternion) {
  101167. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101168. }
  101169. // Do not allow the object to turn more than a full circle
  101170. totalTurnAmountOfDrag += projectDist;
  101171. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101172. if (i_1 >= 8) {
  101173. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101174. }
  101175. else if (i_1 >= 4) {
  101176. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101177. }
  101178. else {
  101179. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101180. }
  101181. // Rotate around center of bounding box
  101182. _this._anchorMesh.addChild(_this.attachedMesh);
  101183. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101184. _this._anchorMesh.removeChild(_this.attachedMesh);
  101185. }
  101186. _this.updateBoundingBox();
  101187. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101188. }
  101189. });
  101190. // Selection/deselection
  101191. _dragBehavior.onDragStartObservable.add(function () {
  101192. _this.onDragStartObservable.notifyObservers({});
  101193. _this._selectNode(sphere);
  101194. });
  101195. _dragBehavior.onDragEndObservable.add(function () {
  101196. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101197. _this._selectNode(null);
  101198. });
  101199. this_1._rotateSpheresParent.addChild(sphere);
  101200. };
  101201. var this_1 = this, _dragBehavior;
  101202. for (var i_1 = 0; i_1 < 12; i_1++) {
  101203. _loop_1(i_1);
  101204. }
  101205. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101206. // Create scale cubes
  101207. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101208. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101209. for (var i = 0; i < 2; i++) {
  101210. for (var j = 0; j < 2; j++) {
  101211. var _loop_2 = function () {
  101212. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101213. box.material = coloredMaterial;
  101214. // Dragging logic
  101215. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101216. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101217. _dragBehavior.moveAttached = false;
  101218. box.addBehavior(_dragBehavior);
  101219. _dragBehavior.onDragObservable.add(function (event) {
  101220. _this.onScaleBoxDragObservable.notifyObservers({});
  101221. if (_this.attachedMesh) {
  101222. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101223. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101224. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101225. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101226. _this.updateBoundingBox();
  101227. if (_this.scalePivot) {
  101228. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101229. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101230. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101231. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101232. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101233. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101234. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101235. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101236. }
  101237. else {
  101238. // Scale from the position of the opposite corner
  101239. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101240. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101241. }
  101242. _this._anchorMesh.addChild(_this.attachedMesh);
  101243. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101244. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101245. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101246. }
  101247. _this._anchorMesh.removeChild(_this.attachedMesh);
  101248. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101249. }
  101250. });
  101251. // Selection/deselection
  101252. _dragBehavior.onDragStartObservable.add(function () {
  101253. _this.onDragStartObservable.notifyObservers({});
  101254. _this._selectNode(box);
  101255. });
  101256. _dragBehavior.onDragEndObservable.add(function () {
  101257. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101258. _this._selectNode(null);
  101259. });
  101260. this_2._scaleBoxesParent.addChild(box);
  101261. };
  101262. var this_2 = this, _dragBehavior;
  101263. for (var k = 0; k < 2; k++) {
  101264. _loop_2();
  101265. }
  101266. }
  101267. }
  101268. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101269. // Hover color change
  101270. var pointerIds = new Array();
  101271. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101272. if (!pointerIds[pointerInfo.event.pointerId]) {
  101273. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101274. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101275. pointerIds[pointerInfo.event.pointerId] = mesh;
  101276. mesh.material = hoverColoredMaterial;
  101277. }
  101278. });
  101279. }
  101280. else {
  101281. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101282. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101283. delete pointerIds[pointerInfo.event.pointerId];
  101284. }
  101285. }
  101286. });
  101287. // Update bounding box positions
  101288. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101289. // Only update the bouding box if scaling has changed
  101290. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101291. _this.updateBoundingBox();
  101292. }
  101293. });
  101294. _this.updateBoundingBox();
  101295. return _this;
  101296. }
  101297. /** @hidden */
  101298. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101299. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101300. // Save old pivot and set pivot to 0,0,0
  101301. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101302. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101303. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101304. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101305. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101306. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101307. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101308. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101309. }
  101310. }
  101311. BoundingBoxGizmo._PivotCached++;
  101312. };
  101313. /** @hidden */
  101314. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101315. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101316. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101317. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101318. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101319. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101320. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101321. }
  101322. this._PivotCached--;
  101323. };
  101324. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101325. if (value) {
  101326. // Reset anchor mesh to match attached mesh's scale
  101327. // This is needed to avoid invalid box/sphere position on first drag
  101328. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101329. this._anchorMesh.addChild(value);
  101330. this._anchorMesh.removeChild(value);
  101331. BoundingBoxGizmo._RestorePivotPoint(value);
  101332. this.updateBoundingBox();
  101333. }
  101334. };
  101335. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101336. this._rotateSpheresParent.getChildMeshes()
  101337. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101338. m.isVisible = (!selectedMesh || m == selectedMesh);
  101339. });
  101340. };
  101341. /**
  101342. * Updates the bounding box information for the Gizmo
  101343. */
  101344. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101345. if (this.attachedMesh) {
  101346. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101347. this._update();
  101348. // Rotate based on axis
  101349. if (!this.attachedMesh.rotationQuaternion) {
  101350. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101351. }
  101352. if (!this._anchorMesh.rotationQuaternion) {
  101353. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101354. }
  101355. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101356. // Store original position and reset mesh to origin before computing the bounding box
  101357. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101358. this._tmpVector.copyFrom(this.attachedMesh.position);
  101359. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101360. this.attachedMesh.position.set(0, 0, 0);
  101361. // Update bounding dimensions/positions
  101362. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101363. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101364. // Update gizmo to match bounding box scaling and rotation
  101365. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101366. 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);
  101367. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101368. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101369. this._lineBoundingBox.computeWorldMatrix();
  101370. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101371. // restore position/rotation values
  101372. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101373. this.attachedMesh.position.copyFrom(this._tmpVector);
  101374. }
  101375. // Update rotation sphere locations
  101376. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101377. for (var i = 0; i < 3; i++) {
  101378. for (var j = 0; j < 2; j++) {
  101379. for (var k = 0; k < 2; k++) {
  101380. var index = ((i * 4) + (j * 2)) + k;
  101381. if (i == 0) {
  101382. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101383. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101384. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101385. }
  101386. if (i == 1) {
  101387. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101388. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101389. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101390. }
  101391. if (i == 2) {
  101392. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101393. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101394. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101395. }
  101396. if (this.fixedDragMeshScreenSize) {
  101397. this._rootMesh.computeWorldMatrix();
  101398. this._rotateSpheresParent.computeWorldMatrix();
  101399. rotateSpheres[index].computeWorldMatrix();
  101400. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101401. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101402. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101403. }
  101404. else {
  101405. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101406. }
  101407. }
  101408. }
  101409. }
  101410. // Update scale box locations
  101411. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101412. for (var i = 0; i < 2; i++) {
  101413. for (var j = 0; j < 2; j++) {
  101414. for (var k = 0; k < 2; k++) {
  101415. var index = ((i * 4) + (j * 2)) + k;
  101416. if (scaleBoxes[index]) {
  101417. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101418. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101419. if (this.fixedDragMeshScreenSize) {
  101420. this._rootMesh.computeWorldMatrix();
  101421. this._scaleBoxesParent.computeWorldMatrix();
  101422. scaleBoxes[index].computeWorldMatrix();
  101423. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101424. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101425. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101426. }
  101427. else {
  101428. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101429. }
  101430. }
  101431. }
  101432. }
  101433. }
  101434. if (this.attachedMesh) {
  101435. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101436. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101437. }
  101438. };
  101439. /**
  101440. * Enables rotation on the specified axis and disables rotation on the others
  101441. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101442. */
  101443. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101444. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101445. if (i < 4) {
  101446. m.setEnabled(axis.indexOf("x") != -1);
  101447. }
  101448. else if (i < 8) {
  101449. m.setEnabled(axis.indexOf("y") != -1);
  101450. }
  101451. else {
  101452. m.setEnabled(axis.indexOf("z") != -1);
  101453. }
  101454. });
  101455. };
  101456. /**
  101457. * Disposes of the gizmo
  101458. */
  101459. BoundingBoxGizmo.prototype.dispose = function () {
  101460. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101461. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101462. this._lineBoundingBox.dispose();
  101463. this._rotateSpheresParent.dispose();
  101464. this._scaleBoxesParent.dispose();
  101465. _super.prototype.dispose.call(this);
  101466. };
  101467. /**
  101468. * 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)
  101469. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101470. * @returns the bounding box mesh with the passed in mesh as a child
  101471. */
  101472. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101473. var makeNotPickable = function (root) {
  101474. root.isPickable = false;
  101475. root.getChildMeshes().forEach(function (c) {
  101476. makeNotPickable(c);
  101477. });
  101478. };
  101479. makeNotPickable(mesh);
  101480. // Reset position to get boudning box from origin with no rotation
  101481. if (!mesh.rotationQuaternion) {
  101482. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101483. }
  101484. var oldPos = mesh.position.clone();
  101485. var oldRot = mesh.rotationQuaternion.clone();
  101486. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101487. mesh.position.set(0, 0, 0);
  101488. // Update bounding dimensions/positions
  101489. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101490. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101491. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101492. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101493. // Restore original positions
  101494. mesh.addChild(box);
  101495. mesh.rotationQuaternion.copyFrom(oldRot);
  101496. mesh.position.copyFrom(oldPos);
  101497. // Reverse parenting
  101498. mesh.removeChild(box);
  101499. box.addChild(mesh);
  101500. box.visibility = 0;
  101501. return box;
  101502. };
  101503. /**
  101504. * CustomMeshes are not supported by this gizmo
  101505. * @param mesh The mesh to replace the default mesh of the gizmo
  101506. */
  101507. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101508. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101509. };
  101510. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101511. // store/remove pivot point should only be applied during their outermost calls
  101512. BoundingBoxGizmo._PivotCached = 0;
  101513. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101514. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101515. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101516. return BoundingBoxGizmo;
  101517. }(BABYLON.Gizmo));
  101518. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101519. })(BABYLON || (BABYLON = {}));
  101520. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101521. var BABYLON;
  101522. (function (BABYLON) {
  101523. /**
  101524. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101525. */
  101526. var GizmoManager = /** @class */ (function () {
  101527. /**
  101528. * Instatiates a gizmo manager
  101529. * @param scene the scene to overlay the gizmos on top of
  101530. */
  101531. function GizmoManager(scene) {
  101532. var _this = this;
  101533. this.scene = scene;
  101534. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101535. this._pointerObserver = null;
  101536. this._attachedMesh = null;
  101537. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101538. /**
  101539. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101540. */
  101541. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101542. /**
  101543. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101544. */
  101545. this.attachableMeshes = null;
  101546. /**
  101547. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101548. */
  101549. this.usePointerToAttachGizmos = true;
  101550. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101551. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101552. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101553. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101554. // Instatiate/dispose gizmos based on pointer actions
  101555. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101556. if (!_this.usePointerToAttachGizmos) {
  101557. return;
  101558. }
  101559. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101560. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101561. var node = pointerInfo.pickInfo.pickedMesh;
  101562. if (_this.attachableMeshes == null) {
  101563. // Attach to the most parent node
  101564. while (node && node.parent != null) {
  101565. node = node.parent;
  101566. }
  101567. }
  101568. else {
  101569. // Attach to the parent node that is an attachableMesh
  101570. var found = false;
  101571. _this.attachableMeshes.forEach(function (mesh) {
  101572. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101573. node = mesh;
  101574. found = true;
  101575. }
  101576. });
  101577. if (!found) {
  101578. node = null;
  101579. }
  101580. }
  101581. if (node instanceof BABYLON.AbstractMesh) {
  101582. _this.attachToMesh(node);
  101583. }
  101584. else {
  101585. _this.attachToMesh(null);
  101586. }
  101587. }
  101588. else {
  101589. _this.attachToMesh(null);
  101590. }
  101591. }
  101592. });
  101593. }
  101594. /**
  101595. * Attaches a set of gizmos to the specified mesh
  101596. * @param mesh The mesh the gizmo's should be attached to
  101597. */
  101598. GizmoManager.prototype.attachToMesh = function (mesh) {
  101599. if (this._attachedMesh) {
  101600. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101601. }
  101602. this._attachedMesh = mesh;
  101603. for (var key in this.gizmos) {
  101604. var gizmo = (this.gizmos[key]);
  101605. if (gizmo && this._gizmosEnabled[key]) {
  101606. gizmo.attachedMesh = mesh;
  101607. }
  101608. }
  101609. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  101610. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101611. }
  101612. };
  101613. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  101614. get: function () {
  101615. return this._gizmosEnabled.positionGizmo;
  101616. },
  101617. /**
  101618. * If the position gizmo is enabled
  101619. */
  101620. set: function (value) {
  101621. if (value) {
  101622. if (!this.gizmos.positionGizmo) {
  101623. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  101624. }
  101625. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  101626. }
  101627. else if (this.gizmos.positionGizmo) {
  101628. this.gizmos.positionGizmo.attachedMesh = null;
  101629. }
  101630. this._gizmosEnabled.positionGizmo = value;
  101631. },
  101632. enumerable: true,
  101633. configurable: true
  101634. });
  101635. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  101636. get: function () {
  101637. return this._gizmosEnabled.rotationGizmo;
  101638. },
  101639. /**
  101640. * If the rotation gizmo is enabled
  101641. */
  101642. set: function (value) {
  101643. if (value) {
  101644. if (!this.gizmos.rotationGizmo) {
  101645. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  101646. }
  101647. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  101648. }
  101649. else if (this.gizmos.rotationGizmo) {
  101650. this.gizmos.rotationGizmo.attachedMesh = null;
  101651. }
  101652. this._gizmosEnabled.rotationGizmo = value;
  101653. },
  101654. enumerable: true,
  101655. configurable: true
  101656. });
  101657. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  101658. get: function () {
  101659. return this._gizmosEnabled.scaleGizmo;
  101660. },
  101661. /**
  101662. * If the scale gizmo is enabled
  101663. */
  101664. set: function (value) {
  101665. if (value) {
  101666. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  101667. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  101668. }
  101669. else if (this.gizmos.scaleGizmo) {
  101670. this.gizmos.scaleGizmo.attachedMesh = null;
  101671. }
  101672. this._gizmosEnabled.scaleGizmo = value;
  101673. },
  101674. enumerable: true,
  101675. configurable: true
  101676. });
  101677. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  101678. get: function () {
  101679. return this._gizmosEnabled.boundingBoxGizmo;
  101680. },
  101681. /**
  101682. * If the boundingBox gizmo is enabled
  101683. */
  101684. set: function (value) {
  101685. if (value) {
  101686. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  101687. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  101688. if (this._attachedMesh) {
  101689. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101690. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101691. }
  101692. }
  101693. else if (this.gizmos.boundingBoxGizmo) {
  101694. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  101695. }
  101696. this._gizmosEnabled.boundingBoxGizmo = value;
  101697. },
  101698. enumerable: true,
  101699. configurable: true
  101700. });
  101701. /**
  101702. * Disposes of the gizmo manager
  101703. */
  101704. GizmoManager.prototype.dispose = function () {
  101705. this.scene.onPointerObservable.remove(this._pointerObserver);
  101706. for (var key in this.gizmos) {
  101707. var gizmo = (this.gizmos[key]);
  101708. if (gizmo) {
  101709. gizmo.dispose();
  101710. }
  101711. }
  101712. this._defaultKeepDepthUtilityLayer.dispose();
  101713. this._defaultUtilityLayer.dispose();
  101714. this.boundingBoxDragBehavior.detach();
  101715. };
  101716. return GizmoManager;
  101717. }());
  101718. BABYLON.GizmoManager = GizmoManager;
  101719. })(BABYLON || (BABYLON = {}));
  101720. //# sourceMappingURL=babylon.gizmoManager.js.map
  101721. var BABYLON;
  101722. (function (BABYLON) {
  101723. /**
  101724. * Defines a target to use with MorphTargetManager
  101725. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  101726. */
  101727. var MorphTarget = /** @class */ (function () {
  101728. /**
  101729. * Creates a new MorphTarget
  101730. * @param name defines the name of the target
  101731. * @param influence defines the influence to use
  101732. */
  101733. function MorphTarget(
  101734. /** defines the name of the target */
  101735. name, influence, scene) {
  101736. if (influence === void 0) { influence = 0; }
  101737. if (scene === void 0) { scene = null; }
  101738. this.name = name;
  101739. /**
  101740. * Gets or sets the list of animations
  101741. */
  101742. this.animations = new Array();
  101743. this._positions = null;
  101744. this._normals = null;
  101745. this._tangents = null;
  101746. /**
  101747. * Observable raised when the influence changes
  101748. */
  101749. this.onInfluenceChanged = new BABYLON.Observable();
  101750. this._animationPropertiesOverride = null;
  101751. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101752. this.influence = influence;
  101753. }
  101754. Object.defineProperty(MorphTarget.prototype, "influence", {
  101755. /**
  101756. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  101757. */
  101758. get: function () {
  101759. return this._influence;
  101760. },
  101761. set: function (influence) {
  101762. if (this._influence === influence) {
  101763. return;
  101764. }
  101765. var previous = this._influence;
  101766. this._influence = influence;
  101767. if (this.onInfluenceChanged.hasObservers) {
  101768. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  101769. }
  101770. },
  101771. enumerable: true,
  101772. configurable: true
  101773. });
  101774. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  101775. /**
  101776. * Gets or sets the animation properties override
  101777. */
  101778. get: function () {
  101779. if (!this._animationPropertiesOverride && this._scene) {
  101780. return this._scene.animationPropertiesOverride;
  101781. }
  101782. return this._animationPropertiesOverride;
  101783. },
  101784. set: function (value) {
  101785. this._animationPropertiesOverride = value;
  101786. },
  101787. enumerable: true,
  101788. configurable: true
  101789. });
  101790. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  101791. /**
  101792. * Gets a boolean defining if the target contains position data
  101793. */
  101794. get: function () {
  101795. return !!this._positions;
  101796. },
  101797. enumerable: true,
  101798. configurable: true
  101799. });
  101800. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  101801. /**
  101802. * Gets a boolean defining if the target contains normal data
  101803. */
  101804. get: function () {
  101805. return !!this._normals;
  101806. },
  101807. enumerable: true,
  101808. configurable: true
  101809. });
  101810. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  101811. /**
  101812. * Gets a boolean defining if the target contains tangent data
  101813. */
  101814. get: function () {
  101815. return !!this._tangents;
  101816. },
  101817. enumerable: true,
  101818. configurable: true
  101819. });
  101820. /**
  101821. * Affects position data to this target
  101822. * @param data defines the position data to use
  101823. */
  101824. MorphTarget.prototype.setPositions = function (data) {
  101825. this._positions = data;
  101826. };
  101827. /**
  101828. * Gets the position data stored in this target
  101829. * @returns a FloatArray containing the position data (or null if not present)
  101830. */
  101831. MorphTarget.prototype.getPositions = function () {
  101832. return this._positions;
  101833. };
  101834. /**
  101835. * Affects normal data to this target
  101836. * @param data defines the normal data to use
  101837. */
  101838. MorphTarget.prototype.setNormals = function (data) {
  101839. this._normals = data;
  101840. };
  101841. /**
  101842. * Gets the normal data stored in this target
  101843. * @returns a FloatArray containing the normal data (or null if not present)
  101844. */
  101845. MorphTarget.prototype.getNormals = function () {
  101846. return this._normals;
  101847. };
  101848. /**
  101849. * Affects tangent data to this target
  101850. * @param data defines the tangent data to use
  101851. */
  101852. MorphTarget.prototype.setTangents = function (data) {
  101853. this._tangents = data;
  101854. };
  101855. /**
  101856. * Gets the tangent data stored in this target
  101857. * @returns a FloatArray containing the tangent data (or null if not present)
  101858. */
  101859. MorphTarget.prototype.getTangents = function () {
  101860. return this._tangents;
  101861. };
  101862. /**
  101863. * Serializes the current target into a Serialization object
  101864. * @returns the serialized object
  101865. */
  101866. MorphTarget.prototype.serialize = function () {
  101867. var serializationObject = {};
  101868. serializationObject.name = this.name;
  101869. serializationObject.influence = this.influence;
  101870. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  101871. if (this.hasNormals) {
  101872. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  101873. }
  101874. if (this.hasTangents) {
  101875. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  101876. }
  101877. // Animations
  101878. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  101879. return serializationObject;
  101880. };
  101881. // Statics
  101882. /**
  101883. * Creates a new target from serialized data
  101884. * @param serializationObject defines the serialized data to use
  101885. * @returns a new MorphTarget
  101886. */
  101887. MorphTarget.Parse = function (serializationObject) {
  101888. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  101889. result.setPositions(serializationObject.positions);
  101890. if (serializationObject.normals) {
  101891. result.setNormals(serializationObject.normals);
  101892. }
  101893. if (serializationObject.tangents) {
  101894. result.setTangents(serializationObject.tangents);
  101895. }
  101896. // Animations
  101897. if (serializationObject.animations) {
  101898. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  101899. var parsedAnimation = serializationObject.animations[animationIndex];
  101900. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  101901. }
  101902. }
  101903. return result;
  101904. };
  101905. /**
  101906. * Creates a MorphTarget from mesh data
  101907. * @param mesh defines the source mesh
  101908. * @param name defines the name to use for the new target
  101909. * @param influence defines the influence to attach to the target
  101910. * @returns a new MorphTarget
  101911. */
  101912. MorphTarget.FromMesh = function (mesh, name, influence) {
  101913. if (!name) {
  101914. name = mesh.name;
  101915. }
  101916. var result = new MorphTarget(name, influence, mesh.getScene());
  101917. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  101918. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101919. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  101920. }
  101921. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  101922. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  101923. }
  101924. return result;
  101925. };
  101926. return MorphTarget;
  101927. }());
  101928. BABYLON.MorphTarget = MorphTarget;
  101929. })(BABYLON || (BABYLON = {}));
  101930. //# sourceMappingURL=babylon.morphTarget.js.map
  101931. var BABYLON;
  101932. (function (BABYLON) {
  101933. /**
  101934. * This class is used to deform meshes using morphing between different targets
  101935. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  101936. */
  101937. var MorphTargetManager = /** @class */ (function () {
  101938. /**
  101939. * Creates a new MorphTargetManager
  101940. * @param scene defines the current scene
  101941. */
  101942. function MorphTargetManager(scene) {
  101943. if (scene === void 0) { scene = null; }
  101944. this._targets = new Array();
  101945. this._targetObservable = new Array();
  101946. this._activeTargets = new BABYLON.SmartArray(16);
  101947. this._supportsNormals = false;
  101948. this._supportsTangents = false;
  101949. this._vertexCount = 0;
  101950. this._uniqueId = 0;
  101951. this._tempInfluences = new Array();
  101952. if (!scene) {
  101953. scene = BABYLON.Engine.LastCreatedScene;
  101954. }
  101955. this._scene = scene;
  101956. if (this._scene) {
  101957. this._scene.morphTargetManagers.push(this);
  101958. this._uniqueId = this._scene.getUniqueId();
  101959. }
  101960. }
  101961. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  101962. /**
  101963. * Gets the unique ID of this manager
  101964. */
  101965. get: function () {
  101966. return this._uniqueId;
  101967. },
  101968. enumerable: true,
  101969. configurable: true
  101970. });
  101971. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  101972. /**
  101973. * Gets the number of vertices handled by this manager
  101974. */
  101975. get: function () {
  101976. return this._vertexCount;
  101977. },
  101978. enumerable: true,
  101979. configurable: true
  101980. });
  101981. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  101982. /**
  101983. * Gets a boolean indicating if this manager supports morphing of normals
  101984. */
  101985. get: function () {
  101986. return this._supportsNormals;
  101987. },
  101988. enumerable: true,
  101989. configurable: true
  101990. });
  101991. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  101992. /**
  101993. * Gets a boolean indicating if this manager supports morphing of tangents
  101994. */
  101995. get: function () {
  101996. return this._supportsTangents;
  101997. },
  101998. enumerable: true,
  101999. configurable: true
  102000. });
  102001. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  102002. /**
  102003. * Gets the number of targets stored in this manager
  102004. */
  102005. get: function () {
  102006. return this._targets.length;
  102007. },
  102008. enumerable: true,
  102009. configurable: true
  102010. });
  102011. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  102012. /**
  102013. * Gets the number of influencers (ie. the number of targets with influences > 0)
  102014. */
  102015. get: function () {
  102016. return this._activeTargets.length;
  102017. },
  102018. enumerable: true,
  102019. configurable: true
  102020. });
  102021. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  102022. /**
  102023. * Gets the list of influences (one per target)
  102024. */
  102025. get: function () {
  102026. return this._influences;
  102027. },
  102028. enumerable: true,
  102029. configurable: true
  102030. });
  102031. /**
  102032. * Gets the active target at specified index. An active target is a target with an influence > 0
  102033. * @param index defines the index to check
  102034. * @returns the requested target
  102035. */
  102036. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102037. return this._activeTargets.data[index];
  102038. };
  102039. /**
  102040. * Gets the target at specified index
  102041. * @param index defines the index to check
  102042. * @returns the requested target
  102043. */
  102044. MorphTargetManager.prototype.getTarget = function (index) {
  102045. return this._targets[index];
  102046. };
  102047. /**
  102048. * Add a new target to this manager
  102049. * @param target defines the target to add
  102050. */
  102051. MorphTargetManager.prototype.addTarget = function (target) {
  102052. var _this = this;
  102053. this._targets.push(target);
  102054. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  102055. _this._syncActiveTargets(needUpdate);
  102056. }));
  102057. this._syncActiveTargets(true);
  102058. };
  102059. /**
  102060. * Removes a target from the manager
  102061. * @param target defines the target to remove
  102062. */
  102063. MorphTargetManager.prototype.removeTarget = function (target) {
  102064. var index = this._targets.indexOf(target);
  102065. if (index >= 0) {
  102066. this._targets.splice(index, 1);
  102067. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  102068. this._syncActiveTargets(true);
  102069. }
  102070. };
  102071. /**
  102072. * Serializes the current manager into a Serialization object
  102073. * @returns the serialized object
  102074. */
  102075. MorphTargetManager.prototype.serialize = function () {
  102076. var serializationObject = {};
  102077. serializationObject.id = this.uniqueId;
  102078. serializationObject.targets = [];
  102079. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102080. var target = _a[_i];
  102081. serializationObject.targets.push(target.serialize());
  102082. }
  102083. return serializationObject;
  102084. };
  102085. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102086. var influenceCount = 0;
  102087. this._activeTargets.reset();
  102088. this._supportsNormals = true;
  102089. this._supportsTangents = true;
  102090. this._vertexCount = 0;
  102091. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102092. var target = _a[_i];
  102093. this._activeTargets.push(target);
  102094. this._tempInfluences[influenceCount++] = target.influence;
  102095. var positions = target.getPositions();
  102096. if (positions) {
  102097. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102098. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102099. var vertexCount = positions.length / 3;
  102100. if (this._vertexCount === 0) {
  102101. this._vertexCount = vertexCount;
  102102. }
  102103. else if (this._vertexCount !== vertexCount) {
  102104. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102105. return;
  102106. }
  102107. }
  102108. }
  102109. if (!this._influences || this._influences.length !== influenceCount) {
  102110. this._influences = new Float32Array(influenceCount);
  102111. }
  102112. for (var index = 0; index < influenceCount; index++) {
  102113. this._influences[index] = this._tempInfluences[index];
  102114. }
  102115. if (needUpdate) {
  102116. this.synchronize();
  102117. }
  102118. };
  102119. /**
  102120. * Syncrhonize the targets with all the meshes using this morph target manager
  102121. */
  102122. MorphTargetManager.prototype.synchronize = function () {
  102123. if (!this._scene) {
  102124. return;
  102125. }
  102126. // Flag meshes as dirty to resync with the active targets
  102127. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102128. var mesh = _a[_i];
  102129. if (mesh.morphTargetManager === this) {
  102130. mesh._syncGeometryWithMorphTargetManager();
  102131. }
  102132. }
  102133. };
  102134. // Statics
  102135. /**
  102136. * Creates a new MorphTargetManager from serialized data
  102137. * @param serializationObject defines the serialized data
  102138. * @param scene defines the hosting scene
  102139. * @returns the new MorphTargetManager
  102140. */
  102141. MorphTargetManager.Parse = function (serializationObject, scene) {
  102142. var result = new MorphTargetManager(scene);
  102143. result._uniqueId = serializationObject.id;
  102144. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102145. var targetData = _a[_i];
  102146. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102147. }
  102148. return result;
  102149. };
  102150. return MorphTargetManager;
  102151. }());
  102152. BABYLON.MorphTargetManager = MorphTargetManager;
  102153. })(BABYLON || (BABYLON = {}));
  102154. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102155. var BABYLON;
  102156. (function (BABYLON) {
  102157. /**
  102158. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102159. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102160. */
  102161. var Octree = /** @class */ (function () {
  102162. /**
  102163. * Creates a octree
  102164. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102165. * @param creationFunc function to be used to instatiate the octree
  102166. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102167. * @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.)
  102168. */
  102169. function Octree(creationFunc, maxBlockCapacity,
  102170. /** 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.) */
  102171. maxDepth) {
  102172. if (maxDepth === void 0) { maxDepth = 2; }
  102173. this.maxDepth = maxDepth;
  102174. /**
  102175. * Content stored in the octree
  102176. */
  102177. this.dynamicContent = new Array();
  102178. this._maxBlockCapacity = maxBlockCapacity || 64;
  102179. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102180. this._creationFunc = creationFunc;
  102181. }
  102182. // Methods
  102183. /**
  102184. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102185. * @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);
  102186. * @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);
  102187. * @param entries meshes to be added to the octree blocks
  102188. */
  102189. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102190. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102191. };
  102192. /**
  102193. * Adds a mesh to the octree
  102194. * @param entry Mesh to add to the octree
  102195. */
  102196. Octree.prototype.addMesh = function (entry) {
  102197. for (var index = 0; index < this.blocks.length; index++) {
  102198. var block = this.blocks[index];
  102199. block.addEntry(entry);
  102200. }
  102201. };
  102202. /**
  102203. * Selects an array of meshes within the frustum
  102204. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102205. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102206. * @returns array of meshes within the frustum
  102207. */
  102208. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102209. this._selectionContent.reset();
  102210. for (var index = 0; index < this.blocks.length; index++) {
  102211. var block = this.blocks[index];
  102212. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102213. }
  102214. if (allowDuplicate) {
  102215. this._selectionContent.concat(this.dynamicContent);
  102216. }
  102217. else {
  102218. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102219. }
  102220. return this._selectionContent;
  102221. };
  102222. /**
  102223. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102224. * @param sphereCenter defines the bounding sphere center
  102225. * @param sphereRadius defines the bounding sphere radius
  102226. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102227. * @returns an array of objects that intersect the sphere
  102228. */
  102229. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102230. this._selectionContent.reset();
  102231. for (var index = 0; index < this.blocks.length; index++) {
  102232. var block = this.blocks[index];
  102233. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102234. }
  102235. if (allowDuplicate) {
  102236. this._selectionContent.concat(this.dynamicContent);
  102237. }
  102238. else {
  102239. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102240. }
  102241. return this._selectionContent;
  102242. };
  102243. /**
  102244. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102245. * @param ray defines the ray to test with
  102246. * @returns array of intersected objects
  102247. */
  102248. Octree.prototype.intersectsRay = function (ray) {
  102249. this._selectionContent.reset();
  102250. for (var index = 0; index < this.blocks.length; index++) {
  102251. var block = this.blocks[index];
  102252. block.intersectsRay(ray, this._selectionContent);
  102253. }
  102254. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102255. return this._selectionContent;
  102256. };
  102257. /**
  102258. * @hidden
  102259. */
  102260. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102261. target.blocks = new Array();
  102262. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102263. // Segmenting space
  102264. for (var x = 0; x < 2; x++) {
  102265. for (var y = 0; y < 2; y++) {
  102266. for (var z = 0; z < 2; z++) {
  102267. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102268. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102269. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102270. block.addEntries(entries);
  102271. target.blocks.push(block);
  102272. }
  102273. }
  102274. }
  102275. };
  102276. /**
  102277. * Adds a mesh into the octree block if it intersects the block
  102278. */
  102279. Octree.CreationFuncForMeshes = function (entry, block) {
  102280. var boundingInfo = entry.getBoundingInfo();
  102281. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102282. block.entries.push(entry);
  102283. }
  102284. };
  102285. /**
  102286. * Adds a submesh into the octree block if it intersects the block
  102287. */
  102288. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102289. var boundingInfo = entry.getBoundingInfo();
  102290. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102291. block.entries.push(entry);
  102292. }
  102293. };
  102294. return Octree;
  102295. }());
  102296. BABYLON.Octree = Octree;
  102297. })(BABYLON || (BABYLON = {}));
  102298. //# sourceMappingURL=babylon.octree.js.map
  102299. var BABYLON;
  102300. (function (BABYLON) {
  102301. /**
  102302. * Class used to store a cell in an octree
  102303. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102304. */
  102305. var OctreeBlock = /** @class */ (function () {
  102306. /**
  102307. * Creates a new block
  102308. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102309. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102310. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102311. * @param depth defines the current depth of this block in the octree
  102312. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102313. * @param creationFunc defines a callback to call when an element is added to the block
  102314. */
  102315. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102316. /**
  102317. * Gets the content of the current block
  102318. */
  102319. this.entries = new Array();
  102320. this._boundingVectors = new Array();
  102321. this._capacity = capacity;
  102322. this._depth = depth;
  102323. this._maxDepth = maxDepth;
  102324. this._creationFunc = creationFunc;
  102325. this._minPoint = minPoint;
  102326. this._maxPoint = maxPoint;
  102327. this._boundingVectors.push(minPoint.clone());
  102328. this._boundingVectors.push(maxPoint.clone());
  102329. this._boundingVectors.push(minPoint.clone());
  102330. this._boundingVectors[2].x = maxPoint.x;
  102331. this._boundingVectors.push(minPoint.clone());
  102332. this._boundingVectors[3].y = maxPoint.y;
  102333. this._boundingVectors.push(minPoint.clone());
  102334. this._boundingVectors[4].z = maxPoint.z;
  102335. this._boundingVectors.push(maxPoint.clone());
  102336. this._boundingVectors[5].z = minPoint.z;
  102337. this._boundingVectors.push(maxPoint.clone());
  102338. this._boundingVectors[6].x = minPoint.x;
  102339. this._boundingVectors.push(maxPoint.clone());
  102340. this._boundingVectors[7].y = minPoint.y;
  102341. }
  102342. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102343. // Property
  102344. /**
  102345. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102346. */
  102347. get: function () {
  102348. return this._capacity;
  102349. },
  102350. enumerable: true,
  102351. configurable: true
  102352. });
  102353. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102354. /**
  102355. * Gets the minimum vector (in world space) of the block's bounding box
  102356. */
  102357. get: function () {
  102358. return this._minPoint;
  102359. },
  102360. enumerable: true,
  102361. configurable: true
  102362. });
  102363. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102364. /**
  102365. * Gets the maximum vector (in world space) of the block's bounding box
  102366. */
  102367. get: function () {
  102368. return this._maxPoint;
  102369. },
  102370. enumerable: true,
  102371. configurable: true
  102372. });
  102373. // Methods
  102374. /**
  102375. * Add a new element to this block
  102376. * @param entry defines the element to add
  102377. */
  102378. OctreeBlock.prototype.addEntry = function (entry) {
  102379. if (this.blocks) {
  102380. for (var index = 0; index < this.blocks.length; index++) {
  102381. var block = this.blocks[index];
  102382. block.addEntry(entry);
  102383. }
  102384. return;
  102385. }
  102386. this._creationFunc(entry, this);
  102387. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102388. this.createInnerBlocks();
  102389. }
  102390. };
  102391. /**
  102392. * Add an array of elements to this block
  102393. * @param entries defines the array of elements to add
  102394. */
  102395. OctreeBlock.prototype.addEntries = function (entries) {
  102396. for (var index = 0; index < entries.length; index++) {
  102397. var mesh = entries[index];
  102398. this.addEntry(mesh);
  102399. }
  102400. };
  102401. /**
  102402. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102403. * @param frustumPlanes defines the frustum planes to test
  102404. * @param selection defines the array to store current content if selection is positive
  102405. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102406. */
  102407. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102408. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102409. if (this.blocks) {
  102410. for (var index = 0; index < this.blocks.length; index++) {
  102411. var block = this.blocks[index];
  102412. block.select(frustumPlanes, selection, allowDuplicate);
  102413. }
  102414. return;
  102415. }
  102416. if (allowDuplicate) {
  102417. selection.concat(this.entries);
  102418. }
  102419. else {
  102420. selection.concatWithNoDuplicate(this.entries);
  102421. }
  102422. }
  102423. };
  102424. /**
  102425. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102426. * @param sphereCenter defines the bounding sphere center
  102427. * @param sphereRadius defines the bounding sphere radius
  102428. * @param selection defines the array to store current content if selection is positive
  102429. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102430. */
  102431. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102432. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102433. if (this.blocks) {
  102434. for (var index = 0; index < this.blocks.length; index++) {
  102435. var block = this.blocks[index];
  102436. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102437. }
  102438. return;
  102439. }
  102440. if (allowDuplicate) {
  102441. selection.concat(this.entries);
  102442. }
  102443. else {
  102444. selection.concatWithNoDuplicate(this.entries);
  102445. }
  102446. }
  102447. };
  102448. /**
  102449. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102450. * @param ray defines the ray to test with
  102451. * @param selection defines the array to store current content if selection is positive
  102452. */
  102453. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102454. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102455. if (this.blocks) {
  102456. for (var index = 0; index < this.blocks.length; index++) {
  102457. var block = this.blocks[index];
  102458. block.intersectsRay(ray, selection);
  102459. }
  102460. return;
  102461. }
  102462. selection.concatWithNoDuplicate(this.entries);
  102463. }
  102464. };
  102465. /**
  102466. * Subdivide the content into child blocks (this block will then be empty)
  102467. */
  102468. OctreeBlock.prototype.createInnerBlocks = function () {
  102469. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102470. };
  102471. return OctreeBlock;
  102472. }());
  102473. BABYLON.OctreeBlock = OctreeBlock;
  102474. })(BABYLON || (BABYLON = {}));
  102475. //# sourceMappingURL=babylon.octreeBlock.js.map
  102476. var BABYLON;
  102477. (function (BABYLON) {
  102478. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102479. if (maxCapacity === void 0) { maxCapacity = 64; }
  102480. if (maxDepth === void 0) { maxDepth = 2; }
  102481. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102482. if (!component) {
  102483. component = new OctreeSceneComponent(this);
  102484. this._addComponent(component);
  102485. }
  102486. if (!this._selectionOctree) {
  102487. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102488. }
  102489. var worldExtends = this.getWorldExtends();
  102490. // Update octree
  102491. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102492. return this._selectionOctree;
  102493. };
  102494. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102495. get: function () {
  102496. return this._selectionOctree;
  102497. },
  102498. enumerable: true,
  102499. configurable: true
  102500. });
  102501. /**
  102502. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102503. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102504. * @param maxCapacity defines the maximum size of each block (64 by default)
  102505. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102506. * @returns the new octree
  102507. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102508. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102509. */
  102510. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102511. if (maxCapacity === void 0) { maxCapacity = 64; }
  102512. if (maxDepth === void 0) { maxDepth = 2; }
  102513. var scene = this.getScene();
  102514. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102515. if (!component) {
  102516. component = new OctreeSceneComponent(scene);
  102517. scene._addComponent(component);
  102518. }
  102519. if (!this._submeshesOctree) {
  102520. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102521. }
  102522. this.computeWorldMatrix(true);
  102523. var boundingInfo = this.getBoundingInfo();
  102524. // Update octree
  102525. var bbox = boundingInfo.boundingBox;
  102526. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102527. return this._submeshesOctree;
  102528. };
  102529. /**
  102530. * Defines the octree scene component responsible to manage any octrees
  102531. * in a given scene.
  102532. */
  102533. var OctreeSceneComponent = /** @class */ (function () {
  102534. /**
  102535. * Creates a new instance of the component for the given scene
  102536. * @param scene Defines the scene to register the component in
  102537. */
  102538. function OctreeSceneComponent(scene) {
  102539. /**
  102540. * The component name helpfull to identify the component in the list of scene components.
  102541. */
  102542. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102543. /**
  102544. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102545. */
  102546. this.checksIsEnabled = true;
  102547. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102548. this.scene = scene;
  102549. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102550. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102551. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102552. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102553. }
  102554. /**
  102555. * Registers the component in a given scene
  102556. */
  102557. OctreeSceneComponent.prototype.register = function () {
  102558. var _this = this;
  102559. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102560. var sceneOctree = _this.scene.selectionOctree;
  102561. if (sceneOctree !== undefined && sceneOctree !== null) {
  102562. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102563. if (index !== -1) {
  102564. sceneOctree.dynamicContent.splice(index, 1);
  102565. }
  102566. }
  102567. });
  102568. this.scene.onMeshImportedObservable.add(function (mesh) {
  102569. var sceneOctree = _this.scene.selectionOctree;
  102570. if (sceneOctree !== undefined && sceneOctree !== null) {
  102571. sceneOctree.addMesh(mesh);
  102572. }
  102573. });
  102574. };
  102575. /**
  102576. * Return the list of active meshes
  102577. * @returns the list of active meshes
  102578. */
  102579. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102580. if (this.scene._selectionOctree) {
  102581. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  102582. return selection;
  102583. }
  102584. return this.scene._getDefaultMeshCandidates();
  102585. };
  102586. /**
  102587. * Return the list of active sub meshes
  102588. * @param mesh The mesh to get the candidates sub meshes from
  102589. * @returns the list of active sub meshes
  102590. */
  102591. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  102592. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  102593. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  102594. return intersections;
  102595. }
  102596. return this.scene._getDefaultSubMeshCandidates(mesh);
  102597. };
  102598. /**
  102599. * Return the list of sub meshes intersecting with a given local ray
  102600. * @param mesh defines the mesh to find the submesh for
  102601. * @param localRay defines the ray in local space
  102602. * @returns the list of intersecting sub meshes
  102603. */
  102604. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  102605. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  102606. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  102607. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  102608. return intersections;
  102609. }
  102610. return this.scene._getDefaultSubMeshCandidates(mesh);
  102611. };
  102612. /**
  102613. * Return the list of sub meshes colliding with a collider
  102614. * @param mesh defines the mesh to find the submesh for
  102615. * @param collider defines the collider to evaluate the collision against
  102616. * @returns the list of colliding sub meshes
  102617. */
  102618. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  102619. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  102620. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  102621. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  102622. return intersections;
  102623. }
  102624. return this.scene._getDefaultSubMeshCandidates(mesh);
  102625. };
  102626. /**
  102627. * Rebuilds the elements related to this component in case of
  102628. * context lost for instance.
  102629. */
  102630. OctreeSceneComponent.prototype.rebuild = function () {
  102631. // Nothing to do here.
  102632. };
  102633. /**
  102634. * Disposes the component and the associated ressources.
  102635. */
  102636. OctreeSceneComponent.prototype.dispose = function () {
  102637. // Nothing to do here.
  102638. };
  102639. return OctreeSceneComponent;
  102640. }());
  102641. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  102642. })(BABYLON || (BABYLON = {}));
  102643. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  102644. var BABYLON;
  102645. (function (BABYLON) {
  102646. /**
  102647. * Postprocess used to generate anaglyphic rendering
  102648. */
  102649. var AnaglyphPostProcess = /** @class */ (function (_super) {
  102650. __extends(AnaglyphPostProcess, _super);
  102651. /**
  102652. * Creates a new AnaglyphPostProcess
  102653. * @param name defines postprocess name
  102654. * @param options defines creation options or target ratio scale
  102655. * @param rigCameras defines cameras using this postprocess
  102656. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  102657. * @param engine defines hosting engine
  102658. * @param reusable defines if the postprocess will be reused multiple times per frame
  102659. */
  102660. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  102661. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  102662. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102663. _this.onApplyObservable.add(function (effect) {
  102664. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  102665. });
  102666. return _this;
  102667. }
  102668. return AnaglyphPostProcess;
  102669. }(BABYLON.PostProcess));
  102670. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  102671. })(BABYLON || (BABYLON = {}));
  102672. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  102673. var BABYLON;
  102674. (function (BABYLON) {
  102675. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  102676. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102677. });
  102678. /**
  102679. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  102680. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102681. */
  102682. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  102683. __extends(AnaglyphArcRotateCamera, _super);
  102684. /**
  102685. * Creates a new AnaglyphArcRotateCamera
  102686. * @param name defines camera name
  102687. * @param alpha defines alpha angle (in radians)
  102688. * @param beta defines beta angle (in radians)
  102689. * @param radius defines radius
  102690. * @param target defines camera target
  102691. * @param interaxialDistance defines distance between each color axis
  102692. * @param scene defines the hosting scene
  102693. */
  102694. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  102695. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102696. _this.interaxialDistance = interaxialDistance;
  102697. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102698. return _this;
  102699. }
  102700. /**
  102701. * Gets camera class name
  102702. * @returns AnaglyphArcRotateCamera
  102703. */
  102704. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  102705. return "AnaglyphArcRotateCamera";
  102706. };
  102707. return AnaglyphArcRotateCamera;
  102708. }(BABYLON.ArcRotateCamera));
  102709. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  102710. })(BABYLON || (BABYLON = {}));
  102711. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  102712. var BABYLON;
  102713. (function (BABYLON) {
  102714. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  102715. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102716. });
  102717. /**
  102718. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  102719. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102720. */
  102721. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  102722. __extends(AnaglyphFreeCamera, _super);
  102723. /**
  102724. * Creates a new AnaglyphFreeCamera
  102725. * @param name defines camera name
  102726. * @param position defines initial position
  102727. * @param interaxialDistance defines distance between each color axis
  102728. * @param scene defines the hosting scene
  102729. */
  102730. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  102731. var _this = _super.call(this, name, position, scene) || this;
  102732. _this.interaxialDistance = interaxialDistance;
  102733. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102734. return _this;
  102735. }
  102736. /**
  102737. * Gets camera class name
  102738. * @returns AnaglyphFreeCamera
  102739. */
  102740. AnaglyphFreeCamera.prototype.getClassName = function () {
  102741. return "AnaglyphFreeCamera";
  102742. };
  102743. return AnaglyphFreeCamera;
  102744. }(BABYLON.FreeCamera));
  102745. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  102746. })(BABYLON || (BABYLON = {}));
  102747. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  102748. var BABYLON;
  102749. (function (BABYLON) {
  102750. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  102751. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102752. });
  102753. /**
  102754. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  102755. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102756. */
  102757. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  102758. __extends(AnaglyphGamepadCamera, _super);
  102759. /**
  102760. * Creates a new AnaglyphGamepadCamera
  102761. * @param name defines camera name
  102762. * @param position defines initial position
  102763. * @param interaxialDistance defines distance between each color axis
  102764. * @param scene defines the hosting scene
  102765. */
  102766. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  102767. var _this = _super.call(this, name, position, scene) || this;
  102768. _this.interaxialDistance = interaxialDistance;
  102769. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102770. return _this;
  102771. }
  102772. /**
  102773. * Gets camera class name
  102774. * @returns AnaglyphGamepadCamera
  102775. */
  102776. AnaglyphGamepadCamera.prototype.getClassName = function () {
  102777. return "AnaglyphGamepadCamera";
  102778. };
  102779. return AnaglyphGamepadCamera;
  102780. }(BABYLON.GamepadCamera));
  102781. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  102782. })(BABYLON || (BABYLON = {}));
  102783. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  102784. var BABYLON;
  102785. (function (BABYLON) {
  102786. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  102787. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102788. });
  102789. /**
  102790. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  102791. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102792. */
  102793. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  102794. __extends(AnaglyphUniversalCamera, _super);
  102795. /**
  102796. * Creates a new AnaglyphUniversalCamera
  102797. * @param name defines camera name
  102798. * @param position defines initial position
  102799. * @param interaxialDistance defines distance between each color axis
  102800. * @param scene defines the hosting scene
  102801. */
  102802. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  102803. var _this = _super.call(this, name, position, scene) || this;
  102804. _this.interaxialDistance = interaxialDistance;
  102805. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102806. return _this;
  102807. }
  102808. /**
  102809. * Gets camera class name
  102810. * @returns AnaglyphUniversalCamera
  102811. */
  102812. AnaglyphUniversalCamera.prototype.getClassName = function () {
  102813. return "AnaglyphUniversalCamera";
  102814. };
  102815. return AnaglyphUniversalCamera;
  102816. }(BABYLON.UniversalCamera));
  102817. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  102818. })(BABYLON || (BABYLON = {}));
  102819. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  102820. var BABYLON;
  102821. (function (BABYLON) {
  102822. /**
  102823. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  102824. */
  102825. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  102826. __extends(StereoscopicInterlacePostProcess, _super);
  102827. /**
  102828. * Initializes a StereoscopicInterlacePostProcess
  102829. * @param name The name of the effect.
  102830. * @param rigCameras The rig cameras to be appled to the post process
  102831. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  102832. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  102833. * @param engine The engine which the post process will be applied. (default: current engine)
  102834. * @param reusable If the post process can be reused on the same frame. (default: false)
  102835. */
  102836. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  102837. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  102838. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102839. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  102840. _this.onSizeChangedObservable.add(function () {
  102841. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  102842. });
  102843. _this.onApplyObservable.add(function (effect) {
  102844. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  102845. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  102846. });
  102847. return _this;
  102848. }
  102849. return StereoscopicInterlacePostProcess;
  102850. }(BABYLON.PostProcess));
  102851. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  102852. })(BABYLON || (BABYLON = {}));
  102853. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  102854. var BABYLON;
  102855. (function (BABYLON) {
  102856. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  102857. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102858. });
  102859. /**
  102860. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  102861. * @see http://doc.babylonjs.com/features/cameras
  102862. */
  102863. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  102864. __extends(StereoscopicArcRotateCamera, _super);
  102865. /**
  102866. * Creates a new StereoscopicArcRotateCamera
  102867. * @param name defines camera name
  102868. * @param alpha defines alpha angle (in radians)
  102869. * @param beta defines beta angle (in radians)
  102870. * @param radius defines radius
  102871. * @param target defines camera target
  102872. * @param interaxialDistance defines distance between each color axis
  102873. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102874. * @param scene defines the hosting scene
  102875. */
  102876. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  102877. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102878. _this.interaxialDistance = interaxialDistance;
  102879. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102880. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102881. return _this;
  102882. }
  102883. /**
  102884. * Gets camera class name
  102885. * @returns StereoscopicArcRotateCamera
  102886. */
  102887. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  102888. return "StereoscopicArcRotateCamera";
  102889. };
  102890. return StereoscopicArcRotateCamera;
  102891. }(BABYLON.ArcRotateCamera));
  102892. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  102893. })(BABYLON || (BABYLON = {}));
  102894. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  102895. var BABYLON;
  102896. (function (BABYLON) {
  102897. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  102898. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102899. });
  102900. /**
  102901. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  102902. * @see http://doc.babylonjs.com/features/cameras
  102903. */
  102904. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  102905. __extends(StereoscopicFreeCamera, _super);
  102906. /**
  102907. * Creates a new StereoscopicFreeCamera
  102908. * @param name defines camera name
  102909. * @param position defines initial position
  102910. * @param interaxialDistance defines distance between each color axis
  102911. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102912. * @param scene defines the hosting scene
  102913. */
  102914. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102915. var _this = _super.call(this, name, position, scene) || this;
  102916. _this.interaxialDistance = interaxialDistance;
  102917. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102918. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102919. return _this;
  102920. }
  102921. /**
  102922. * Gets camera class name
  102923. * @returns StereoscopicFreeCamera
  102924. */
  102925. StereoscopicFreeCamera.prototype.getClassName = function () {
  102926. return "StereoscopicFreeCamera";
  102927. };
  102928. return StereoscopicFreeCamera;
  102929. }(BABYLON.FreeCamera));
  102930. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  102931. })(BABYLON || (BABYLON = {}));
  102932. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  102933. var BABYLON;
  102934. (function (BABYLON) {
  102935. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  102936. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102937. });
  102938. /**
  102939. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  102940. * @see http://doc.babylonjs.com/features/cameras
  102941. */
  102942. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  102943. __extends(StereoscopicGamepadCamera, _super);
  102944. /**
  102945. * Creates a new StereoscopicGamepadCamera
  102946. * @param name defines camera name
  102947. * @param position defines initial position
  102948. * @param interaxialDistance defines distance between each color axis
  102949. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102950. * @param scene defines the hosting scene
  102951. */
  102952. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102953. var _this = _super.call(this, name, position, scene) || this;
  102954. _this.interaxialDistance = interaxialDistance;
  102955. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102956. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102957. return _this;
  102958. }
  102959. /**
  102960. * Gets camera class name
  102961. * @returns StereoscopicGamepadCamera
  102962. */
  102963. StereoscopicGamepadCamera.prototype.getClassName = function () {
  102964. return "StereoscopicGamepadCamera";
  102965. };
  102966. return StereoscopicGamepadCamera;
  102967. }(BABYLON.GamepadCamera));
  102968. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  102969. })(BABYLON || (BABYLON = {}));
  102970. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  102971. var BABYLON;
  102972. (function (BABYLON) {
  102973. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  102974. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102975. });
  102976. /**
  102977. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  102978. * @see http://doc.babylonjs.com/features/cameras
  102979. */
  102980. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  102981. __extends(StereoscopicUniversalCamera, _super);
  102982. /**
  102983. * Creates a new StereoscopicUniversalCamera
  102984. * @param name defines camera name
  102985. * @param position defines initial position
  102986. * @param interaxialDistance defines distance between each color axis
  102987. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102988. * @param scene defines the hosting scene
  102989. */
  102990. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102991. var _this = _super.call(this, name, position, scene) || this;
  102992. _this.interaxialDistance = interaxialDistance;
  102993. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102994. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102995. return _this;
  102996. }
  102997. /**
  102998. * Gets camera class name
  102999. * @returns StereoscopicUniversalCamera
  103000. */
  103001. StereoscopicUniversalCamera.prototype.getClassName = function () {
  103002. return "StereoscopicUniversalCamera";
  103003. };
  103004. return StereoscopicUniversalCamera;
  103005. }(BABYLON.UniversalCamera));
  103006. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  103007. })(BABYLON || (BABYLON = {}));
  103008. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  103009. var BABYLON;
  103010. (function (BABYLON) {
  103011. /**
  103012. * VRDistortionCorrectionPostProcess used for mobile VR
  103013. */
  103014. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  103015. __extends(VRDistortionCorrectionPostProcess, _super);
  103016. /**
  103017. * Initializes the VRDistortionCorrectionPostProcess
  103018. * @param name The name of the effect.
  103019. * @param camera The camera to apply the render pass to.
  103020. * @param isRightEye If this is for the right eye distortion
  103021. * @param vrMetrics All the required metrics for the VR camera
  103022. */
  103023. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  103024. var _this = _super.call(this, name, "vrDistortionCorrection", [
  103025. 'LensCenter',
  103026. 'Scale',
  103027. 'ScaleIn',
  103028. 'HmdWarpParam'
  103029. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103030. _this._isRightEye = isRightEye;
  103031. _this._distortionFactors = vrMetrics.distortionK;
  103032. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103033. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103034. _this.adaptScaleToCurrentViewport = true;
  103035. _this.onSizeChangedObservable.add(function () {
  103036. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103037. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103038. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103039. });
  103040. _this.onApplyObservable.add(function (effect) {
  103041. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103042. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103043. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103044. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103045. });
  103046. return _this;
  103047. }
  103048. return VRDistortionCorrectionPostProcess;
  103049. }(BABYLON.PostProcess));
  103050. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103051. })(BABYLON || (BABYLON = {}));
  103052. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103053. var BABYLON;
  103054. (function (BABYLON) {
  103055. /**
  103056. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103057. * Screen rotation is taken into account.
  103058. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103059. */
  103060. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103061. /**
  103062. * Instantiates a new input
  103063. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103064. */
  103065. function FreeCameraDeviceOrientationInput() {
  103066. var _this = this;
  103067. this._screenOrientationAngle = 0;
  103068. this._screenQuaternion = new BABYLON.Quaternion();
  103069. this._alpha = 0;
  103070. this._beta = 0;
  103071. this._gamma = 0;
  103072. this._orientationChanged = function () {
  103073. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103074. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103075. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103076. };
  103077. this._deviceOrientation = function (evt) {
  103078. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103079. _this._beta = evt.beta !== null ? evt.beta : 0;
  103080. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103081. };
  103082. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103083. this._orientationChanged();
  103084. }
  103085. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103086. /**
  103087. * Define the camera controlled by the input.
  103088. */
  103089. get: function () {
  103090. return this._camera;
  103091. },
  103092. set: function (camera) {
  103093. this._camera = camera;
  103094. if (this._camera != null && !this._camera.rotationQuaternion) {
  103095. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103096. }
  103097. },
  103098. enumerable: true,
  103099. configurable: true
  103100. });
  103101. /**
  103102. * Attach the input controls to a specific dom element to get the input from.
  103103. * @param element Defines the element the controls should be listened from
  103104. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103105. */
  103106. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103107. window.addEventListener("orientationchange", this._orientationChanged);
  103108. window.addEventListener("deviceorientation", this._deviceOrientation);
  103109. //In certain cases, the attach control is called AFTER orientation was changed,
  103110. //So this is needed.
  103111. this._orientationChanged();
  103112. };
  103113. /**
  103114. * Detach the current controls from the specified dom element.
  103115. * @param element Defines the element to stop listening the inputs from
  103116. */
  103117. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103118. window.removeEventListener("orientationchange", this._orientationChanged);
  103119. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103120. };
  103121. /**
  103122. * Update the current camera state depending on the inputs that have been used this frame.
  103123. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103124. */
  103125. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103126. //if no device orientation provided, don't update the rotation.
  103127. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103128. if (!this._alpha)
  103129. return;
  103130. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103131. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103132. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103133. //Mirror on XY Plane
  103134. this._camera.rotationQuaternion.z *= -1;
  103135. this._camera.rotationQuaternion.w *= -1;
  103136. };
  103137. /**
  103138. * Gets the class name of the current intput.
  103139. * @returns the class name
  103140. */
  103141. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103142. return "FreeCameraDeviceOrientationInput";
  103143. };
  103144. /**
  103145. * Get the friendly name associated with the input class.
  103146. * @returns the input friendly name
  103147. */
  103148. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103149. return "deviceOrientation";
  103150. };
  103151. return FreeCameraDeviceOrientationInput;
  103152. }());
  103153. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103154. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103155. })(BABYLON || (BABYLON = {}));
  103156. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103157. var BABYLON;
  103158. (function (BABYLON) {
  103159. /**
  103160. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103161. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103162. */
  103163. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103164. /**
  103165. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103166. */
  103167. function ArcRotateCameraVRDeviceOrientationInput() {
  103168. /**
  103169. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103170. */
  103171. this.alphaCorrection = 1;
  103172. /**
  103173. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103174. */
  103175. this.betaCorrection = 1;
  103176. /**
  103177. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103178. */
  103179. this.gammaCorrection = 1;
  103180. this._alpha = 0;
  103181. this._gamma = 0;
  103182. this._dirty = false;
  103183. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103184. }
  103185. /**
  103186. * Attach the input controls to a specific dom element to get the input from.
  103187. * @param element Defines the element the controls should be listened from
  103188. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103189. */
  103190. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103191. this.camera.attachControl(element, noPreventDefault);
  103192. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103193. };
  103194. /** @hidden */
  103195. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103196. if (evt.alpha !== null) {
  103197. this._alpha = +evt.alpha | 0;
  103198. }
  103199. if (evt.gamma !== null) {
  103200. this._gamma = +evt.gamma | 0;
  103201. }
  103202. this._dirty = true;
  103203. };
  103204. /**
  103205. * Update the current camera state depending on the inputs that have been used this frame.
  103206. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103207. */
  103208. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103209. if (this._dirty) {
  103210. this._dirty = false;
  103211. if (this._gamma < 0) {
  103212. this._gamma = 180 + this._gamma;
  103213. }
  103214. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103215. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103216. }
  103217. };
  103218. /**
  103219. * Detach the current controls from the specified dom element.
  103220. * @param element Defines the element to stop listening the inputs from
  103221. */
  103222. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103223. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103224. };
  103225. /**
  103226. * Gets the class name of the current intput.
  103227. * @returns the class name
  103228. */
  103229. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103230. return "ArcRotateCameraVRDeviceOrientationInput";
  103231. };
  103232. /**
  103233. * Get the friendly name associated with the input class.
  103234. * @returns the input friendly name
  103235. */
  103236. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103237. return "VRDeviceOrientation";
  103238. };
  103239. return ArcRotateCameraVRDeviceOrientationInput;
  103240. }());
  103241. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103242. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103243. })(BABYLON || (BABYLON = {}));
  103244. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103245. var BABYLON;
  103246. (function (BABYLON) {
  103247. /**
  103248. * This represents all the required metrics to create a VR camera.
  103249. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103250. */
  103251. var VRCameraMetrics = /** @class */ (function () {
  103252. function VRCameraMetrics() {
  103253. /**
  103254. * Define if the current vr camera should compensate the distortion of the lense or not.
  103255. */
  103256. this.compensateDistortion = true;
  103257. }
  103258. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103259. /**
  103260. * Gets the rendering aspect ratio based on the provided resolutions.
  103261. */
  103262. get: function () {
  103263. return this.hResolution / (2 * this.vResolution);
  103264. },
  103265. enumerable: true,
  103266. configurable: true
  103267. });
  103268. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103269. /**
  103270. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103271. */
  103272. get: function () {
  103273. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103274. },
  103275. enumerable: true,
  103276. configurable: true
  103277. });
  103278. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103279. /**
  103280. * @hidden
  103281. */
  103282. get: function () {
  103283. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103284. var h = (4 * meters) / this.hScreenSize;
  103285. return BABYLON.Matrix.Translation(h, 0, 0);
  103286. },
  103287. enumerable: true,
  103288. configurable: true
  103289. });
  103290. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103291. /**
  103292. * @hidden
  103293. */
  103294. get: function () {
  103295. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103296. var h = (4 * meters) / this.hScreenSize;
  103297. return BABYLON.Matrix.Translation(-h, 0, 0);
  103298. },
  103299. enumerable: true,
  103300. configurable: true
  103301. });
  103302. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103303. /**
  103304. * @hidden
  103305. */
  103306. get: function () {
  103307. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103308. },
  103309. enumerable: true,
  103310. configurable: true
  103311. });
  103312. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103313. /**
  103314. * @hidden
  103315. */
  103316. get: function () {
  103317. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103318. },
  103319. enumerable: true,
  103320. configurable: true
  103321. });
  103322. /**
  103323. * Get the default VRMetrics based on the most generic setup.
  103324. * @returns the default vr metrics
  103325. */
  103326. VRCameraMetrics.GetDefault = function () {
  103327. var result = new VRCameraMetrics();
  103328. result.hResolution = 1280;
  103329. result.vResolution = 800;
  103330. result.hScreenSize = 0.149759993;
  103331. result.vScreenSize = 0.0935999975;
  103332. result.vScreenCenter = 0.0467999987;
  103333. result.eyeToScreenDistance = 0.0410000011;
  103334. result.lensSeparationDistance = 0.0635000020;
  103335. result.interpupillaryDistance = 0.0640000030;
  103336. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103337. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103338. result.postProcessScaleFactor = 1.714605507808412;
  103339. result.lensCenterOffset = 0.151976421;
  103340. return result;
  103341. };
  103342. return VRCameraMetrics;
  103343. }());
  103344. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103345. })(BABYLON || (BABYLON = {}));
  103346. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103347. var BABYLON;
  103348. (function (BABYLON) {
  103349. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103350. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103351. });
  103352. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103353. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103354. });
  103355. /**
  103356. * This represents a WebVR camera.
  103357. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103358. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103359. */
  103360. var WebVRFreeCamera = /** @class */ (function (_super) {
  103361. __extends(WebVRFreeCamera, _super);
  103362. /**
  103363. * Instantiates a WebVRFreeCamera.
  103364. * @param name The name of the WebVRFreeCamera
  103365. * @param position The starting anchor position for the camera
  103366. * @param scene The scene the camera belongs to
  103367. * @param webVROptions a set of customizable options for the webVRCamera
  103368. */
  103369. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103370. if (webVROptions === void 0) { webVROptions = {}; }
  103371. var _this = _super.call(this, name, position, scene) || this;
  103372. _this.webVROptions = webVROptions;
  103373. /**
  103374. * @hidden
  103375. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103376. */
  103377. _this._vrDevice = null;
  103378. /**
  103379. * The rawPose of the vrDevice.
  103380. */
  103381. _this.rawPose = null;
  103382. _this._specsVersion = "1.1";
  103383. _this._attached = false;
  103384. _this._descendants = [];
  103385. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103386. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103387. /** @hidden */
  103388. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103389. _this._standingMatrix = null;
  103390. /**
  103391. * Represents device position in babylon space.
  103392. */
  103393. _this.devicePosition = BABYLON.Vector3.Zero();
  103394. /**
  103395. * Represents device rotation in babylon space.
  103396. */
  103397. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103398. /**
  103399. * The scale of the device to be used when translating from device space to babylon space.
  103400. */
  103401. _this.deviceScaleFactor = 1;
  103402. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103403. _this._worldToDevice = BABYLON.Matrix.Identity();
  103404. /**
  103405. * References to the webVR controllers for the vrDevice.
  103406. */
  103407. _this.controllers = [];
  103408. /**
  103409. * Emits an event when a controller is attached.
  103410. */
  103411. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103412. /**
  103413. * Emits an event when a controller's mesh has been loaded;
  103414. */
  103415. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103416. /**
  103417. * Emits an event when the HMD's pose has been updated.
  103418. */
  103419. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103420. _this._poseSet = false;
  103421. /**
  103422. * If the rig cameras be used as parent instead of this camera.
  103423. */
  103424. _this.rigParenting = true;
  103425. _this._defaultHeight = undefined;
  103426. _this._htmlElementAttached = null;
  103427. _this._detachIfAttached = function () {
  103428. var vrDisplay = _this.getEngine().getVRDevice();
  103429. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103430. _this.detachControl(_this._htmlElementAttached);
  103431. }
  103432. };
  103433. _this._workingVector = BABYLON.Vector3.Zero();
  103434. _this._oneVector = BABYLON.Vector3.One();
  103435. _this._workingMatrix = BABYLON.Matrix.Identity();
  103436. _this._tmpMatrix = new BABYLON.Matrix();
  103437. _this._cache.position = BABYLON.Vector3.Zero();
  103438. if (webVROptions.defaultHeight) {
  103439. _this._defaultHeight = webVROptions.defaultHeight;
  103440. _this.position.y = _this._defaultHeight;
  103441. }
  103442. _this.minZ = 0.1;
  103443. //legacy support - the compensation boolean was removed.
  103444. if (arguments.length === 5) {
  103445. _this.webVROptions = arguments[4];
  103446. }
  103447. // default webVR options
  103448. if (_this.webVROptions.trackPosition == undefined) {
  103449. _this.webVROptions.trackPosition = true;
  103450. }
  103451. if (_this.webVROptions.controllerMeshes == undefined) {
  103452. _this.webVROptions.controllerMeshes = true;
  103453. }
  103454. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103455. _this.webVROptions.defaultLightingOnControllers = true;
  103456. }
  103457. _this.rotationQuaternion = new BABYLON.Quaternion();
  103458. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103459. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103460. }
  103461. //enable VR
  103462. var engine = _this.getEngine();
  103463. _this._onVREnabled = function (success) { if (success) {
  103464. _this.initControllers();
  103465. } };
  103466. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103467. engine.initWebVR().add(function (event) {
  103468. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103469. return;
  103470. }
  103471. _this._vrDevice = event.vrDisplay;
  103472. //reset the rig parameters.
  103473. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103474. if (_this._attached) {
  103475. _this.getEngine().enableVR();
  103476. }
  103477. });
  103478. if (typeof (VRFrameData) !== "undefined")
  103479. _this._frameData = new VRFrameData();
  103480. /**
  103481. * The idea behind the following lines:
  103482. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103483. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103484. * the second will not show it correctly.
  103485. *
  103486. * To solve this - each object that has the camera as parent will be added to a protected array.
  103487. * When the rig camera renders, it will take this array and set all of those to be its children.
  103488. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103489. * Amazing!
  103490. */
  103491. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103492. if (camera.parent === _this && _this.rigParenting) {
  103493. _this._descendants = _this.getDescendants(true, function (n) {
  103494. // don't take the cameras or the controllers!
  103495. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103496. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103497. return !isController && !isRigCamera;
  103498. });
  103499. _this._descendants.forEach(function (node) {
  103500. node.parent = camera;
  103501. });
  103502. }
  103503. });
  103504. scene.onAfterCameraRenderObservable.add(function (camera) {
  103505. if (camera.parent === _this && _this.rigParenting) {
  103506. _this._descendants.forEach(function (node) {
  103507. node.parent = _this;
  103508. });
  103509. }
  103510. });
  103511. return _this;
  103512. }
  103513. /**
  103514. * Gets the device distance from the ground in meters.
  103515. * @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.
  103516. */
  103517. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103518. if (this._standingMatrix) {
  103519. // Add standing matrix offset to get real offset from ground in room
  103520. this._standingMatrix.getTranslationToRef(this._workingVector);
  103521. return this._deviceRoomPosition.y + this._workingVector.y;
  103522. }
  103523. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103524. return this._defaultHeight || 0;
  103525. };
  103526. /**
  103527. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103528. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103529. */
  103530. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103531. var _this = this;
  103532. if (callback === void 0) { callback = function (bool) { }; }
  103533. // Use standing matrix if available
  103534. this.getEngine().initWebVRAsync().then(function (result) {
  103535. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103536. callback(false);
  103537. }
  103538. else {
  103539. _this._standingMatrix = new BABYLON.Matrix();
  103540. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103541. if (!_this.getScene().useRightHandedSystem) {
  103542. [2, 6, 8, 9, 14].forEach(function (num) {
  103543. if (_this._standingMatrix) {
  103544. _this._standingMatrix.m[num] *= -1;
  103545. }
  103546. });
  103547. }
  103548. callback(true);
  103549. }
  103550. });
  103551. };
  103552. /**
  103553. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103554. * @returns A promise with a boolean set to if the standing matrix is supported.
  103555. */
  103556. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103557. var _this = this;
  103558. return new Promise(function (res, rej) {
  103559. _this.useStandingMatrix(function (supported) {
  103560. res(supported);
  103561. });
  103562. });
  103563. };
  103564. /**
  103565. * Disposes the camera
  103566. */
  103567. WebVRFreeCamera.prototype.dispose = function () {
  103568. this._detachIfAttached();
  103569. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103570. if (this._updateCacheWhenTrackingDisabledObserver) {
  103571. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103572. }
  103573. _super.prototype.dispose.call(this);
  103574. };
  103575. /**
  103576. * Gets a vrController by name.
  103577. * @param name The name of the controller to retreive
  103578. * @returns the controller matching the name specified or null if not found
  103579. */
  103580. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  103581. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  103582. var gp = _a[_i];
  103583. if (gp.hand === name) {
  103584. return gp;
  103585. }
  103586. }
  103587. return null;
  103588. };
  103589. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  103590. /**
  103591. * The controller corrisponding to the users left hand.
  103592. */
  103593. get: function () {
  103594. if (!this._leftController) {
  103595. this._leftController = this.getControllerByName("left");
  103596. }
  103597. return this._leftController;
  103598. },
  103599. enumerable: true,
  103600. configurable: true
  103601. });
  103602. ;
  103603. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  103604. /**
  103605. * The controller corrisponding to the users right hand.
  103606. */
  103607. get: function () {
  103608. if (!this._rightController) {
  103609. this._rightController = this.getControllerByName("right");
  103610. }
  103611. return this._rightController;
  103612. },
  103613. enumerable: true,
  103614. configurable: true
  103615. });
  103616. ;
  103617. /**
  103618. * Casts a ray forward from the vrCamera's gaze.
  103619. * @param length Length of the ray (default: 100)
  103620. * @returns the ray corrisponding to the gaze
  103621. */
  103622. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  103623. if (length === void 0) { length = 100; }
  103624. if (this.leftCamera) {
  103625. // Use left eye to avoid computation to compute center on every call
  103626. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  103627. }
  103628. else {
  103629. return _super.prototype.getForwardRay.call(this, length);
  103630. }
  103631. };
  103632. /**
  103633. * @hidden
  103634. * Updates the camera based on device's frame data
  103635. */
  103636. WebVRFreeCamera.prototype._checkInputs = function () {
  103637. if (this._vrDevice && this._vrDevice.isPresenting) {
  103638. this._vrDevice.getFrameData(this._frameData);
  103639. this.updateFromDevice(this._frameData.pose);
  103640. }
  103641. _super.prototype._checkInputs.call(this);
  103642. };
  103643. /**
  103644. * Updates the poseControlled values based on the input device pose.
  103645. * @param poseData Pose coming from the device
  103646. */
  103647. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  103648. if (poseData && poseData.orientation) {
  103649. this.rawPose = poseData;
  103650. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  103651. if (this.getScene().useRightHandedSystem) {
  103652. this._deviceRoomRotationQuaternion.z *= -1;
  103653. this._deviceRoomRotationQuaternion.w *= -1;
  103654. }
  103655. if (this.webVROptions.trackPosition && this.rawPose.position) {
  103656. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  103657. if (this.getScene().useRightHandedSystem) {
  103658. this._deviceRoomPosition.z *= -1;
  103659. }
  103660. }
  103661. this._poseSet = true;
  103662. }
  103663. };
  103664. /**
  103665. * WebVR's attach control will start broadcasting frames to the device.
  103666. * Note that in certain browsers (chrome for example) this function must be called
  103667. * within a user-interaction callback. Example:
  103668. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  103669. *
  103670. * @param element html element to attach the vrDevice to
  103671. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  103672. */
  103673. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  103674. _super.prototype.attachControl.call(this, element, noPreventDefault);
  103675. this._attached = true;
  103676. this._htmlElementAttached = element;
  103677. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  103678. if (this._vrDevice) {
  103679. this.getEngine().enableVR();
  103680. }
  103681. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103682. };
  103683. /**
  103684. * Detaches the camera from the html element and disables VR
  103685. *
  103686. * @param element html element to detach from
  103687. */
  103688. WebVRFreeCamera.prototype.detachControl = function (element) {
  103689. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  103690. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  103691. _super.prototype.detachControl.call(this, element);
  103692. this._attached = false;
  103693. this.getEngine().disableVR();
  103694. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103695. };
  103696. /**
  103697. * @returns the name of this class
  103698. */
  103699. WebVRFreeCamera.prototype.getClassName = function () {
  103700. return "WebVRFreeCamera";
  103701. };
  103702. /**
  103703. * Calls resetPose on the vrDisplay
  103704. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  103705. */
  103706. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  103707. //uses the vrDisplay's "resetPose()".
  103708. //pitch and roll won't be affected.
  103709. this._vrDevice.resetPose();
  103710. };
  103711. /**
  103712. * @hidden
  103713. * Updates the rig cameras (left and right eye)
  103714. */
  103715. WebVRFreeCamera.prototype._updateRigCameras = function () {
  103716. var camLeft = this._rigCameras[0];
  103717. var camRight = this._rigCameras[1];
  103718. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  103719. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  103720. camLeft.position.copyFrom(this._deviceRoomPosition);
  103721. camRight.position.copyFrom(this._deviceRoomPosition);
  103722. };
  103723. // Remove translation from 6dof headset if trackposition is set to false
  103724. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  103725. if (isViewMatrix === void 0) { isViewMatrix = false; }
  103726. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  103727. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  103728. if (!isViewMatrix) {
  103729. this._tmpMatrix.invert();
  103730. }
  103731. this._tmpMatrix.multiplyToRef(matrix, matrix);
  103732. }
  103733. };
  103734. /**
  103735. * @hidden
  103736. * Updates the cached values of the camera
  103737. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  103738. */
  103739. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  103740. var _this = this;
  103741. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  103742. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  103743. if (!this.updateCacheCalled) {
  103744. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  103745. this.updateCacheCalled = true;
  103746. this.update();
  103747. }
  103748. // Set working vector to the device position in room space rotated by the new rotation
  103749. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  103750. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  103751. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  103752. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  103753. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  103754. // Add translation from anchor position
  103755. this._deviceToWorld.getTranslationToRef(this._workingVector);
  103756. this._workingVector.addInPlace(this.position);
  103757. this._workingVector.subtractInPlace(this._cache.position);
  103758. this._deviceToWorld.setTranslation(this._workingVector);
  103759. // Set an inverted matrix to be used when updating the camera
  103760. this._deviceToWorld.invertToRef(this._worldToDevice);
  103761. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  103762. this.controllers.forEach(function (controller) {
  103763. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  103764. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  103765. controller.update();
  103766. });
  103767. }
  103768. if (!ignoreParentClass) {
  103769. _super.prototype._updateCache.call(this);
  103770. }
  103771. this.updateCacheCalled = false;
  103772. };
  103773. /**
  103774. * @hidden
  103775. * Get current device position in babylon world
  103776. */
  103777. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  103778. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  103779. };
  103780. /**
  103781. * Updates the current device position and rotation in the babylon world
  103782. */
  103783. WebVRFreeCamera.prototype.update = function () {
  103784. this._computeDevicePosition();
  103785. // Get current device rotation in babylon world
  103786. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  103787. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  103788. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  103789. if (this._poseSet) {
  103790. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  103791. }
  103792. _super.prototype.update.call(this);
  103793. };
  103794. /**
  103795. * @hidden
  103796. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  103797. * @returns an identity matrix
  103798. */
  103799. WebVRFreeCamera.prototype._getViewMatrix = function () {
  103800. return BABYLON.Matrix.Identity();
  103801. };
  103802. /**
  103803. * This function is called by the two RIG cameras.
  103804. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  103805. */
  103806. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  103807. var _this = this;
  103808. // Update the parent camera prior to using a child camera to avoid desynchronization
  103809. var parentCamera = this._cameraRigParams["parentCamera"];
  103810. parentCamera._updateCache();
  103811. //WebVR 1.1
  103812. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  103813. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  103814. if (!this.getScene().useRightHandedSystem) {
  103815. [2, 6, 8, 9, 14].forEach(function (num) {
  103816. _this._webvrViewMatrix.m[num] *= -1;
  103817. });
  103818. }
  103819. // update the camera rotation matrix
  103820. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  103821. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  103822. // Computing target and final matrix
  103823. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  103824. // should the view matrix be updated with scale and position offset?
  103825. if (parentCamera.deviceScaleFactor !== 1) {
  103826. this._webvrViewMatrix.invert();
  103827. // scale the position, if set
  103828. if (parentCamera.deviceScaleFactor) {
  103829. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  103830. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  103831. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  103832. }
  103833. this._webvrViewMatrix.invert();
  103834. }
  103835. // Remove translation from 6dof headset if trackposition is set to false
  103836. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  103837. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  103838. // Compute global position
  103839. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  103840. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  103841. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  103842. this._workingMatrix.getTranslationToRef(this._globalPosition);
  103843. this._markSyncedWithParent();
  103844. return this._webvrViewMatrix;
  103845. };
  103846. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  103847. var _this = this;
  103848. var parentCamera = this.parent;
  103849. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  103850. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  103851. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  103852. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  103853. //babylon compatible matrix
  103854. if (!this.getScene().useRightHandedSystem) {
  103855. [8, 9, 10, 11].forEach(function (num) {
  103856. _this._projectionMatrix.m[num] *= -1;
  103857. });
  103858. }
  103859. return this._projectionMatrix;
  103860. };
  103861. /**
  103862. * Initializes the controllers and their meshes
  103863. */
  103864. WebVRFreeCamera.prototype.initControllers = function () {
  103865. var _this = this;
  103866. this.controllers = [];
  103867. var manager = this.getScene().gamepadManager;
  103868. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  103869. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  103870. var webVrController = gamepad;
  103871. if (webVrController.defaultModel) {
  103872. webVrController.defaultModel.setEnabled(false);
  103873. }
  103874. if (webVrController.hand === "right") {
  103875. _this._rightController = null;
  103876. }
  103877. if (webVrController.hand === "left") {
  103878. _this._leftController = null;
  103879. }
  103880. var controllerIndex = _this.controllers.indexOf(webVrController);
  103881. if (controllerIndex !== -1) {
  103882. _this.controllers.splice(controllerIndex, 1);
  103883. }
  103884. }
  103885. });
  103886. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  103887. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  103888. var webVrController_1 = gamepad;
  103889. if (!_this.webVROptions.trackPosition) {
  103890. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  103891. // Cache must be updated before rendering controllers to avoid them being one frame behind
  103892. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  103893. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  103894. _this._updateCache();
  103895. });
  103896. }
  103897. }
  103898. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  103899. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  103900. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  103901. if (_this.webVROptions.controllerMeshes) {
  103902. if (webVrController_1.defaultModel) {
  103903. webVrController_1.defaultModel.setEnabled(true);
  103904. }
  103905. else {
  103906. // Load the meshes
  103907. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  103908. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  103909. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  103910. if (_this.webVROptions.defaultLightingOnControllers) {
  103911. if (!_this._lightOnControllers) {
  103912. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  103913. }
  103914. var activateLightOnSubMeshes_1 = function (mesh, light) {
  103915. var children = mesh.getChildren();
  103916. if (children && children.length !== 0) {
  103917. children.forEach(function (mesh) {
  103918. light.includedOnlyMeshes.push(mesh);
  103919. activateLightOnSubMeshes_1(mesh, light);
  103920. });
  103921. }
  103922. };
  103923. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  103924. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  103925. }
  103926. });
  103927. }
  103928. }
  103929. webVrController_1.attachToPoseControlledCamera(_this);
  103930. // since this is async - sanity check. Is the controller already stored?
  103931. if (_this.controllers.indexOf(webVrController_1) === -1) {
  103932. //add to the controllers array
  103933. _this.controllers.push(webVrController_1);
  103934. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  103935. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  103936. // So we're overriding setting left & right manually to be sure
  103937. var firstViveWandDetected = false;
  103938. for (var i = 0; i < _this.controllers.length; i++) {
  103939. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103940. if (!firstViveWandDetected) {
  103941. firstViveWandDetected = true;
  103942. _this.controllers[i].hand = "left";
  103943. }
  103944. else {
  103945. _this.controllers[i].hand = "right";
  103946. }
  103947. }
  103948. }
  103949. //did we find enough controllers? Great! let the developer know.
  103950. if (_this.controllers.length >= 2) {
  103951. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  103952. }
  103953. }
  103954. }
  103955. });
  103956. };
  103957. return WebVRFreeCamera;
  103958. }(BABYLON.FreeCamera));
  103959. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  103960. })(BABYLON || (BABYLON = {}));
  103961. //# sourceMappingURL=babylon.webVRCamera.js.map
  103962. var BABYLON;
  103963. (function (BABYLON) {
  103964. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  103965. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  103966. });
  103967. // We're mainly based on the logic defined into the FreeCamera code
  103968. /**
  103969. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  103970. * being tilted forward or back and left or right.
  103971. */
  103972. var DeviceOrientationCamera = /** @class */ (function (_super) {
  103973. __extends(DeviceOrientationCamera, _super);
  103974. /**
  103975. * Creates a new device orientation camera
  103976. * @param name The name of the camera
  103977. * @param position The start position camera
  103978. * @param scene The scene the camera belongs to
  103979. */
  103980. function DeviceOrientationCamera(name, position, scene) {
  103981. var _this = _super.call(this, name, position, scene) || this;
  103982. _this._quaternionCache = new BABYLON.Quaternion();
  103983. _this.inputs.addDeviceOrientation();
  103984. return _this;
  103985. }
  103986. /**
  103987. * Gets the current instance class name ("DeviceOrientationCamera").
  103988. * This helps avoiding instanceof at run time.
  103989. * @returns the class name
  103990. */
  103991. DeviceOrientationCamera.prototype.getClassName = function () {
  103992. return "DeviceOrientationCamera";
  103993. };
  103994. /**
  103995. * @hidden
  103996. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  103997. */
  103998. DeviceOrientationCamera.prototype._checkInputs = function () {
  103999. _super.prototype._checkInputs.call(this);
  104000. this._quaternionCache.copyFrom(this.rotationQuaternion);
  104001. if (this._initialQuaternion) {
  104002. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104003. }
  104004. };
  104005. /**
  104006. * Reset the camera to its default orientation on the specified axis only.
  104007. * @param axis The axis to reset
  104008. */
  104009. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  104010. var _this = this;
  104011. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  104012. //can only work if this camera has a rotation quaternion already.
  104013. if (!this.rotationQuaternion)
  104014. return;
  104015. if (!this._initialQuaternion) {
  104016. this._initialQuaternion = new BABYLON.Quaternion();
  104017. }
  104018. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  104019. ['x', 'y', 'z'].forEach(function (axisName) {
  104020. if (!axis[axisName]) {
  104021. _this._initialQuaternion[axisName] = 0;
  104022. }
  104023. else {
  104024. _this._initialQuaternion[axisName] *= -1;
  104025. }
  104026. });
  104027. this._initialQuaternion.normalize();
  104028. //force rotation update
  104029. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104030. };
  104031. return DeviceOrientationCamera;
  104032. }(BABYLON.FreeCamera));
  104033. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104034. })(BABYLON || (BABYLON = {}));
  104035. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104036. var BABYLON;
  104037. (function (BABYLON) {
  104038. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104039. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104040. });
  104041. /**
  104042. * Camera used to simulate VR rendering (based on FreeCamera)
  104043. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104044. */
  104045. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104046. __extends(VRDeviceOrientationFreeCamera, _super);
  104047. /**
  104048. * Creates a new VRDeviceOrientationFreeCamera
  104049. * @param name defines camera name
  104050. * @param position defines the start position of the camera
  104051. * @param scene defines the scene the camera belongs to
  104052. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104053. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104054. */
  104055. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104056. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104057. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104058. var _this = _super.call(this, name, position, scene) || this;
  104059. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104060. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104061. return _this;
  104062. }
  104063. /**
  104064. * Gets camera class name
  104065. * @returns VRDeviceOrientationFreeCamera
  104066. */
  104067. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104068. return "VRDeviceOrientationFreeCamera";
  104069. };
  104070. return VRDeviceOrientationFreeCamera;
  104071. }(BABYLON.DeviceOrientationCamera));
  104072. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104073. })(BABYLON || (BABYLON = {}));
  104074. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104075. var BABYLON;
  104076. (function (BABYLON) {
  104077. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104078. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104079. });
  104080. /**
  104081. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104082. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104083. */
  104084. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104085. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104086. /**
  104087. * Creates a new VRDeviceOrientationArcRotateCamera
  104088. * @param name defines camera name
  104089. * @param alpha defines the camera rotation along the logitudinal axis
  104090. * @param beta defines the camera rotation along the latitudinal axis
  104091. * @param radius defines the camera distance from its target
  104092. * @param target defines the camera target
  104093. * @param scene defines the scene the camera belongs to
  104094. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104095. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104096. */
  104097. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104098. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104099. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104100. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104101. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104102. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104103. _this.inputs.addVRDeviceOrientation();
  104104. return _this;
  104105. }
  104106. /**
  104107. * Gets camera class name
  104108. * @returns VRDeviceOrientationArcRotateCamera
  104109. */
  104110. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104111. return "VRDeviceOrientationArcRotateCamera";
  104112. };
  104113. return VRDeviceOrientationArcRotateCamera;
  104114. }(BABYLON.ArcRotateCamera));
  104115. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104116. })(BABYLON || (BABYLON = {}));
  104117. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104118. var BABYLON;
  104119. (function (BABYLON) {
  104120. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104121. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104122. });
  104123. /**
  104124. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104125. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104126. */
  104127. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104128. __extends(VRDeviceOrientationGamepadCamera, _super);
  104129. /**
  104130. * Creates a new VRDeviceOrientationGamepadCamera
  104131. * @param name defines camera name
  104132. * @param position defines the start position of the camera
  104133. * @param scene defines the scene the camera belongs to
  104134. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104135. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104136. */
  104137. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104138. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104139. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104140. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104141. _this.inputs.addGamepad();
  104142. return _this;
  104143. }
  104144. /**
  104145. * Gets camera class name
  104146. * @returns VRDeviceOrientationGamepadCamera
  104147. */
  104148. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104149. return "VRDeviceOrientationGamepadCamera";
  104150. };
  104151. return VRDeviceOrientationGamepadCamera;
  104152. }(BABYLON.VRDeviceOrientationFreeCamera));
  104153. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104154. })(BABYLON || (BABYLON = {}));
  104155. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104156. var BABYLON;
  104157. (function (BABYLON) {
  104158. var VRExperienceHelperGazer = /** @class */ (function () {
  104159. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104160. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104161. this.scene = scene;
  104162. /** @hidden */
  104163. this._pointerDownOnMeshAsked = false;
  104164. /** @hidden */
  104165. this._isActionableMesh = false;
  104166. /** @hidden */
  104167. this._teleportationRequestInitiated = false;
  104168. /** @hidden */
  104169. this._teleportationBackRequestInitiated = false;
  104170. /** @hidden */
  104171. this._rotationRightAsked = false;
  104172. /** @hidden */
  104173. this._rotationLeftAsked = false;
  104174. /** @hidden */
  104175. this._dpadPressed = true;
  104176. /** @hidden */
  104177. this._activePointer = false;
  104178. this._id = VRExperienceHelperGazer._idCounter++;
  104179. // Gaze tracker
  104180. if (!gazeTrackerToClone) {
  104181. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104182. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104183. this._gazeTracker.isPickable = false;
  104184. this._gazeTracker.isVisible = false;
  104185. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104186. targetMat.specularColor = BABYLON.Color3.Black();
  104187. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104188. targetMat.backFaceCulling = false;
  104189. this._gazeTracker.material = targetMat;
  104190. }
  104191. else {
  104192. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104193. }
  104194. }
  104195. /** @hidden */
  104196. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104197. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104198. };
  104199. /** @hidden */
  104200. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104201. this._pointerDownOnMeshAsked = true;
  104202. if (this._currentHit) {
  104203. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104204. }
  104205. };
  104206. /** @hidden */
  104207. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104208. if (this._currentHit) {
  104209. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104210. }
  104211. this._pointerDownOnMeshAsked = false;
  104212. };
  104213. /** @hidden */
  104214. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104215. this._activePointer = true;
  104216. };
  104217. /** @hidden */
  104218. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104219. this._activePointer = false;
  104220. };
  104221. /** @hidden */
  104222. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104223. if (distance === void 0) { distance = 100; }
  104224. };
  104225. VRExperienceHelperGazer.prototype.dispose = function () {
  104226. this._interactionsEnabled = false;
  104227. this._teleportationEnabled = false;
  104228. if (this._gazeTracker) {
  104229. this._gazeTracker.dispose();
  104230. }
  104231. };
  104232. VRExperienceHelperGazer._idCounter = 0;
  104233. return VRExperienceHelperGazer;
  104234. }());
  104235. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104236. __extends(VRExperienceHelperControllerGazer, _super);
  104237. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104238. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104239. _this.webVRController = webVRController;
  104240. // Laser pointer
  104241. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104242. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104243. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104244. laserPointerMaterial.alpha = 0.6;
  104245. _this._laserPointer.material = laserPointerMaterial;
  104246. _this._laserPointer.rotation.x = Math.PI / 2;
  104247. _this._laserPointer.position.z = -0.5;
  104248. _this._laserPointer.isVisible = false;
  104249. _this._laserPointer.isPickable = false;
  104250. if (!webVRController.mesh) {
  104251. // Create an empty mesh that is used prior to loading the high quality model
  104252. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104253. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104254. preloadPointerPose.rotation.x = -0.7;
  104255. preloadMesh.addChild(preloadPointerPose);
  104256. webVRController.attachToMesh(preloadMesh);
  104257. }
  104258. _this._setLaserPointerParent(webVRController.mesh);
  104259. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104260. _this._setLaserPointerParent(mesh);
  104261. });
  104262. return _this;
  104263. }
  104264. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104265. return this.webVRController.getForwardRay(length);
  104266. };
  104267. /** @hidden */
  104268. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104269. _super.prototype._activatePointer.call(this);
  104270. this._laserPointer.isVisible = true;
  104271. };
  104272. /** @hidden */
  104273. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104274. _super.prototype._deactivatePointer.call(this);
  104275. this._laserPointer.isVisible = false;
  104276. };
  104277. /** @hidden */
  104278. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104279. this._laserPointer.material.emissiveColor = color;
  104280. };
  104281. /** @hidden */
  104282. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104283. var makeNotPick = function (root) {
  104284. root.isPickable = false;
  104285. root.getChildMeshes().forEach(function (c) {
  104286. makeNotPick(c);
  104287. });
  104288. };
  104289. makeNotPick(mesh);
  104290. var childMeshes = mesh.getChildMeshes();
  104291. this.webVRController._pointingPoseNode = null;
  104292. for (var i = 0; i < childMeshes.length; i++) {
  104293. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104294. mesh = childMeshes[i];
  104295. this.webVRController._pointingPoseNode = mesh;
  104296. break;
  104297. }
  104298. }
  104299. this._laserPointer.parent = mesh;
  104300. };
  104301. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104302. if (distance === void 0) { distance = 100; }
  104303. this._laserPointer.scaling.y = distance;
  104304. this._laserPointer.position.z = -distance / 2;
  104305. };
  104306. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104307. _super.prototype.dispose.call(this);
  104308. this._laserPointer.dispose();
  104309. if (this._meshAttachedObserver) {
  104310. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104311. }
  104312. };
  104313. return VRExperienceHelperControllerGazer;
  104314. }(VRExperienceHelperGazer));
  104315. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104316. __extends(VRExperienceHelperCameraGazer, _super);
  104317. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104318. var _this = _super.call(this, scene) || this;
  104319. _this.getCamera = getCamera;
  104320. return _this;
  104321. }
  104322. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104323. var camera = this.getCamera();
  104324. if (camera) {
  104325. return camera.getForwardRay(length);
  104326. }
  104327. else {
  104328. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104329. }
  104330. };
  104331. return VRExperienceHelperCameraGazer;
  104332. }(VRExperienceHelperGazer));
  104333. /**
  104334. * Helps to quickly add VR support to an existing scene.
  104335. * See http://doc.babylonjs.com/how_to/webvr_helper
  104336. */
  104337. var VRExperienceHelper = /** @class */ (function () {
  104338. /**
  104339. * Instantiates a VRExperienceHelper.
  104340. * Helps to quickly add VR support to an existing scene.
  104341. * @param scene The scene the VRExperienceHelper belongs to.
  104342. * @param webVROptions Options to modify the vr experience helper's behavior.
  104343. */
  104344. function VRExperienceHelper(scene,
  104345. /** Options to modify the vr experience helper's behavior. */
  104346. webVROptions) {
  104347. if (webVROptions === void 0) { webVROptions = {}; }
  104348. var _this = this;
  104349. this.webVROptions = webVROptions;
  104350. // Can the system support WebVR, even if a headset isn't plugged in?
  104351. this._webVRsupported = false;
  104352. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104353. this._webVRready = false;
  104354. // Are we waiting for the requestPresent callback to complete?
  104355. this._webVRrequesting = false;
  104356. // Are we presenting to the headset right now? (this is the vrDevice state)
  104357. this._webVRpresenting = false;
  104358. // Are we presenting in the fullscreen fallback?
  104359. this._fullscreenVRpresenting = false;
  104360. /**
  104361. * Observable raised when entering VR.
  104362. */
  104363. this.onEnteringVRObservable = new BABYLON.Observable();
  104364. /**
  104365. * Observable raised when exiting VR.
  104366. */
  104367. this.onExitingVRObservable = new BABYLON.Observable();
  104368. /**
  104369. * Observable raised when controller mesh is loaded.
  104370. */
  104371. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104372. this._useCustomVRButton = false;
  104373. this._teleportationRequested = false;
  104374. this._teleportActive = false;
  104375. this._floorMeshesCollection = [];
  104376. this._rotationAllowed = true;
  104377. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104378. this._isDefaultTeleportationTarget = true;
  104379. this._teleportationFillColor = "#444444";
  104380. this._teleportationBorderColor = "#FFFFFF";
  104381. this._rotationAngle = 0;
  104382. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104383. this._padSensibilityUp = 0.65;
  104384. this._padSensibilityDown = 0.35;
  104385. this._leftController = null;
  104386. this._rightController = null;
  104387. /**
  104388. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104389. */
  104390. this.onNewMeshSelected = new BABYLON.Observable();
  104391. /**
  104392. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104393. */
  104394. this.onNewMeshPicked = new BABYLON.Observable();
  104395. /**
  104396. * Observable raised before camera teleportation
  104397. */
  104398. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104399. /**
  104400. * Observable raised after camera teleportation
  104401. */
  104402. this.onAfterCameraTeleport = new BABYLON.Observable();
  104403. /**
  104404. * Observable raised when current selected mesh gets unselected
  104405. */
  104406. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104407. /**
  104408. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104409. */
  104410. this.teleportationEnabled = true;
  104411. this._teleportationInitialized = false;
  104412. this._interactionsEnabled = false;
  104413. this._interactionsRequested = false;
  104414. this._displayGaze = true;
  104415. this._displayLaserPointer = true;
  104416. /**
  104417. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104418. */
  104419. this.updateGazeTrackerScale = true;
  104420. this._onResize = function () {
  104421. _this.moveButtonToBottomRight();
  104422. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104423. _this.exitVR();
  104424. }
  104425. };
  104426. this._onFullscreenChange = function () {
  104427. if (document.fullscreen !== undefined) {
  104428. _this._fullscreenVRpresenting = document.fullscreen;
  104429. }
  104430. else if (document.mozFullScreen !== undefined) {
  104431. _this._fullscreenVRpresenting = document.mozFullScreen;
  104432. }
  104433. else if (document.webkitIsFullScreen !== undefined) {
  104434. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104435. }
  104436. else if (document.msIsFullScreen !== undefined) {
  104437. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104438. }
  104439. else if (document.msFullscreenElement !== undefined) {
  104440. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104441. }
  104442. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104443. _this.exitVR();
  104444. if (!_this._useCustomVRButton) {
  104445. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104446. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104447. }
  104448. }
  104449. };
  104450. this.beforeRender = function () {
  104451. if (_this._leftController && _this._leftController._activePointer) {
  104452. _this._castRayAndSelectObject(_this._leftController);
  104453. }
  104454. if (_this._rightController && _this._rightController._activePointer) {
  104455. _this._castRayAndSelectObject(_this._rightController);
  104456. }
  104457. if (_this._noControllerIsActive) {
  104458. _this._castRayAndSelectObject(_this._cameraGazer);
  104459. }
  104460. else {
  104461. _this._cameraGazer._gazeTracker.isVisible = false;
  104462. }
  104463. };
  104464. this._onNewGamepadConnected = function (gamepad) {
  104465. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104466. if (gamepad.leftStick) {
  104467. gamepad.onleftstickchanged(function (stickValues) {
  104468. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104469. // Listening to classic/xbox gamepad only if no VR controller is active
  104470. if ((!_this._leftController && !_this._rightController) ||
  104471. ((_this._leftController && !_this._leftController._activePointer) &&
  104472. (_this._rightController && !_this._rightController._activePointer))) {
  104473. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104474. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104475. }
  104476. }
  104477. });
  104478. }
  104479. if (gamepad.rightStick) {
  104480. gamepad.onrightstickchanged(function (stickValues) {
  104481. if (_this._teleportationInitialized) {
  104482. _this._checkRotate(stickValues, _this._cameraGazer);
  104483. }
  104484. });
  104485. }
  104486. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104487. gamepad.onbuttondown(function (buttonPressed) {
  104488. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104489. _this._cameraGazer._selectionPointerDown();
  104490. }
  104491. });
  104492. gamepad.onbuttonup(function (buttonPressed) {
  104493. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104494. _this._cameraGazer._selectionPointerUp();
  104495. }
  104496. });
  104497. }
  104498. }
  104499. else {
  104500. var webVRController = gamepad;
  104501. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104502. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104503. _this._rightController = controller;
  104504. }
  104505. else {
  104506. _this._leftController = controller;
  104507. }
  104508. _this._tryEnableInteractionOnController(controller);
  104509. }
  104510. };
  104511. // 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
  104512. this._tryEnableInteractionOnController = function (controller) {
  104513. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104514. _this._enableInteractionOnController(controller);
  104515. }
  104516. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104517. _this._enableTeleportationOnController(controller);
  104518. }
  104519. };
  104520. this._onNewGamepadDisconnected = function (gamepad) {
  104521. if (gamepad instanceof BABYLON.WebVRController) {
  104522. if (gamepad.hand === "left" && _this._leftController != null) {
  104523. _this._leftController.dispose();
  104524. _this._leftController = null;
  104525. }
  104526. if (gamepad.hand === "right" && _this._rightController != null) {
  104527. _this._rightController.dispose();
  104528. _this._rightController = null;
  104529. }
  104530. }
  104531. };
  104532. this._workingVector = BABYLON.Vector3.Zero();
  104533. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104534. this._workingMatrix = BABYLON.Matrix.Identity();
  104535. this._scene = scene;
  104536. this._canvas = scene.getEngine().getRenderingCanvas();
  104537. // Parse options
  104538. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104539. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104540. }
  104541. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104542. webVROptions.createDeviceOrientationCamera = true;
  104543. }
  104544. if (webVROptions.laserToggle === undefined) {
  104545. webVROptions.laserToggle = true;
  104546. }
  104547. if (webVROptions.defaultHeight === undefined) {
  104548. webVROptions.defaultHeight = 1.7;
  104549. }
  104550. if (webVROptions.useCustomVRButton) {
  104551. this._useCustomVRButton = true;
  104552. if (webVROptions.customVRButton) {
  104553. this._btnVR = webVROptions.customVRButton;
  104554. }
  104555. }
  104556. if (webVROptions.rayLength) {
  104557. this._rayLength = webVROptions.rayLength;
  104558. }
  104559. this._defaultHeight = webVROptions.defaultHeight;
  104560. if (webVROptions.positionScale) {
  104561. this._rayLength *= webVROptions.positionScale;
  104562. this._defaultHeight *= webVROptions.positionScale;
  104563. }
  104564. this._hasEnteredVR = false;
  104565. // Set position
  104566. if (this._scene.activeCamera) {
  104567. this._position = this._scene.activeCamera.position.clone();
  104568. }
  104569. else {
  104570. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104571. }
  104572. // Set non-vr camera
  104573. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104574. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104575. // Copy data from existing camera
  104576. if (this._scene.activeCamera) {
  104577. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104578. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104579. // Set rotation from previous camera
  104580. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  104581. var targetCamera = this._scene.activeCamera;
  104582. if (targetCamera.rotationQuaternion) {
  104583. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  104584. }
  104585. else {
  104586. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  104587. }
  104588. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  104589. }
  104590. }
  104591. this._scene.activeCamera = this._deviceOrientationCamera;
  104592. if (this._canvas) {
  104593. this._scene.activeCamera.attachControl(this._canvas);
  104594. }
  104595. }
  104596. else {
  104597. this._existingCamera = this._scene.activeCamera;
  104598. }
  104599. // Create VR cameras
  104600. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104601. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  104602. }
  104603. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  104604. this._webVRCamera.useStandingMatrix();
  104605. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  104606. // Create default button
  104607. if (!this._useCustomVRButton) {
  104608. this._btnVR = document.createElement("BUTTON");
  104609. this._btnVR.className = "babylonVRicon";
  104610. this._btnVR.id = "babylonVRiconbtn";
  104611. this._btnVR.title = "Click to switch to VR";
  104612. 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) }";
  104613. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  104614. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  104615. // css += ".babylonVRicon.vrdisplaysupported { }";
  104616. // css += ".babylonVRicon.vrdisplayready { }";
  104617. // css += ".babylonVRicon.vrdisplayrequesting { }";
  104618. var style = document.createElement('style');
  104619. style.appendChild(document.createTextNode(css));
  104620. document.getElementsByTagName('head')[0].appendChild(style);
  104621. this.moveButtonToBottomRight();
  104622. }
  104623. // VR button click event
  104624. if (this._btnVR) {
  104625. this._btnVR.addEventListener("click", function () {
  104626. if (!_this.isInVRMode) {
  104627. _this.enterVR();
  104628. }
  104629. else {
  104630. _this.exitVR();
  104631. }
  104632. });
  104633. }
  104634. // Window events
  104635. window.addEventListener("resize", this._onResize);
  104636. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  104637. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  104638. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  104639. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  104640. document.onmsfullscreenchange = this._onFullscreenChange;
  104641. // Display vr button when headset is connected
  104642. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104643. this.displayVRButton();
  104644. }
  104645. else {
  104646. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  104647. if (e.vrDisplay) {
  104648. _this.displayVRButton();
  104649. }
  104650. });
  104651. }
  104652. // Exiting VR mode using 'ESC' key on desktop
  104653. this._onKeyDown = function (event) {
  104654. if (event.keyCode === 27 && _this.isInVRMode) {
  104655. _this.exitVR();
  104656. }
  104657. };
  104658. document.addEventListener("keydown", this._onKeyDown);
  104659. // Exiting VR mode double tapping the touch screen
  104660. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  104661. if (_this.isInVRMode) {
  104662. _this.exitVR();
  104663. if (_this._fullscreenVRpresenting) {
  104664. _this._scene.getEngine().switchFullscreen(true);
  104665. }
  104666. }
  104667. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  104668. // Listen for WebVR display changes
  104669. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  104670. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  104671. this._onVRRequestPresentStart = function () {
  104672. _this._webVRrequesting = true;
  104673. _this.updateButtonVisibility();
  104674. };
  104675. this._onVRRequestPresentComplete = function (success) {
  104676. _this._webVRrequesting = false;
  104677. _this.updateButtonVisibility();
  104678. };
  104679. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  104680. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  104681. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  104682. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104683. scene.onDisposeObservable.add(function () {
  104684. _this.dispose();
  104685. });
  104686. // Gamepad connection events
  104687. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  104688. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  104689. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  104690. this.updateButtonVisibility();
  104691. //create easing functions
  104692. this._circleEase = new BABYLON.CircleEase();
  104693. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104694. if (this.webVROptions.floorMeshes) {
  104695. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  104696. }
  104697. }
  104698. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  104699. /** Return this.onEnteringVRObservable
  104700. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  104701. */
  104702. get: function () {
  104703. return this.onEnteringVRObservable;
  104704. },
  104705. enumerable: true,
  104706. configurable: true
  104707. });
  104708. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  104709. /** Return this.onExitingVRObservable
  104710. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  104711. */
  104712. get: function () {
  104713. return this.onExitingVRObservable;
  104714. },
  104715. enumerable: true,
  104716. configurable: true
  104717. });
  104718. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  104719. /** Return this.onControllerMeshLoadedObservable
  104720. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  104721. */
  104722. get: function () {
  104723. return this.onControllerMeshLoadedObservable;
  104724. },
  104725. enumerable: true,
  104726. configurable: true
  104727. });
  104728. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  104729. /**
  104730. * The mesh used to display where the user is going to teleport.
  104731. */
  104732. get: function () {
  104733. return this._teleportationTarget;
  104734. },
  104735. /**
  104736. * Sets the mesh to be used to display where the user is going to teleport.
  104737. */
  104738. set: function (value) {
  104739. if (value) {
  104740. value.name = "teleportationTarget";
  104741. this._isDefaultTeleportationTarget = false;
  104742. this._teleportationTarget = value;
  104743. }
  104744. },
  104745. enumerable: true,
  104746. configurable: true
  104747. });
  104748. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  104749. /**
  104750. * 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
  104751. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  104752. * See http://doc.babylonjs.com/resources/baking_transformations
  104753. */
  104754. get: function () {
  104755. return this._cameraGazer._gazeTracker;
  104756. },
  104757. set: function (value) {
  104758. if (value) {
  104759. // Dispose of existing meshes
  104760. if (this._cameraGazer._gazeTracker) {
  104761. this._cameraGazer._gazeTracker.dispose();
  104762. }
  104763. if (this._leftController && this._leftController._gazeTracker) {
  104764. this._leftController._gazeTracker.dispose();
  104765. }
  104766. if (this._rightController && this._rightController._gazeTracker) {
  104767. this._rightController._gazeTracker.dispose();
  104768. }
  104769. // Set and create gaze trackers on head and controllers
  104770. this._cameraGazer._gazeTracker = value;
  104771. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  104772. this._cameraGazer._gazeTracker.isPickable = false;
  104773. this._cameraGazer._gazeTracker.isVisible = false;
  104774. this._cameraGazer._gazeTracker.name = "gazeTracker";
  104775. if (this._leftController) {
  104776. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  104777. }
  104778. if (this._rightController) {
  104779. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  104780. }
  104781. }
  104782. },
  104783. enumerable: true,
  104784. configurable: true
  104785. });
  104786. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  104787. /**
  104788. * The gaze tracking mesh corresponding to the left controller
  104789. */
  104790. get: function () {
  104791. if (this._leftController) {
  104792. return this._leftController._gazeTracker;
  104793. }
  104794. return null;
  104795. },
  104796. enumerable: true,
  104797. configurable: true
  104798. });
  104799. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  104800. /**
  104801. * The gaze tracking mesh corresponding to the right controller
  104802. */
  104803. get: function () {
  104804. if (this._rightController) {
  104805. return this._rightController._gazeTracker;
  104806. }
  104807. return null;
  104808. },
  104809. enumerable: true,
  104810. configurable: true
  104811. });
  104812. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  104813. /**
  104814. * If the ray of the gaze should be displayed.
  104815. */
  104816. get: function () {
  104817. return this._displayGaze;
  104818. },
  104819. /**
  104820. * Sets if the ray of the gaze should be displayed.
  104821. */
  104822. set: function (value) {
  104823. this._displayGaze = value;
  104824. if (!value) {
  104825. this._cameraGazer._gazeTracker.isVisible = false;
  104826. if (this._leftController) {
  104827. this._leftController._gazeTracker.isVisible = false;
  104828. }
  104829. if (this._rightController) {
  104830. this._rightController._gazeTracker.isVisible = false;
  104831. }
  104832. }
  104833. },
  104834. enumerable: true,
  104835. configurable: true
  104836. });
  104837. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  104838. /**
  104839. * If the ray of the LaserPointer should be displayed.
  104840. */
  104841. get: function () {
  104842. return this._displayLaserPointer;
  104843. },
  104844. /**
  104845. * Sets if the ray of the LaserPointer should be displayed.
  104846. */
  104847. set: function (value) {
  104848. this._displayLaserPointer = value;
  104849. if (!value) {
  104850. if (this._rightController) {
  104851. this._rightController._deactivatePointer();
  104852. this._rightController._gazeTracker.isVisible = false;
  104853. }
  104854. if (this._leftController) {
  104855. this._leftController._deactivatePointer();
  104856. this._leftController._gazeTracker.isVisible = false;
  104857. }
  104858. }
  104859. else {
  104860. if (this._rightController) {
  104861. this._rightController._activatePointer();
  104862. }
  104863. if (this._leftController) {
  104864. this._leftController._activatePointer();
  104865. }
  104866. }
  104867. },
  104868. enumerable: true,
  104869. configurable: true
  104870. });
  104871. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  104872. /**
  104873. * The deviceOrientationCamera used as the camera when not in VR.
  104874. */
  104875. get: function () {
  104876. return this._deviceOrientationCamera;
  104877. },
  104878. enumerable: true,
  104879. configurable: true
  104880. });
  104881. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  104882. /**
  104883. * Based on the current WebVR support, returns the current VR camera used.
  104884. */
  104885. get: function () {
  104886. if (this._webVRready) {
  104887. return this._webVRCamera;
  104888. }
  104889. else {
  104890. return this._scene.activeCamera;
  104891. }
  104892. },
  104893. enumerable: true,
  104894. configurable: true
  104895. });
  104896. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  104897. /**
  104898. * The webVRCamera which is used when in VR.
  104899. */
  104900. get: function () {
  104901. return this._webVRCamera;
  104902. },
  104903. enumerable: true,
  104904. configurable: true
  104905. });
  104906. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  104907. /**
  104908. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  104909. */
  104910. get: function () {
  104911. return this._vrDeviceOrientationCamera;
  104912. },
  104913. enumerable: true,
  104914. configurable: true
  104915. });
  104916. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  104917. get: function () {
  104918. var result = this._cameraGazer._teleportationRequestInitiated
  104919. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  104920. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  104921. return result;
  104922. },
  104923. enumerable: true,
  104924. configurable: true
  104925. });
  104926. // Raised when one of the controller has loaded successfully its associated default mesh
  104927. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  104928. if (this._leftController && this._leftController.webVRController == webVRController) {
  104929. if (webVRController.mesh) {
  104930. this._leftController._setLaserPointerParent(webVRController.mesh);
  104931. }
  104932. }
  104933. if (this._rightController && this._rightController.webVRController == webVRController) {
  104934. if (webVRController.mesh) {
  104935. this._rightController._setLaserPointerParent(webVRController.mesh);
  104936. }
  104937. }
  104938. try {
  104939. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  104940. }
  104941. catch (err) {
  104942. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  104943. }
  104944. };
  104945. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  104946. /**
  104947. * Gets a value indicating if we are currently in VR mode.
  104948. */
  104949. get: function () {
  104950. return this._webVRpresenting || this._fullscreenVRpresenting;
  104951. },
  104952. enumerable: true,
  104953. configurable: true
  104954. });
  104955. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  104956. var vrDisplay = this._scene.getEngine().getVRDevice();
  104957. if (vrDisplay) {
  104958. var wasPresenting = this._webVRpresenting;
  104959. this._webVRpresenting = vrDisplay.isPresenting;
  104960. if (wasPresenting && !this._webVRpresenting)
  104961. this.exitVR();
  104962. }
  104963. else {
  104964. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  104965. }
  104966. this.updateButtonVisibility();
  104967. };
  104968. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  104969. this._webVRsupported = eventArgs.vrSupported;
  104970. this._webVRready = !!eventArgs.vrDisplay;
  104971. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  104972. this.updateButtonVisibility();
  104973. };
  104974. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  104975. if (this._canvas && !this._useCustomVRButton) {
  104976. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  104977. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  104978. }
  104979. };
  104980. VRExperienceHelper.prototype.displayVRButton = function () {
  104981. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  104982. document.body.appendChild(this._btnVR);
  104983. this._btnVRDisplayed = true;
  104984. }
  104985. };
  104986. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  104987. if (!this._btnVR || this._useCustomVRButton) {
  104988. return;
  104989. }
  104990. this._btnVR.className = "babylonVRicon";
  104991. if (this.isInVRMode) {
  104992. this._btnVR.className += " vrdisplaypresenting";
  104993. }
  104994. else {
  104995. if (this._webVRready)
  104996. this._btnVR.className += " vrdisplayready";
  104997. if (this._webVRsupported)
  104998. this._btnVR.className += " vrdisplaysupported";
  104999. if (this._webVRrequesting)
  105000. this._btnVR.className += " vrdisplayrequesting";
  105001. }
  105002. };
  105003. /**
  105004. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  105005. * Otherwise, will use the fullscreen API.
  105006. */
  105007. VRExperienceHelper.prototype.enterVR = function () {
  105008. if (this.onEnteringVRObservable) {
  105009. try {
  105010. this.onEnteringVRObservable.notifyObservers(this);
  105011. }
  105012. catch (err) {
  105013. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  105014. }
  105015. }
  105016. if (this._scene.activeCamera) {
  105017. this._position = this._scene.activeCamera.position.clone();
  105018. // make sure that we return to the last active camera
  105019. this._existingCamera = this._scene.activeCamera;
  105020. }
  105021. if (this._webVRrequesting)
  105022. return;
  105023. // If WebVR is supported and a headset is connected
  105024. if (this._webVRready) {
  105025. if (!this._webVRpresenting) {
  105026. this._webVRCamera.position = this._position;
  105027. this._scene.activeCamera = this._webVRCamera;
  105028. }
  105029. }
  105030. else if (this._vrDeviceOrientationCamera) {
  105031. this._vrDeviceOrientationCamera.position = this._position;
  105032. if (this._scene.activeCamera) {
  105033. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105034. }
  105035. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105036. this._scene.getEngine().switchFullscreen(true);
  105037. this.updateButtonVisibility();
  105038. }
  105039. if (this._scene.activeCamera && this._canvas) {
  105040. this._scene.activeCamera.attachControl(this._canvas);
  105041. }
  105042. if (this._interactionsEnabled) {
  105043. this._scene.registerBeforeRender(this.beforeRender);
  105044. }
  105045. this._hasEnteredVR = true;
  105046. };
  105047. /**
  105048. * Attempt to exit VR, or fullscreen.
  105049. */
  105050. VRExperienceHelper.prototype.exitVR = function () {
  105051. if (this._hasEnteredVR) {
  105052. if (this.onExitingVRObservable) {
  105053. try {
  105054. this.onExitingVRObservable.notifyObservers(this);
  105055. }
  105056. catch (err) {
  105057. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105058. }
  105059. }
  105060. if (this._webVRpresenting) {
  105061. this._scene.getEngine().disableVR();
  105062. }
  105063. if (this._scene.activeCamera) {
  105064. this._position = this._scene.activeCamera.position.clone();
  105065. }
  105066. if (this._deviceOrientationCamera) {
  105067. this._deviceOrientationCamera.position = this._position;
  105068. this._scene.activeCamera = this._deviceOrientationCamera;
  105069. if (this._canvas) {
  105070. this._scene.activeCamera.attachControl(this._canvas);
  105071. }
  105072. }
  105073. else if (this._existingCamera) {
  105074. this._existingCamera.position = this._position;
  105075. this._scene.activeCamera = this._existingCamera;
  105076. }
  105077. this.updateButtonVisibility();
  105078. if (this._interactionsEnabled) {
  105079. this._scene.unregisterBeforeRender(this.beforeRender);
  105080. this._cameraGazer._gazeTracker.isVisible = false;
  105081. if (this._leftController) {
  105082. this._leftController._gazeTracker.isVisible = false;
  105083. }
  105084. if (this._rightController) {
  105085. this._rightController._gazeTracker.isVisible = false;
  105086. }
  105087. }
  105088. // resize to update width and height when exiting vr exits fullscreen
  105089. this._scene.getEngine().resize();
  105090. this._hasEnteredVR = false;
  105091. }
  105092. };
  105093. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105094. /**
  105095. * The position of the vr experience helper.
  105096. */
  105097. get: function () {
  105098. return this._position;
  105099. },
  105100. /**
  105101. * Sets the position of the vr experience helper.
  105102. */
  105103. set: function (value) {
  105104. this._position = value;
  105105. if (this._scene.activeCamera) {
  105106. this._scene.activeCamera.position = value;
  105107. }
  105108. },
  105109. enumerable: true,
  105110. configurable: true
  105111. });
  105112. /**
  105113. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105114. */
  105115. VRExperienceHelper.prototype.enableInteractions = function () {
  105116. var _this = this;
  105117. if (!this._interactionsEnabled) {
  105118. this._interactionsRequested = true;
  105119. if (this._leftController) {
  105120. this._enableInteractionOnController(this._leftController);
  105121. }
  105122. if (this._rightController) {
  105123. this._enableInteractionOnController(this._rightController);
  105124. }
  105125. this.raySelectionPredicate = function (mesh) {
  105126. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105127. };
  105128. this.meshSelectionPredicate = function (mesh) {
  105129. return true;
  105130. };
  105131. this._raySelectionPredicate = function (mesh) {
  105132. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105133. && mesh.name.indexOf("teleportationTarget") === -1
  105134. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105135. return _this.raySelectionPredicate(mesh);
  105136. }
  105137. return false;
  105138. };
  105139. this._interactionsEnabled = true;
  105140. }
  105141. };
  105142. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105143. get: function () {
  105144. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105145. },
  105146. enumerable: true,
  105147. configurable: true
  105148. });
  105149. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105150. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105151. if (this._floorMeshesCollection[i].id === mesh.id) {
  105152. return true;
  105153. }
  105154. }
  105155. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105156. return true;
  105157. }
  105158. return false;
  105159. };
  105160. /**
  105161. * Adds a floor mesh to be used for teleportation.
  105162. * @param floorMesh the mesh to be used for teleportation.
  105163. */
  105164. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105165. if (!this._floorMeshesCollection) {
  105166. return;
  105167. }
  105168. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105169. return;
  105170. }
  105171. this._floorMeshesCollection.push(floorMesh);
  105172. };
  105173. /**
  105174. * Removes a floor mesh from being used for teleportation.
  105175. * @param floorMesh the mesh to be removed.
  105176. */
  105177. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105178. if (!this._floorMeshesCollection) {
  105179. return;
  105180. }
  105181. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105182. if (meshIndex !== -1) {
  105183. this._floorMeshesCollection.splice(meshIndex, 1);
  105184. }
  105185. };
  105186. /**
  105187. * Enables interactions and teleportation using the VR controllers and gaze.
  105188. * @param vrTeleportationOptions options to modify teleportation behavior.
  105189. */
  105190. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105191. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105192. if (!this._teleportationInitialized) {
  105193. this._teleportationRequested = true;
  105194. this.enableInteractions();
  105195. if (vrTeleportationOptions.floorMeshName) {
  105196. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105197. }
  105198. if (vrTeleportationOptions.floorMeshes) {
  105199. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105200. }
  105201. if (this._leftController != null) {
  105202. this._enableTeleportationOnController(this._leftController);
  105203. }
  105204. if (this._rightController != null) {
  105205. this._enableTeleportationOnController(this._rightController);
  105206. }
  105207. // Creates an image processing post process for the vignette not relying
  105208. // on the main scene configuration for image processing to reduce setup and spaces
  105209. // (gamma/linear) conflicts.
  105210. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105211. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105212. imageProcessingConfiguration.vignetteEnabled = true;
  105213. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105214. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105215. this._teleportationInitialized = true;
  105216. if (this._isDefaultTeleportationTarget) {
  105217. this._createTeleportationCircles();
  105218. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105219. }
  105220. }
  105221. };
  105222. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105223. var _this = this;
  105224. var controllerMesh = controller.webVRController.mesh;
  105225. if (controllerMesh) {
  105226. controller._interactionsEnabled = true;
  105227. controller._activatePointer();
  105228. if (this.webVROptions.laserToggle) {
  105229. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105230. // Enabling / disabling laserPointer
  105231. if (_this._displayLaserPointer && stateObject.value === 1) {
  105232. if (controller._activePointer) {
  105233. controller._deactivatePointer();
  105234. }
  105235. else {
  105236. controller._activatePointer();
  105237. }
  105238. if (_this.displayGaze) {
  105239. controller._gazeTracker.isVisible = controller._activePointer;
  105240. }
  105241. }
  105242. });
  105243. }
  105244. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105245. var gazer = controller;
  105246. if (_this._noControllerIsActive) {
  105247. gazer = _this._cameraGazer;
  105248. }
  105249. if (!gazer._pointerDownOnMeshAsked) {
  105250. if (stateObject.value > _this._padSensibilityUp) {
  105251. gazer._selectionPointerDown();
  105252. }
  105253. }
  105254. else if (stateObject.value < _this._padSensibilityDown) {
  105255. gazer._selectionPointerUp();
  105256. }
  105257. });
  105258. }
  105259. };
  105260. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105261. // Dont teleport if another gaze already requested teleportation
  105262. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105263. return;
  105264. }
  105265. if (!gazer._teleportationRequestInitiated) {
  105266. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105267. gazer._activatePointer();
  105268. gazer._teleportationRequestInitiated = true;
  105269. }
  105270. }
  105271. else {
  105272. // Listening to the proper controller values changes to confirm teleportation
  105273. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105274. if (this._teleportActive) {
  105275. this.teleportCamera(this._haloCenter);
  105276. }
  105277. gazer._teleportationRequestInitiated = false;
  105278. }
  105279. }
  105280. };
  105281. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105282. // Only rotate when user is not currently selecting a teleportation location
  105283. if (gazer._teleportationRequestInitiated) {
  105284. return;
  105285. }
  105286. if (!gazer._rotationLeftAsked) {
  105287. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105288. gazer._rotationLeftAsked = true;
  105289. if (this._rotationAllowed) {
  105290. this._rotateCamera(false);
  105291. }
  105292. }
  105293. }
  105294. else {
  105295. if (stateObject.x > -this._padSensibilityDown) {
  105296. gazer._rotationLeftAsked = false;
  105297. }
  105298. }
  105299. if (!gazer._rotationRightAsked) {
  105300. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105301. gazer._rotationRightAsked = true;
  105302. if (this._rotationAllowed) {
  105303. this._rotateCamera(true);
  105304. }
  105305. }
  105306. }
  105307. else {
  105308. if (stateObject.x < this._padSensibilityDown) {
  105309. gazer._rotationRightAsked = false;
  105310. }
  105311. }
  105312. };
  105313. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105314. // Only teleport backwards when user is not currently selecting a teleportation location
  105315. if (gazer._teleportationRequestInitiated) {
  105316. return;
  105317. }
  105318. // Teleport backwards
  105319. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105320. if (!gazer._teleportationBackRequestInitiated) {
  105321. if (!this.currentVRCamera) {
  105322. return;
  105323. }
  105324. // Get rotation and position of the current camera
  105325. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105326. var position = this.currentVRCamera.position;
  105327. // If the camera has device position, use that instead
  105328. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105329. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105330. position = this.currentVRCamera.devicePosition;
  105331. }
  105332. // Get matrix with only the y rotation of the device rotation
  105333. rotation.toEulerAnglesToRef(this._workingVector);
  105334. this._workingVector.z = 0;
  105335. this._workingVector.x = 0;
  105336. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105337. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105338. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105339. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105340. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105341. var ray = new BABYLON.Ray(position, this._workingVector);
  105342. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105343. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105344. this.teleportCamera(hit.pickedPoint);
  105345. }
  105346. gazer._teleportationBackRequestInitiated = true;
  105347. }
  105348. }
  105349. else {
  105350. gazer._teleportationBackRequestInitiated = false;
  105351. }
  105352. };
  105353. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105354. var _this = this;
  105355. var controllerMesh = controller.webVRController.mesh;
  105356. if (controllerMesh) {
  105357. if (!controller._interactionsEnabled) {
  105358. this._enableInteractionOnController(controller);
  105359. }
  105360. controller._interactionsEnabled = true;
  105361. controller._teleportationEnabled = true;
  105362. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105363. controller._dpadPressed = false;
  105364. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105365. controller._dpadPressed = stateObject.pressed;
  105366. if (!controller._dpadPressed) {
  105367. controller._rotationLeftAsked = false;
  105368. controller._rotationRightAsked = false;
  105369. controller._teleportationBackRequestInitiated = false;
  105370. }
  105371. });
  105372. }
  105373. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105374. if (_this.teleportationEnabled) {
  105375. _this._checkTeleportBackwards(stateObject, controller);
  105376. _this._checkTeleportWithRay(stateObject, controller);
  105377. }
  105378. _this._checkRotate(stateObject, controller);
  105379. });
  105380. }
  105381. };
  105382. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105383. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105384. this._teleportationTarget.isPickable = false;
  105385. var length = 512;
  105386. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105387. dynamicTexture.hasAlpha = true;
  105388. var context = dynamicTexture.getContext();
  105389. var centerX = length / 2;
  105390. var centerY = length / 2;
  105391. var radius = 200;
  105392. context.beginPath();
  105393. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105394. context.fillStyle = this._teleportationFillColor;
  105395. context.fill();
  105396. context.lineWidth = 10;
  105397. context.strokeStyle = this._teleportationBorderColor;
  105398. context.stroke();
  105399. context.closePath();
  105400. dynamicTexture.update();
  105401. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105402. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105403. this._teleportationTarget.material = teleportationCircleMaterial;
  105404. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105405. torus.isPickable = false;
  105406. torus.parent = this._teleportationTarget;
  105407. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105408. var keys = [];
  105409. keys.push({
  105410. frame: 0,
  105411. value: 0
  105412. });
  105413. keys.push({
  105414. frame: 30,
  105415. value: 0.4
  105416. });
  105417. keys.push({
  105418. frame: 60,
  105419. value: 0
  105420. });
  105421. animationInnerCircle.setKeys(keys);
  105422. var easingFunction = new BABYLON.SineEase();
  105423. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105424. animationInnerCircle.setEasingFunction(easingFunction);
  105425. torus.animations = [];
  105426. torus.animations.push(animationInnerCircle);
  105427. this._scene.beginAnimation(torus, 0, 60, true);
  105428. this._hideTeleportationTarget();
  105429. };
  105430. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105431. this._teleportActive = true;
  105432. if (this._teleportationInitialized) {
  105433. this._teleportationTarget.isVisible = true;
  105434. if (this._isDefaultTeleportationTarget) {
  105435. this._teleportationTarget.getChildren()[0].isVisible = true;
  105436. }
  105437. }
  105438. };
  105439. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105440. this._teleportActive = false;
  105441. if (this._teleportationInitialized) {
  105442. this._teleportationTarget.isVisible = false;
  105443. if (this._isDefaultTeleportationTarget) {
  105444. this._teleportationTarget.getChildren()[0].isVisible = false;
  105445. }
  105446. }
  105447. };
  105448. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105449. var _this = this;
  105450. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105451. return;
  105452. }
  105453. if (right) {
  105454. this._rotationAngle++;
  105455. }
  105456. else {
  105457. this._rotationAngle--;
  105458. }
  105459. this.currentVRCamera.animations = [];
  105460. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105461. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105462. var animationRotationKeys = [];
  105463. animationRotationKeys.push({
  105464. frame: 0,
  105465. value: this.currentVRCamera.rotationQuaternion
  105466. });
  105467. animationRotationKeys.push({
  105468. frame: 6,
  105469. value: target
  105470. });
  105471. animationRotation.setKeys(animationRotationKeys);
  105472. animationRotation.setEasingFunction(this._circleEase);
  105473. this.currentVRCamera.animations.push(animationRotation);
  105474. this._postProcessMove.animations = [];
  105475. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105476. var vignetteWeightKeys = [];
  105477. vignetteWeightKeys.push({
  105478. frame: 0,
  105479. value: 0
  105480. });
  105481. vignetteWeightKeys.push({
  105482. frame: 3,
  105483. value: 4
  105484. });
  105485. vignetteWeightKeys.push({
  105486. frame: 6,
  105487. value: 0
  105488. });
  105489. animationPP.setKeys(vignetteWeightKeys);
  105490. animationPP.setEasingFunction(this._circleEase);
  105491. this._postProcessMove.animations.push(animationPP);
  105492. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105493. var vignetteStretchKeys = [];
  105494. vignetteStretchKeys.push({
  105495. frame: 0,
  105496. value: 0
  105497. });
  105498. vignetteStretchKeys.push({
  105499. frame: 3,
  105500. value: 10
  105501. });
  105502. vignetteStretchKeys.push({
  105503. frame: 6,
  105504. value: 0
  105505. });
  105506. animationPP2.setKeys(vignetteStretchKeys);
  105507. animationPP2.setEasingFunction(this._circleEase);
  105508. this._postProcessMove.animations.push(animationPP2);
  105509. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105510. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105511. this._postProcessMove.samples = 4;
  105512. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105513. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105514. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105515. });
  105516. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105517. };
  105518. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105519. if (hit.pickedPoint) {
  105520. if (gazer._teleportationRequestInitiated) {
  105521. this._displayTeleportationTarget();
  105522. this._haloCenter.copyFrom(hit.pickedPoint);
  105523. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105524. }
  105525. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105526. if (pickNormal) {
  105527. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105528. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105529. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105530. }
  105531. this._teleportationTarget.position.y += 0.1;
  105532. }
  105533. };
  105534. /**
  105535. * Teleports the users feet to the desired location
  105536. * @param location The location where the user's feet should be placed
  105537. */
  105538. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105539. var _this = this;
  105540. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105541. return;
  105542. }
  105543. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105544. // offset of the headset from the anchor.
  105545. if (this.webVRCamera.leftCamera) {
  105546. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105547. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105548. location.subtractToRef(this._workingVector, this._workingVector);
  105549. }
  105550. else {
  105551. this._workingVector.copyFrom(location);
  105552. }
  105553. // Add height to account for user's height offset
  105554. if (this.isInVRMode) {
  105555. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105556. }
  105557. else {
  105558. this._workingVector.y += this._defaultHeight;
  105559. }
  105560. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105561. // Create animation from the camera's position to the new location
  105562. this.currentVRCamera.animations = [];
  105563. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105564. var animationCameraTeleportationKeys = [{
  105565. frame: 0,
  105566. value: this.currentVRCamera.position
  105567. },
  105568. {
  105569. frame: 11,
  105570. value: this._workingVector
  105571. }
  105572. ];
  105573. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105574. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105575. this.currentVRCamera.animations.push(animationCameraTeleportation);
  105576. this._postProcessMove.animations = [];
  105577. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105578. var vignetteWeightKeys = [];
  105579. vignetteWeightKeys.push({
  105580. frame: 0,
  105581. value: 0
  105582. });
  105583. vignetteWeightKeys.push({
  105584. frame: 5,
  105585. value: 8
  105586. });
  105587. vignetteWeightKeys.push({
  105588. frame: 11,
  105589. value: 0
  105590. });
  105591. animationPP.setKeys(vignetteWeightKeys);
  105592. this._postProcessMove.animations.push(animationPP);
  105593. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105594. var vignetteStretchKeys = [];
  105595. vignetteStretchKeys.push({
  105596. frame: 0,
  105597. value: 0
  105598. });
  105599. vignetteStretchKeys.push({
  105600. frame: 5,
  105601. value: 10
  105602. });
  105603. vignetteStretchKeys.push({
  105604. frame: 11,
  105605. value: 0
  105606. });
  105607. animationPP2.setKeys(vignetteStretchKeys);
  105608. this._postProcessMove.animations.push(animationPP2);
  105609. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105610. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105611. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105612. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  105613. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105614. });
  105615. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  105616. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  105617. });
  105618. this._hideTeleportationTarget();
  105619. };
  105620. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  105621. if (normal) {
  105622. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  105623. if (angle < Math.PI / 2) {
  105624. normal.scaleInPlace(-1);
  105625. }
  105626. }
  105627. return normal;
  105628. };
  105629. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  105630. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105631. return;
  105632. }
  105633. var ray = gazer._getForwardRay(this._rayLength);
  105634. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105635. if (hit) {
  105636. // Populate the contrllers mesh that can be used for drag/drop
  105637. if (gazer._laserPointer) {
  105638. hit.originMesh = gazer._laserPointer.parent;
  105639. }
  105640. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  105641. }
  105642. gazer._currentHit = hit;
  105643. // Moving the gazeTracker on the mesh face targetted
  105644. if (hit && hit.pickedPoint) {
  105645. if (this._displayGaze) {
  105646. var multiplier = 1;
  105647. gazer._gazeTracker.isVisible = true;
  105648. if (gazer._isActionableMesh) {
  105649. multiplier = 3;
  105650. }
  105651. if (this.updateGazeTrackerScale) {
  105652. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  105653. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  105654. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  105655. }
  105656. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  105657. // To avoid z-fighting
  105658. var deltaFighting = 0.002;
  105659. if (pickNormal) {
  105660. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105661. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105662. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  105663. }
  105664. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  105665. if (gazer._gazeTracker.position.x < 0) {
  105666. gazer._gazeTracker.position.x += deltaFighting;
  105667. }
  105668. else {
  105669. gazer._gazeTracker.position.x -= deltaFighting;
  105670. }
  105671. if (gazer._gazeTracker.position.y < 0) {
  105672. gazer._gazeTracker.position.y += deltaFighting;
  105673. }
  105674. else {
  105675. gazer._gazeTracker.position.y -= deltaFighting;
  105676. }
  105677. if (gazer._gazeTracker.position.z < 0) {
  105678. gazer._gazeTracker.position.z += deltaFighting;
  105679. }
  105680. else {
  105681. gazer._gazeTracker.position.z -= deltaFighting;
  105682. }
  105683. }
  105684. // Changing the size of the laser pointer based on the distance from the targetted point
  105685. gazer._updatePointerDistance(hit.distance);
  105686. }
  105687. else {
  105688. gazer._updatePointerDistance();
  105689. gazer._gazeTracker.isVisible = false;
  105690. }
  105691. if (hit && hit.pickedMesh) {
  105692. // The object selected is the floor, we're in a teleportation scenario
  105693. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  105694. // Moving the teleportation area to this targetted point
  105695. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  105696. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  105697. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105698. }
  105699. gazer._currentMeshSelected = null;
  105700. if (gazer._teleportationRequestInitiated) {
  105701. this._moveTeleportationSelectorTo(hit, gazer, ray);
  105702. }
  105703. return;
  105704. }
  105705. // If not, we're in a selection scenario
  105706. //this._teleportationAllowed = false;
  105707. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  105708. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  105709. this.onNewMeshPicked.notifyObservers(hit);
  105710. gazer._currentMeshSelected = hit.pickedMesh;
  105711. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  105712. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  105713. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  105714. gazer._isActionableMesh = true;
  105715. }
  105716. else {
  105717. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105718. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105719. gazer._isActionableMesh = false;
  105720. }
  105721. try {
  105722. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  105723. }
  105724. catch (err) {
  105725. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  105726. }
  105727. }
  105728. else {
  105729. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105730. gazer._currentMeshSelected = null;
  105731. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105732. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105733. }
  105734. }
  105735. }
  105736. else {
  105737. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105738. gazer._currentMeshSelected = null;
  105739. //this._teleportationAllowed = false;
  105740. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105741. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105742. }
  105743. };
  105744. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  105745. if (mesh) {
  105746. this.onSelectedMeshUnselected.notifyObservers(mesh);
  105747. }
  105748. };
  105749. /**
  105750. * Sets the color of the laser ray from the vr controllers.
  105751. * @param color new color for the ray.
  105752. */
  105753. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  105754. if (this._leftController) {
  105755. this._leftController._setLaserPointerColor(color);
  105756. }
  105757. if (this._rightController) {
  105758. this._rightController._setLaserPointerColor(color);
  105759. }
  105760. };
  105761. /**
  105762. * Sets the color of the ray from the vr headsets gaze.
  105763. * @param color new color for the ray.
  105764. */
  105765. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  105766. if (!this._cameraGazer._gazeTracker.material) {
  105767. return;
  105768. }
  105769. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  105770. if (this._leftController) {
  105771. this._leftController._gazeTracker.material.emissiveColor = color;
  105772. }
  105773. if (this._rightController) {
  105774. this._rightController._gazeTracker.material.emissiveColor = color;
  105775. }
  105776. };
  105777. /**
  105778. * Exits VR and disposes of the vr experience helper
  105779. */
  105780. VRExperienceHelper.prototype.dispose = function () {
  105781. if (this.isInVRMode) {
  105782. this.exitVR();
  105783. }
  105784. if (this._postProcessMove) {
  105785. this._postProcessMove.dispose();
  105786. }
  105787. if (this._webVRCamera) {
  105788. this._webVRCamera.dispose();
  105789. }
  105790. if (this._vrDeviceOrientationCamera) {
  105791. this._vrDeviceOrientationCamera.dispose();
  105792. }
  105793. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  105794. document.body.removeChild(this._btnVR);
  105795. }
  105796. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  105797. this._deviceOrientationCamera.dispose();
  105798. }
  105799. if (this._cameraGazer) {
  105800. this._cameraGazer.dispose();
  105801. }
  105802. if (this._leftController) {
  105803. this._leftController.dispose();
  105804. }
  105805. if (this._rightController) {
  105806. this._rightController.dispose();
  105807. }
  105808. if (this._teleportationTarget) {
  105809. this._teleportationTarget.dispose();
  105810. }
  105811. this._floorMeshesCollection = [];
  105812. document.removeEventListener("keydown", this._onKeyDown);
  105813. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105814. window.removeEventListener("resize", this._onResize);
  105815. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  105816. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  105817. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  105818. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  105819. document.onmsfullscreenchange = null;
  105820. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  105821. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  105822. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  105823. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105824. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  105825. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  105826. this._scene.unregisterBeforeRender(this.beforeRender);
  105827. };
  105828. /**
  105829. * Gets the name of the VRExperienceHelper class
  105830. * @returns "VRExperienceHelper"
  105831. */
  105832. VRExperienceHelper.prototype.getClassName = function () {
  105833. return "VRExperienceHelper";
  105834. };
  105835. return VRExperienceHelper;
  105836. }());
  105837. BABYLON.VRExperienceHelper = VRExperienceHelper;
  105838. })(BABYLON || (BABYLON = {}));
  105839. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  105840. // Mainly based on these 2 articles :
  105841. // 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
  105842. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  105843. var BABYLON;
  105844. (function (BABYLON) {
  105845. /**
  105846. * Defines the potential axis of a Joystick
  105847. */
  105848. var JoystickAxis;
  105849. (function (JoystickAxis) {
  105850. /** X axis */
  105851. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  105852. /** Y axis */
  105853. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  105854. /** Z axis */
  105855. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  105856. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  105857. /**
  105858. * Class used to define virtual joystick (used in touch mode)
  105859. */
  105860. var VirtualJoystick = /** @class */ (function () {
  105861. /**
  105862. * Creates a new virtual joystick
  105863. * @param leftJoystick defines that the joystick is for left hand (false by default)
  105864. */
  105865. function VirtualJoystick(leftJoystick) {
  105866. var _this = this;
  105867. if (leftJoystick) {
  105868. this._leftJoystick = true;
  105869. }
  105870. else {
  105871. this._leftJoystick = false;
  105872. }
  105873. VirtualJoystick._globalJoystickIndex++;
  105874. // By default left & right arrow keys are moving the X
  105875. // and up & down keys are moving the Y
  105876. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  105877. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  105878. this.reverseLeftRight = false;
  105879. this.reverseUpDown = false;
  105880. // collections of pointers
  105881. this._touches = new BABYLON.StringDictionary();
  105882. this.deltaPosition = BABYLON.Vector3.Zero();
  105883. this._joystickSensibility = 25;
  105884. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  105885. this._onResize = function (evt) {
  105886. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  105887. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  105888. if (VirtualJoystick.vjCanvas) {
  105889. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  105890. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  105891. }
  105892. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  105893. };
  105894. // injecting a canvas element on top of the canvas 3D game
  105895. if (!VirtualJoystick.vjCanvas) {
  105896. window.addEventListener("resize", this._onResize, false);
  105897. VirtualJoystick.vjCanvas = document.createElement("canvas");
  105898. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  105899. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  105900. VirtualJoystick.vjCanvas.width = window.innerWidth;
  105901. VirtualJoystick.vjCanvas.height = window.innerHeight;
  105902. VirtualJoystick.vjCanvas.style.width = "100%";
  105903. VirtualJoystick.vjCanvas.style.height = "100%";
  105904. VirtualJoystick.vjCanvas.style.position = "absolute";
  105905. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  105906. VirtualJoystick.vjCanvas.style.top = "0px";
  105907. VirtualJoystick.vjCanvas.style.left = "0px";
  105908. VirtualJoystick.vjCanvas.style.zIndex = "5";
  105909. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  105910. // Support for jQuery PEP polyfill
  105911. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  105912. var context = VirtualJoystick.vjCanvas.getContext('2d');
  105913. if (!context) {
  105914. throw new Error("Unable to create canvas for virtual joystick");
  105915. }
  105916. VirtualJoystick.vjCanvasContext = context;
  105917. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  105918. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  105919. document.body.appendChild(VirtualJoystick.vjCanvas);
  105920. }
  105921. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  105922. this.pressed = false;
  105923. // default joystick color
  105924. this._joystickColor = "cyan";
  105925. this._joystickPointerID = -1;
  105926. // current joystick position
  105927. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  105928. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  105929. // origin joystick position
  105930. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  105931. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  105932. this._onPointerDownHandlerRef = function (evt) {
  105933. _this._onPointerDown(evt);
  105934. };
  105935. this._onPointerMoveHandlerRef = function (evt) {
  105936. _this._onPointerMove(evt);
  105937. };
  105938. this._onPointerUpHandlerRef = function (evt) {
  105939. _this._onPointerUp(evt);
  105940. };
  105941. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  105942. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  105943. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  105944. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  105945. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  105946. evt.preventDefault(); // Disables system menu
  105947. }, false);
  105948. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  105949. }
  105950. /**
  105951. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  105952. * @param newJoystickSensibility defines the new sensibility
  105953. */
  105954. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  105955. this._joystickSensibility = newJoystickSensibility;
  105956. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  105957. };
  105958. VirtualJoystick.prototype._onPointerDown = function (e) {
  105959. var positionOnScreenCondition;
  105960. e.preventDefault();
  105961. if (this._leftJoystick === true) {
  105962. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  105963. }
  105964. else {
  105965. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  105966. }
  105967. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  105968. // First contact will be dedicated to the virtual joystick
  105969. this._joystickPointerID = e.pointerId;
  105970. this._joystickPointerStartPos.x = e.clientX;
  105971. this._joystickPointerStartPos.y = e.clientY;
  105972. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  105973. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  105974. this._deltaJoystickVector.x = 0;
  105975. this._deltaJoystickVector.y = 0;
  105976. this.pressed = true;
  105977. this._touches.add(e.pointerId.toString(), e);
  105978. }
  105979. else {
  105980. // You can only trigger the action buttons with a joystick declared
  105981. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  105982. this._action();
  105983. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  105984. }
  105985. }
  105986. };
  105987. VirtualJoystick.prototype._onPointerMove = function (e) {
  105988. // If the current pointer is the one associated to the joystick (first touch contact)
  105989. if (this._joystickPointerID == e.pointerId) {
  105990. this._joystickPointerPos.x = e.clientX;
  105991. this._joystickPointerPos.y = e.clientY;
  105992. this._deltaJoystickVector = this._joystickPointerPos.clone();
  105993. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  105994. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  105995. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  105996. switch (this._axisTargetedByLeftAndRight) {
  105997. case JoystickAxis.X:
  105998. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  105999. break;
  106000. case JoystickAxis.Y:
  106001. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  106002. break;
  106003. case JoystickAxis.Z:
  106004. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  106005. break;
  106006. }
  106007. var directionUpDown = this.reverseUpDown ? 1 : -1;
  106008. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  106009. switch (this._axisTargetedByUpAndDown) {
  106010. case JoystickAxis.X:
  106011. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  106012. break;
  106013. case JoystickAxis.Y:
  106014. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  106015. break;
  106016. case JoystickAxis.Z:
  106017. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  106018. break;
  106019. }
  106020. }
  106021. else {
  106022. var data = this._touches.get(e.pointerId.toString());
  106023. if (data) {
  106024. data.x = e.clientX;
  106025. data.y = e.clientY;
  106026. }
  106027. }
  106028. };
  106029. VirtualJoystick.prototype._onPointerUp = function (e) {
  106030. if (this._joystickPointerID == e.pointerId) {
  106031. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106032. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106033. this._joystickPointerID = -1;
  106034. this.pressed = false;
  106035. }
  106036. else {
  106037. var touch = this._touches.get(e.pointerId.toString());
  106038. if (touch) {
  106039. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106040. }
  106041. }
  106042. this._deltaJoystickVector.x = 0;
  106043. this._deltaJoystickVector.y = 0;
  106044. this._touches.remove(e.pointerId.toString());
  106045. };
  106046. /**
  106047. * Change the color of the virtual joystick
  106048. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106049. */
  106050. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106051. this._joystickColor = newColor;
  106052. };
  106053. /**
  106054. * Defines a callback to call when the joystick is touched
  106055. * @param action defines the callback
  106056. */
  106057. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106058. this._action = action;
  106059. };
  106060. /**
  106061. * Defines which axis you'd like to control for left & right
  106062. * @param axis defines the axis to use
  106063. */
  106064. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106065. switch (axis) {
  106066. case JoystickAxis.X:
  106067. case JoystickAxis.Y:
  106068. case JoystickAxis.Z:
  106069. this._axisTargetedByLeftAndRight = axis;
  106070. break;
  106071. default:
  106072. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106073. break;
  106074. }
  106075. };
  106076. /**
  106077. * Defines which axis you'd like to control for up & down
  106078. * @param axis defines the axis to use
  106079. */
  106080. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106081. switch (axis) {
  106082. case JoystickAxis.X:
  106083. case JoystickAxis.Y:
  106084. case JoystickAxis.Z:
  106085. this._axisTargetedByUpAndDown = axis;
  106086. break;
  106087. default:
  106088. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106089. break;
  106090. }
  106091. };
  106092. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106093. var _this = this;
  106094. if (this.pressed) {
  106095. this._touches.forEach(function (key, touch) {
  106096. if (touch.pointerId === _this._joystickPointerID) {
  106097. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106098. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106099. VirtualJoystick.vjCanvasContext.beginPath();
  106100. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106101. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106102. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106103. VirtualJoystick.vjCanvasContext.stroke();
  106104. VirtualJoystick.vjCanvasContext.closePath();
  106105. VirtualJoystick.vjCanvasContext.beginPath();
  106106. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106107. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106108. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106109. VirtualJoystick.vjCanvasContext.stroke();
  106110. VirtualJoystick.vjCanvasContext.closePath();
  106111. VirtualJoystick.vjCanvasContext.beginPath();
  106112. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106113. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106114. VirtualJoystick.vjCanvasContext.stroke();
  106115. VirtualJoystick.vjCanvasContext.closePath();
  106116. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106117. }
  106118. else {
  106119. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106120. VirtualJoystick.vjCanvasContext.beginPath();
  106121. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106122. VirtualJoystick.vjCanvasContext.beginPath();
  106123. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106124. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106125. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106126. VirtualJoystick.vjCanvasContext.stroke();
  106127. VirtualJoystick.vjCanvasContext.closePath();
  106128. touch.prevX = touch.x;
  106129. touch.prevY = touch.y;
  106130. }
  106131. ;
  106132. });
  106133. }
  106134. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106135. };
  106136. /**
  106137. * Release internal HTML canvas
  106138. */
  106139. VirtualJoystick.prototype.releaseCanvas = function () {
  106140. if (VirtualJoystick.vjCanvas) {
  106141. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106142. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106143. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106144. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106145. window.removeEventListener("resize", this._onResize);
  106146. document.body.removeChild(VirtualJoystick.vjCanvas);
  106147. VirtualJoystick.vjCanvas = null;
  106148. }
  106149. };
  106150. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106151. VirtualJoystick._globalJoystickIndex = 0;
  106152. return VirtualJoystick;
  106153. }());
  106154. BABYLON.VirtualJoystick = VirtualJoystick;
  106155. })(BABYLON || (BABYLON = {}));
  106156. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106157. var BABYLON;
  106158. (function (BABYLON) {
  106159. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106160. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106161. });
  106162. /**
  106163. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106164. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106165. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106166. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106167. */
  106168. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106169. __extends(VirtualJoysticksCamera, _super);
  106170. /**
  106171. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106172. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106173. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106174. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106175. * @param name Define the name of the camera in the scene
  106176. * @param position Define the start position of the camera in the scene
  106177. * @param scene Define the scene the camera belongs to
  106178. */
  106179. function VirtualJoysticksCamera(name, position, scene) {
  106180. var _this = _super.call(this, name, position, scene) || this;
  106181. _this.inputs.addVirtualJoystick();
  106182. return _this;
  106183. }
  106184. /**
  106185. * Gets the current object class name.
  106186. * @return the class name
  106187. */
  106188. VirtualJoysticksCamera.prototype.getClassName = function () {
  106189. return "VirtualJoysticksCamera";
  106190. };
  106191. return VirtualJoysticksCamera;
  106192. }(BABYLON.FreeCamera));
  106193. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106194. })(BABYLON || (BABYLON = {}));
  106195. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106196. var BABYLON;
  106197. (function (BABYLON) {
  106198. /**
  106199. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106200. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106201. */
  106202. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106203. function FreeCameraVirtualJoystickInput() {
  106204. }
  106205. /**
  106206. * Gets the left stick of the virtual joystick.
  106207. * @returns The virtual Joystick
  106208. */
  106209. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106210. return this._leftjoystick;
  106211. };
  106212. /**
  106213. * Gets the right stick of the virtual joystick.
  106214. * @returns The virtual Joystick
  106215. */
  106216. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106217. return this._rightjoystick;
  106218. };
  106219. /**
  106220. * Update the current camera state depending on the inputs that have been used this frame.
  106221. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106222. */
  106223. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106224. if (this._leftjoystick) {
  106225. var camera = this.camera;
  106226. var speed = camera._computeLocalCameraSpeed() * 50;
  106227. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106228. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106229. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106230. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106231. if (!this._leftjoystick.pressed) {
  106232. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106233. }
  106234. if (!this._rightjoystick.pressed) {
  106235. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106236. }
  106237. }
  106238. };
  106239. /**
  106240. * Attach the input controls to a specific dom element to get the input from.
  106241. * @param element Defines the element the controls should be listened from
  106242. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106243. */
  106244. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106245. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106246. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106247. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106248. this._leftjoystick.setJoystickSensibility(0.15);
  106249. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106250. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106251. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106252. this._rightjoystick.reverseUpDown = true;
  106253. this._rightjoystick.setJoystickSensibility(0.05);
  106254. this._rightjoystick.setJoystickColor("yellow");
  106255. };
  106256. /**
  106257. * Detach the current controls from the specified dom element.
  106258. * @param element Defines the element to stop listening the inputs from
  106259. */
  106260. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106261. this._leftjoystick.releaseCanvas();
  106262. this._rightjoystick.releaseCanvas();
  106263. };
  106264. /**
  106265. * Gets the class name of the current intput.
  106266. * @returns the class name
  106267. */
  106268. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106269. return "FreeCameraVirtualJoystickInput";
  106270. };
  106271. /**
  106272. * Get the friendly name associated with the input class.
  106273. * @returns the input friendly name
  106274. */
  106275. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106276. return "virtualJoystick";
  106277. };
  106278. return FreeCameraVirtualJoystickInput;
  106279. }());
  106280. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106281. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106282. })(BABYLON || (BABYLON = {}));
  106283. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106284. var BABYLON;
  106285. (function (BABYLON) {
  106286. /**
  106287. * Class used to specify simplification options
  106288. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106289. */
  106290. var SimplificationSettings = /** @class */ (function () {
  106291. /**
  106292. * Creates a SimplificationSettings
  106293. * @param quality expected quality
  106294. * @param distance distance when this optimized version should be used
  106295. * @param optimizeMesh already optimized mesh
  106296. */
  106297. function SimplificationSettings(
  106298. /** expected quality */
  106299. quality,
  106300. /** distance when this optimized version should be used */
  106301. distance,
  106302. /** already optimized mesh */
  106303. optimizeMesh) {
  106304. this.quality = quality;
  106305. this.distance = distance;
  106306. this.optimizeMesh = optimizeMesh;
  106307. }
  106308. return SimplificationSettings;
  106309. }());
  106310. BABYLON.SimplificationSettings = SimplificationSettings;
  106311. /**
  106312. * Queue used to order the simplification tasks
  106313. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106314. */
  106315. var SimplificationQueue = /** @class */ (function () {
  106316. /**
  106317. * Creates a new queue
  106318. */
  106319. function SimplificationQueue() {
  106320. this.running = false;
  106321. this._simplificationArray = [];
  106322. }
  106323. /**
  106324. * Adds a new simplification task
  106325. * @param task defines a task to add
  106326. */
  106327. SimplificationQueue.prototype.addTask = function (task) {
  106328. this._simplificationArray.push(task);
  106329. };
  106330. /**
  106331. * Execute next task
  106332. */
  106333. SimplificationQueue.prototype.executeNext = function () {
  106334. var task = this._simplificationArray.pop();
  106335. if (task) {
  106336. this.running = true;
  106337. this.runSimplification(task);
  106338. }
  106339. else {
  106340. this.running = false;
  106341. }
  106342. };
  106343. /**
  106344. * Execute a simplification task
  106345. * @param task defines the task to run
  106346. */
  106347. SimplificationQueue.prototype.runSimplification = function (task) {
  106348. var _this = this;
  106349. if (task.parallelProcessing) {
  106350. //parallel simplifier
  106351. task.settings.forEach(function (setting) {
  106352. var simplifier = _this.getSimplifier(task);
  106353. simplifier.simplify(setting, function (newMesh) {
  106354. task.mesh.addLODLevel(setting.distance, newMesh);
  106355. newMesh.isVisible = true;
  106356. //check if it is the last
  106357. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106358. //all done, run the success callback.
  106359. task.successCallback();
  106360. }
  106361. _this.executeNext();
  106362. });
  106363. });
  106364. }
  106365. else {
  106366. //single simplifier.
  106367. var simplifier = this.getSimplifier(task);
  106368. var runDecimation = function (setting, callback) {
  106369. simplifier.simplify(setting, function (newMesh) {
  106370. task.mesh.addLODLevel(setting.distance, newMesh);
  106371. newMesh.isVisible = true;
  106372. //run the next quality level
  106373. callback();
  106374. });
  106375. };
  106376. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106377. runDecimation(task.settings[loop.index], function () {
  106378. loop.executeNext();
  106379. });
  106380. }, function () {
  106381. //execution ended, run the success callback.
  106382. if (task.successCallback) {
  106383. task.successCallback();
  106384. }
  106385. _this.executeNext();
  106386. });
  106387. }
  106388. };
  106389. SimplificationQueue.prototype.getSimplifier = function (task) {
  106390. switch (task.simplificationType) {
  106391. case SimplificationType.QUADRATIC:
  106392. default:
  106393. return new QuadraticErrorSimplification(task.mesh);
  106394. }
  106395. };
  106396. return SimplificationQueue;
  106397. }());
  106398. BABYLON.SimplificationQueue = SimplificationQueue;
  106399. /**
  106400. * The implemented types of simplification
  106401. * At the moment only Quadratic Error Decimation is implemented
  106402. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106403. */
  106404. var SimplificationType;
  106405. (function (SimplificationType) {
  106406. /** Quadratic error decimation */
  106407. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106408. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106409. var DecimationTriangle = /** @class */ (function () {
  106410. function DecimationTriangle(vertices) {
  106411. this.vertices = vertices;
  106412. this.error = new Array(4);
  106413. this.deleted = false;
  106414. this.isDirty = false;
  106415. this.deletePending = false;
  106416. this.borderFactor = 0;
  106417. }
  106418. return DecimationTriangle;
  106419. }());
  106420. var DecimationVertex = /** @class */ (function () {
  106421. function DecimationVertex(position, id) {
  106422. this.position = position;
  106423. this.id = id;
  106424. this.isBorder = true;
  106425. this.q = new QuadraticMatrix();
  106426. this.triangleCount = 0;
  106427. this.triangleStart = 0;
  106428. this.originalOffsets = [];
  106429. }
  106430. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106431. this.position.copyFrom(newPosition);
  106432. };
  106433. return DecimationVertex;
  106434. }());
  106435. var QuadraticMatrix = /** @class */ (function () {
  106436. function QuadraticMatrix(data) {
  106437. this.data = new Array(10);
  106438. for (var i = 0; i < 10; ++i) {
  106439. if (data && data[i]) {
  106440. this.data[i] = data[i];
  106441. }
  106442. else {
  106443. this.data[i] = 0;
  106444. }
  106445. }
  106446. }
  106447. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106448. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106449. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106450. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106451. return det;
  106452. };
  106453. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106454. for (var i = 0; i < 10; ++i) {
  106455. this.data[i] += matrix.data[i];
  106456. }
  106457. };
  106458. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106459. for (var i = 0; i < 10; ++i) {
  106460. this.data[i] += data[i];
  106461. }
  106462. };
  106463. QuadraticMatrix.prototype.add = function (matrix) {
  106464. var m = new QuadraticMatrix();
  106465. for (var i = 0; i < 10; ++i) {
  106466. m.data[i] = this.data[i] + matrix.data[i];
  106467. }
  106468. return m;
  106469. };
  106470. QuadraticMatrix.FromData = function (a, b, c, d) {
  106471. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106472. };
  106473. //returning an array to avoid garbage collection
  106474. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106475. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106476. };
  106477. return QuadraticMatrix;
  106478. }());
  106479. var Reference = /** @class */ (function () {
  106480. function Reference(vertexId, triangleId) {
  106481. this.vertexId = vertexId;
  106482. this.triangleId = triangleId;
  106483. }
  106484. return Reference;
  106485. }());
  106486. /**
  106487. * An implementation of the Quadratic Error simplification algorithm.
  106488. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106489. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106490. * @author RaananW
  106491. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106492. */
  106493. var QuadraticErrorSimplification = /** @class */ (function () {
  106494. function QuadraticErrorSimplification(_mesh) {
  106495. this._mesh = _mesh;
  106496. this.syncIterations = 5000;
  106497. this.aggressiveness = 7;
  106498. this.decimationIterations = 100;
  106499. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106500. }
  106501. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106502. var _this = this;
  106503. this.initDecimatedMesh();
  106504. //iterating through the submeshes array, one after the other.
  106505. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106506. _this.initWithMesh(loop.index, function () {
  106507. _this.runDecimation(settings, loop.index, function () {
  106508. loop.executeNext();
  106509. });
  106510. }, settings.optimizeMesh);
  106511. }, function () {
  106512. setTimeout(function () {
  106513. successCallback(_this._reconstructedMesh);
  106514. }, 0);
  106515. });
  106516. };
  106517. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106518. var _this = this;
  106519. var targetCount = ~~(this.triangles.length * settings.quality);
  106520. var deletedTriangles = 0;
  106521. var triangleCount = this.triangles.length;
  106522. var iterationFunction = function (iteration, callback) {
  106523. setTimeout(function () {
  106524. if (iteration % 5 === 0) {
  106525. _this.updateMesh(iteration === 0);
  106526. }
  106527. for (var i = 0; i < _this.triangles.length; ++i) {
  106528. _this.triangles[i].isDirty = false;
  106529. }
  106530. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106531. var trianglesIterator = function (i) {
  106532. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106533. var t = _this.triangles[tIdx];
  106534. if (!t)
  106535. return;
  106536. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106537. return;
  106538. }
  106539. for (var j = 0; j < 3; ++j) {
  106540. if (t.error[j] < threshold) {
  106541. var deleted0 = [];
  106542. var deleted1 = [];
  106543. var v0 = t.vertices[j];
  106544. var v1 = t.vertices[(j + 1) % 3];
  106545. if (v0.isBorder || v1.isBorder)
  106546. continue;
  106547. var p = BABYLON.Vector3.Zero();
  106548. var n = BABYLON.Vector3.Zero();
  106549. var uv = BABYLON.Vector2.Zero();
  106550. var color = new BABYLON.Color4(0, 0, 0, 1);
  106551. _this.calculateError(v0, v1, p, n, uv, color);
  106552. var delTr = new Array();
  106553. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  106554. continue;
  106555. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  106556. continue;
  106557. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  106558. continue;
  106559. var uniqueArray = new Array();
  106560. delTr.forEach(function (deletedT) {
  106561. if (uniqueArray.indexOf(deletedT) === -1) {
  106562. deletedT.deletePending = true;
  106563. uniqueArray.push(deletedT);
  106564. }
  106565. });
  106566. if (uniqueArray.length % 2 !== 0) {
  106567. continue;
  106568. }
  106569. v0.q = v1.q.add(v0.q);
  106570. v0.updatePosition(p);
  106571. var tStart = _this.references.length;
  106572. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  106573. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  106574. var tCount = _this.references.length - tStart;
  106575. if (tCount <= v0.triangleCount) {
  106576. if (tCount) {
  106577. for (var c = 0; c < tCount; c++) {
  106578. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  106579. }
  106580. }
  106581. }
  106582. else {
  106583. v0.triangleStart = tStart;
  106584. }
  106585. v0.triangleCount = tCount;
  106586. break;
  106587. }
  106588. }
  106589. };
  106590. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  106591. }, 0);
  106592. };
  106593. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  106594. if (triangleCount - deletedTriangles <= targetCount)
  106595. loop.breakLoop();
  106596. else {
  106597. iterationFunction(loop.index, function () {
  106598. loop.executeNext();
  106599. });
  106600. }
  106601. }, function () {
  106602. setTimeout(function () {
  106603. //reconstruct this part of the mesh
  106604. _this.reconstructMesh(submeshIndex);
  106605. successCallback();
  106606. }, 0);
  106607. });
  106608. };
  106609. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  106610. var _this = this;
  106611. this.vertices = [];
  106612. this.triangles = [];
  106613. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106614. var indices = this._mesh.getIndices();
  106615. var submesh = this._mesh.subMeshes[submeshIndex];
  106616. var findInVertices = function (positionToSearch) {
  106617. if (optimizeMesh) {
  106618. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  106619. if (_this.vertices[ii].position.equals(positionToSearch)) {
  106620. return _this.vertices[ii];
  106621. }
  106622. }
  106623. }
  106624. return null;
  106625. };
  106626. var vertexReferences = [];
  106627. var vertexInit = function (i) {
  106628. if (!positionData) {
  106629. return;
  106630. }
  106631. var offset = i + submesh.verticesStart;
  106632. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  106633. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  106634. vertex.originalOffsets.push(offset);
  106635. if (vertex.id === _this.vertices.length) {
  106636. _this.vertices.push(vertex);
  106637. }
  106638. vertexReferences.push(vertex.id);
  106639. };
  106640. //var totalVertices = mesh.getTotalVertices();
  106641. var totalVertices = submesh.verticesCount;
  106642. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  106643. var indicesInit = function (i) {
  106644. if (!indices) {
  106645. return;
  106646. }
  106647. var offset = (submesh.indexStart / 3) + i;
  106648. var pos = (offset * 3);
  106649. var i0 = indices[pos + 0];
  106650. var i1 = indices[pos + 1];
  106651. var i2 = indices[pos + 2];
  106652. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  106653. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  106654. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  106655. var triangle = new DecimationTriangle([v0, v1, v2]);
  106656. triangle.originalOffset = pos;
  106657. _this.triangles.push(triangle);
  106658. };
  106659. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  106660. _this.init(callback);
  106661. });
  106662. });
  106663. };
  106664. QuadraticErrorSimplification.prototype.init = function (callback) {
  106665. var _this = this;
  106666. var triangleInit1 = function (i) {
  106667. var t = _this.triangles[i];
  106668. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  106669. for (var j = 0; j < 3; j++) {
  106670. 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))));
  106671. }
  106672. };
  106673. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  106674. var triangleInit2 = function (i) {
  106675. var t = _this.triangles[i];
  106676. for (var j = 0; j < 3; ++j) {
  106677. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  106678. }
  106679. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106680. };
  106681. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  106682. callback();
  106683. });
  106684. });
  106685. };
  106686. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  106687. var newTriangles = [];
  106688. var i;
  106689. for (i = 0; i < this.vertices.length; ++i) {
  106690. this.vertices[i].triangleCount = 0;
  106691. }
  106692. var t;
  106693. var j;
  106694. for (i = 0; i < this.triangles.length; ++i) {
  106695. if (!this.triangles[i].deleted) {
  106696. t = this.triangles[i];
  106697. for (j = 0; j < 3; ++j) {
  106698. t.vertices[j].triangleCount = 1;
  106699. }
  106700. newTriangles.push(t);
  106701. }
  106702. }
  106703. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  106704. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  106705. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  106706. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  106707. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  106708. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  106709. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  106710. var vertexCount = 0;
  106711. for (i = 0; i < this.vertices.length; ++i) {
  106712. var vertex = this.vertices[i];
  106713. vertex.id = vertexCount;
  106714. if (vertex.triangleCount) {
  106715. vertex.originalOffsets.forEach(function (originalOffset) {
  106716. if (!normalData) {
  106717. return;
  106718. }
  106719. newPositionData.push(vertex.position.x);
  106720. newPositionData.push(vertex.position.y);
  106721. newPositionData.push(vertex.position.z);
  106722. newNormalData.push(normalData[originalOffset * 3]);
  106723. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  106724. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  106725. if (uvs && uvs.length) {
  106726. newUVsData.push(uvs[(originalOffset * 2)]);
  106727. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  106728. }
  106729. else if (colorsData && colorsData.length) {
  106730. newColorsData.push(colorsData[(originalOffset * 4)]);
  106731. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  106732. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  106733. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  106734. }
  106735. ++vertexCount;
  106736. });
  106737. }
  106738. }
  106739. var startingIndex = this._reconstructedMesh.getTotalIndices();
  106740. var startingVertex = this._reconstructedMesh.getTotalVertices();
  106741. var submeshesArray = this._reconstructedMesh.subMeshes;
  106742. this._reconstructedMesh.subMeshes = [];
  106743. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  106744. var originalIndices = this._mesh.getIndices();
  106745. for (i = 0; i < newTriangles.length; ++i) {
  106746. t = newTriangles[i]; //now get the new referencing point for each vertex
  106747. [0, 1, 2].forEach(function (idx) {
  106748. var id = originalIndices[t.originalOffset + idx];
  106749. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  106750. if (offset < 0)
  106751. offset = 0;
  106752. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  106753. });
  106754. }
  106755. //overwriting the old vertex buffers and indices.
  106756. this._reconstructedMesh.setIndices(newIndicesArray);
  106757. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  106758. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  106759. if (newUVsData.length > 0)
  106760. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  106761. if (newColorsData.length > 0)
  106762. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  106763. //create submesh
  106764. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  106765. if (submeshIndex > 0) {
  106766. this._reconstructedMesh.subMeshes = [];
  106767. submeshesArray.forEach(function (submesh) {
  106768. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  106769. });
  106770. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  106771. }
  106772. };
  106773. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  106774. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  106775. this._reconstructedMesh.material = this._mesh.material;
  106776. this._reconstructedMesh.parent = this._mesh.parent;
  106777. this._reconstructedMesh.isVisible = false;
  106778. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  106779. };
  106780. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  106781. for (var i = 0; i < vertex1.triangleCount; ++i) {
  106782. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  106783. if (t.deleted)
  106784. continue;
  106785. var s = this.references[vertex1.triangleStart + i].vertexId;
  106786. var v1 = t.vertices[(s + 1) % 3];
  106787. var v2 = t.vertices[(s + 2) % 3];
  106788. if ((v1 === vertex2 || v2 === vertex2)) {
  106789. deletedArray[i] = true;
  106790. delTr.push(t);
  106791. continue;
  106792. }
  106793. var d1 = v1.position.subtract(point);
  106794. d1 = d1.normalize();
  106795. var d2 = v2.position.subtract(point);
  106796. d2 = d2.normalize();
  106797. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  106798. return true;
  106799. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  106800. deletedArray[i] = false;
  106801. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  106802. return true;
  106803. }
  106804. return false;
  106805. };
  106806. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  106807. var newDeleted = deletedTriangles;
  106808. for (var i = 0; i < vertex.triangleCount; ++i) {
  106809. var ref = this.references[vertex.triangleStart + i];
  106810. var t = this.triangles[ref.triangleId];
  106811. if (t.deleted)
  106812. continue;
  106813. if (deletedArray[i] && t.deletePending) {
  106814. t.deleted = true;
  106815. newDeleted++;
  106816. continue;
  106817. }
  106818. t.vertices[ref.vertexId] = origVertex;
  106819. t.isDirty = true;
  106820. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  106821. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  106822. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  106823. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106824. this.references.push(ref);
  106825. }
  106826. return newDeleted;
  106827. };
  106828. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  106829. for (var i = 0; i < this.vertices.length; ++i) {
  106830. var vCount = [];
  106831. var vId = [];
  106832. var v = this.vertices[i];
  106833. var j;
  106834. for (j = 0; j < v.triangleCount; ++j) {
  106835. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  106836. for (var ii = 0; ii < 3; ii++) {
  106837. var ofs = 0;
  106838. var vv = triangle.vertices[ii];
  106839. while (ofs < vCount.length) {
  106840. if (vId[ofs] === vv.id)
  106841. break;
  106842. ++ofs;
  106843. }
  106844. if (ofs === vCount.length) {
  106845. vCount.push(1);
  106846. vId.push(vv.id);
  106847. }
  106848. else {
  106849. vCount[ofs]++;
  106850. }
  106851. }
  106852. }
  106853. for (j = 0; j < vCount.length; ++j) {
  106854. if (vCount[j] === 1) {
  106855. this.vertices[vId[j]].isBorder = true;
  106856. }
  106857. else {
  106858. this.vertices[vId[j]].isBorder = false;
  106859. }
  106860. }
  106861. }
  106862. };
  106863. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  106864. if (identifyBorders === void 0) { identifyBorders = false; }
  106865. var i;
  106866. if (!identifyBorders) {
  106867. var newTrianglesVector = [];
  106868. for (i = 0; i < this.triangles.length; ++i) {
  106869. if (!this.triangles[i].deleted) {
  106870. newTrianglesVector.push(this.triangles[i]);
  106871. }
  106872. }
  106873. this.triangles = newTrianglesVector;
  106874. }
  106875. for (i = 0; i < this.vertices.length; ++i) {
  106876. this.vertices[i].triangleCount = 0;
  106877. this.vertices[i].triangleStart = 0;
  106878. }
  106879. var t;
  106880. var j;
  106881. var v;
  106882. for (i = 0; i < this.triangles.length; ++i) {
  106883. t = this.triangles[i];
  106884. for (j = 0; j < 3; ++j) {
  106885. v = t.vertices[j];
  106886. v.triangleCount++;
  106887. }
  106888. }
  106889. var tStart = 0;
  106890. for (i = 0; i < this.vertices.length; ++i) {
  106891. this.vertices[i].triangleStart = tStart;
  106892. tStart += this.vertices[i].triangleCount;
  106893. this.vertices[i].triangleCount = 0;
  106894. }
  106895. var newReferences = new Array(this.triangles.length * 3);
  106896. for (i = 0; i < this.triangles.length; ++i) {
  106897. t = this.triangles[i];
  106898. for (j = 0; j < 3; ++j) {
  106899. v = t.vertices[j];
  106900. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  106901. v.triangleCount++;
  106902. }
  106903. }
  106904. this.references = newReferences;
  106905. if (identifyBorders) {
  106906. this.identifyBorder();
  106907. }
  106908. };
  106909. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  106910. var x = point.x;
  106911. var y = point.y;
  106912. var z = point.z;
  106913. 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
  106914. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  106915. };
  106916. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  106917. var q = vertex1.q.add(vertex2.q);
  106918. var border = vertex1.isBorder && vertex2.isBorder;
  106919. var error = 0;
  106920. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  106921. if (qDet !== 0 && !border) {
  106922. if (!pointResult) {
  106923. pointResult = BABYLON.Vector3.Zero();
  106924. }
  106925. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  106926. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  106927. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  106928. error = this.vertexError(q, pointResult);
  106929. }
  106930. else {
  106931. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  106932. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  106933. var error1 = this.vertexError(q, vertex1.position);
  106934. var error2 = this.vertexError(q, vertex2.position);
  106935. var error3 = this.vertexError(q, p3);
  106936. error = Math.min(error1, error2, error3);
  106937. if (error === error1) {
  106938. if (pointResult) {
  106939. pointResult.copyFrom(vertex1.position);
  106940. }
  106941. }
  106942. else if (error === error2) {
  106943. if (pointResult) {
  106944. pointResult.copyFrom(vertex2.position);
  106945. }
  106946. }
  106947. else {
  106948. if (pointResult) {
  106949. pointResult.copyFrom(p3);
  106950. }
  106951. }
  106952. }
  106953. return error;
  106954. };
  106955. return QuadraticErrorSimplification;
  106956. }());
  106957. })(BABYLON || (BABYLON = {}));
  106958. //# sourceMappingURL=babylon.meshSimplification.js.map
  106959. var BABYLON;
  106960. (function (BABYLON) {
  106961. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  106962. get: function () {
  106963. if (!this._simplificationQueue) {
  106964. this._simplificationQueue = new BABYLON.SimplificationQueue();
  106965. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  106966. if (!component) {
  106967. component = new SimplicationQueueSceneComponent(this);
  106968. this._addComponent(component);
  106969. }
  106970. }
  106971. return this._simplificationQueue;
  106972. },
  106973. set: function (value) {
  106974. this._simplificationQueue = value;
  106975. },
  106976. enumerable: true,
  106977. configurable: true
  106978. });
  106979. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  106980. if (parallelProcessing === void 0) { parallelProcessing = true; }
  106981. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  106982. this.getScene().simplificationQueue.addTask({
  106983. settings: settings,
  106984. parallelProcessing: parallelProcessing,
  106985. mesh: this,
  106986. simplificationType: simplificationType,
  106987. successCallback: successCallback
  106988. });
  106989. return this;
  106990. };
  106991. /**
  106992. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  106993. * created in a scene
  106994. */
  106995. var SimplicationQueueSceneComponent = /** @class */ (function () {
  106996. /**
  106997. * Creates a new instance of the component for the given scene
  106998. * @param scene Defines the scene to register the component in
  106999. */
  107000. function SimplicationQueueSceneComponent(scene) {
  107001. /**
  107002. * The component name helpfull to identify the component in the list of scene components.
  107003. */
  107004. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  107005. this.scene = scene;
  107006. }
  107007. /**
  107008. * Registers the component in a given scene
  107009. */
  107010. SimplicationQueueSceneComponent.prototype.register = function () {
  107011. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  107012. };
  107013. /**
  107014. * Rebuilds the elements related to this component in case of
  107015. * context lost for instance.
  107016. */
  107017. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  107018. // Nothing to do for this component
  107019. };
  107020. /**
  107021. * Disposes the component and the associated ressources
  107022. */
  107023. SimplicationQueueSceneComponent.prototype.dispose = function () {
  107024. // Nothing to do for this component
  107025. };
  107026. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  107027. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  107028. this.scene._simplificationQueue.executeNext();
  107029. }
  107030. };
  107031. return SimplicationQueueSceneComponent;
  107032. }());
  107033. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107034. })(BABYLON || (BABYLON = {}));
  107035. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107036. var BABYLON;
  107037. (function (BABYLON) {
  107038. /**
  107039. * Class used to represent a specific level of detail of a mesh
  107040. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107041. */
  107042. var MeshLODLevel = /** @class */ (function () {
  107043. /**
  107044. * Creates a new LOD level
  107045. * @param distance defines the distance where this level should star being displayed
  107046. * @param mesh defines the mesh to use to render this level
  107047. */
  107048. function MeshLODLevel(
  107049. /** Defines the distance where this level should star being displayed */
  107050. distance,
  107051. /** Defines the mesh to use to render this level */
  107052. mesh) {
  107053. this.distance = distance;
  107054. this.mesh = mesh;
  107055. }
  107056. return MeshLODLevel;
  107057. }());
  107058. BABYLON.MeshLODLevel = MeshLODLevel;
  107059. })(BABYLON || (BABYLON = {}));
  107060. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107061. var BABYLON;
  107062. (function (BABYLON) {
  107063. /**
  107064. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107065. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107066. */
  107067. var SceneOptimization = /** @class */ (function () {
  107068. /**
  107069. * Creates the SceneOptimization object
  107070. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107071. * @param desc defines the description associated with the optimization
  107072. */
  107073. function SceneOptimization(
  107074. /**
  107075. * Defines the priority of this optimization (0 by default which means first in the list)
  107076. */
  107077. priority) {
  107078. if (priority === void 0) { priority = 0; }
  107079. this.priority = priority;
  107080. }
  107081. /**
  107082. * Gets a string describing the action executed by the current optimization
  107083. * @returns description string
  107084. */
  107085. SceneOptimization.prototype.getDescription = function () {
  107086. return "";
  107087. };
  107088. /**
  107089. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107090. * @param scene defines the current scene where to apply this optimization
  107091. * @param optimizer defines the current optimizer
  107092. * @returns true if everything that can be done was applied
  107093. */
  107094. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107095. return true;
  107096. };
  107097. ;
  107098. return SceneOptimization;
  107099. }());
  107100. BABYLON.SceneOptimization = SceneOptimization;
  107101. /**
  107102. * Defines an optimization used to reduce the size of render target textures
  107103. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107104. */
  107105. var TextureOptimization = /** @class */ (function (_super) {
  107106. __extends(TextureOptimization, _super);
  107107. /**
  107108. * Creates the TextureOptimization object
  107109. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107110. * @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
  107111. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107112. */
  107113. function TextureOptimization(
  107114. /**
  107115. * Defines the priority of this optimization (0 by default which means first in the list)
  107116. */
  107117. priority,
  107118. /**
  107119. * 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
  107120. */
  107121. maximumSize,
  107122. /**
  107123. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107124. */
  107125. step) {
  107126. if (priority === void 0) { priority = 0; }
  107127. if (maximumSize === void 0) { maximumSize = 1024; }
  107128. if (step === void 0) { step = 0.5; }
  107129. var _this = _super.call(this, priority) || this;
  107130. _this.priority = priority;
  107131. _this.maximumSize = maximumSize;
  107132. _this.step = step;
  107133. return _this;
  107134. }
  107135. /**
  107136. * Gets a string describing the action executed by the current optimization
  107137. * @returns description string
  107138. */
  107139. TextureOptimization.prototype.getDescription = function () {
  107140. return "Reducing render target texture size to " + this.maximumSize;
  107141. };
  107142. /**
  107143. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107144. * @param scene defines the current scene where to apply this optimization
  107145. * @param optimizer defines the current optimizer
  107146. * @returns true if everything that can be done was applied
  107147. */
  107148. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107149. var allDone = true;
  107150. for (var index = 0; index < scene.textures.length; index++) {
  107151. var texture = scene.textures[index];
  107152. if (!texture.canRescale || texture.getContext) {
  107153. continue;
  107154. }
  107155. var currentSize = texture.getSize();
  107156. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107157. if (maxDimension > this.maximumSize) {
  107158. texture.scale(this.step);
  107159. allDone = false;
  107160. }
  107161. }
  107162. return allDone;
  107163. };
  107164. return TextureOptimization;
  107165. }(SceneOptimization));
  107166. BABYLON.TextureOptimization = TextureOptimization;
  107167. /**
  107168. * Defines an optimization used to increase or decrease the rendering resolution
  107169. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107170. */
  107171. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107172. __extends(HardwareScalingOptimization, _super);
  107173. /**
  107174. * Creates the HardwareScalingOptimization object
  107175. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107176. * @param maximumScale defines the maximum scale to use (2 by default)
  107177. * @param step defines the step to use between two passes (0.5 by default)
  107178. */
  107179. function HardwareScalingOptimization(
  107180. /**
  107181. * Defines the priority of this optimization (0 by default which means first in the list)
  107182. */
  107183. priority,
  107184. /**
  107185. * Defines the maximum scale to use (2 by default)
  107186. */
  107187. maximumScale,
  107188. /**
  107189. * Defines the step to use between two passes (0.5 by default)
  107190. */
  107191. step) {
  107192. if (priority === void 0) { priority = 0; }
  107193. if (maximumScale === void 0) { maximumScale = 2; }
  107194. if (step === void 0) { step = 0.25; }
  107195. var _this = _super.call(this, priority) || this;
  107196. _this.priority = priority;
  107197. _this.maximumScale = maximumScale;
  107198. _this.step = step;
  107199. _this._currentScale = -1;
  107200. _this._directionOffset = 1;
  107201. return _this;
  107202. }
  107203. /**
  107204. * Gets a string describing the action executed by the current optimization
  107205. * @return description string
  107206. */
  107207. HardwareScalingOptimization.prototype.getDescription = function () {
  107208. return "Setting hardware scaling level to " + this._currentScale;
  107209. };
  107210. /**
  107211. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107212. * @param scene defines the current scene where to apply this optimization
  107213. * @param optimizer defines the current optimizer
  107214. * @returns true if everything that can be done was applied
  107215. */
  107216. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107217. if (this._currentScale === -1) {
  107218. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107219. if (this._currentScale > this.maximumScale) {
  107220. this._directionOffset = -1;
  107221. }
  107222. }
  107223. this._currentScale += this._directionOffset * this.step;
  107224. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107225. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107226. };
  107227. ;
  107228. return HardwareScalingOptimization;
  107229. }(SceneOptimization));
  107230. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107231. /**
  107232. * Defines an optimization used to remove shadows
  107233. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107234. */
  107235. var ShadowsOptimization = /** @class */ (function (_super) {
  107236. __extends(ShadowsOptimization, _super);
  107237. function ShadowsOptimization() {
  107238. return _super !== null && _super.apply(this, arguments) || this;
  107239. }
  107240. /**
  107241. * Gets a string describing the action executed by the current optimization
  107242. * @return description string
  107243. */
  107244. ShadowsOptimization.prototype.getDescription = function () {
  107245. return "Turning shadows on/off";
  107246. };
  107247. /**
  107248. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107249. * @param scene defines the current scene where to apply this optimization
  107250. * @param optimizer defines the current optimizer
  107251. * @returns true if everything that can be done was applied
  107252. */
  107253. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107254. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107255. return true;
  107256. };
  107257. ;
  107258. return ShadowsOptimization;
  107259. }(SceneOptimization));
  107260. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107261. /**
  107262. * Defines an optimization used to turn post-processes off
  107263. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107264. */
  107265. var PostProcessesOptimization = /** @class */ (function (_super) {
  107266. __extends(PostProcessesOptimization, _super);
  107267. function PostProcessesOptimization() {
  107268. return _super !== null && _super.apply(this, arguments) || this;
  107269. }
  107270. /**
  107271. * Gets a string describing the action executed by the current optimization
  107272. * @return description string
  107273. */
  107274. PostProcessesOptimization.prototype.getDescription = function () {
  107275. return "Turning post-processes on/off";
  107276. };
  107277. /**
  107278. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107279. * @param scene defines the current scene where to apply this optimization
  107280. * @param optimizer defines the current optimizer
  107281. * @returns true if everything that can be done was applied
  107282. */
  107283. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107284. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107285. return true;
  107286. };
  107287. ;
  107288. return PostProcessesOptimization;
  107289. }(SceneOptimization));
  107290. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107291. /**
  107292. * Defines an optimization used to turn lens flares off
  107293. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107294. */
  107295. var LensFlaresOptimization = /** @class */ (function (_super) {
  107296. __extends(LensFlaresOptimization, _super);
  107297. function LensFlaresOptimization() {
  107298. return _super !== null && _super.apply(this, arguments) || this;
  107299. }
  107300. /**
  107301. * Gets a string describing the action executed by the current optimization
  107302. * @return description string
  107303. */
  107304. LensFlaresOptimization.prototype.getDescription = function () {
  107305. return "Turning lens flares on/off";
  107306. };
  107307. /**
  107308. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107309. * @param scene defines the current scene where to apply this optimization
  107310. * @param optimizer defines the current optimizer
  107311. * @returns true if everything that can be done was applied
  107312. */
  107313. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107314. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107315. return true;
  107316. };
  107317. ;
  107318. return LensFlaresOptimization;
  107319. }(SceneOptimization));
  107320. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107321. /**
  107322. * Defines an optimization based on user defined callback.
  107323. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107324. */
  107325. var CustomOptimization = /** @class */ (function (_super) {
  107326. __extends(CustomOptimization, _super);
  107327. function CustomOptimization() {
  107328. return _super !== null && _super.apply(this, arguments) || this;
  107329. }
  107330. /**
  107331. * Gets a string describing the action executed by the current optimization
  107332. * @returns description string
  107333. */
  107334. CustomOptimization.prototype.getDescription = function () {
  107335. if (this.onGetDescription) {
  107336. return this.onGetDescription();
  107337. }
  107338. return "Running user defined callback";
  107339. };
  107340. /**
  107341. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107342. * @param scene defines the current scene where to apply this optimization
  107343. * @param optimizer defines the current optimizer
  107344. * @returns true if everything that can be done was applied
  107345. */
  107346. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107347. if (this.onApply) {
  107348. return this.onApply(scene, optimizer);
  107349. }
  107350. return true;
  107351. };
  107352. ;
  107353. return CustomOptimization;
  107354. }(SceneOptimization));
  107355. BABYLON.CustomOptimization = CustomOptimization;
  107356. /**
  107357. * Defines an optimization used to turn particles off
  107358. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107359. */
  107360. var ParticlesOptimization = /** @class */ (function (_super) {
  107361. __extends(ParticlesOptimization, _super);
  107362. function ParticlesOptimization() {
  107363. return _super !== null && _super.apply(this, arguments) || this;
  107364. }
  107365. /**
  107366. * Gets a string describing the action executed by the current optimization
  107367. * @return description string
  107368. */
  107369. ParticlesOptimization.prototype.getDescription = function () {
  107370. return "Turning particles on/off";
  107371. };
  107372. /**
  107373. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107374. * @param scene defines the current scene where to apply this optimization
  107375. * @param optimizer defines the current optimizer
  107376. * @returns true if everything that can be done was applied
  107377. */
  107378. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107379. scene.particlesEnabled = optimizer.isInImprovementMode;
  107380. return true;
  107381. };
  107382. ;
  107383. return ParticlesOptimization;
  107384. }(SceneOptimization));
  107385. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107386. /**
  107387. * Defines an optimization used to turn render targets off
  107388. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107389. */
  107390. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107391. __extends(RenderTargetsOptimization, _super);
  107392. function RenderTargetsOptimization() {
  107393. return _super !== null && _super.apply(this, arguments) || this;
  107394. }
  107395. /**
  107396. * Gets a string describing the action executed by the current optimization
  107397. * @return description string
  107398. */
  107399. RenderTargetsOptimization.prototype.getDescription = function () {
  107400. return "Turning render targets off";
  107401. };
  107402. /**
  107403. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107404. * @param scene defines the current scene where to apply this optimization
  107405. * @param optimizer defines the current optimizer
  107406. * @returns true if everything that can be done was applied
  107407. */
  107408. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107409. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107410. return true;
  107411. };
  107412. ;
  107413. return RenderTargetsOptimization;
  107414. }(SceneOptimization));
  107415. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107416. /**
  107417. * Defines an optimization used to merge meshes with compatible materials
  107418. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107419. */
  107420. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107421. __extends(MergeMeshesOptimization, _super);
  107422. function MergeMeshesOptimization() {
  107423. var _this = _super !== null && _super.apply(this, arguments) || this;
  107424. _this._canBeMerged = function (abstractMesh) {
  107425. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107426. return false;
  107427. }
  107428. var mesh = abstractMesh;
  107429. if (mesh.isDisposed()) {
  107430. return false;
  107431. }
  107432. if (!mesh.isVisible || !mesh.isEnabled()) {
  107433. return false;
  107434. }
  107435. if (mesh.instances.length > 0) {
  107436. return false;
  107437. }
  107438. if (mesh.skeleton || mesh.hasLODLevels) {
  107439. return false;
  107440. }
  107441. return true;
  107442. };
  107443. return _this;
  107444. }
  107445. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107446. /**
  107447. * Gets or sets a boolean which defines if optimization octree has to be updated
  107448. */
  107449. get: function () {
  107450. return MergeMeshesOptimization._UpdateSelectionTree;
  107451. },
  107452. /**
  107453. * Gets or sets a boolean which defines if optimization octree has to be updated
  107454. */
  107455. set: function (value) {
  107456. MergeMeshesOptimization._UpdateSelectionTree = value;
  107457. },
  107458. enumerable: true,
  107459. configurable: true
  107460. });
  107461. /**
  107462. * Gets a string describing the action executed by the current optimization
  107463. * @return description string
  107464. */
  107465. MergeMeshesOptimization.prototype.getDescription = function () {
  107466. return "Merging similar meshes together";
  107467. };
  107468. /**
  107469. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107470. * @param scene defines the current scene where to apply this optimization
  107471. * @param optimizer defines the current optimizer
  107472. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107473. * @returns true if everything that can be done was applied
  107474. */
  107475. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107476. var globalPool = scene.meshes.slice(0);
  107477. var globalLength = globalPool.length;
  107478. for (var index = 0; index < globalLength; index++) {
  107479. var currentPool = new Array();
  107480. var current = globalPool[index];
  107481. // Checks
  107482. if (!this._canBeMerged(current)) {
  107483. continue;
  107484. }
  107485. currentPool.push(current);
  107486. // Find compatible meshes
  107487. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107488. var otherMesh = globalPool[subIndex];
  107489. if (!this._canBeMerged(otherMesh)) {
  107490. continue;
  107491. }
  107492. if (otherMesh.material !== current.material) {
  107493. continue;
  107494. }
  107495. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107496. continue;
  107497. }
  107498. currentPool.push(otherMesh);
  107499. globalLength--;
  107500. globalPool.splice(subIndex, 1);
  107501. subIndex--;
  107502. }
  107503. if (currentPool.length < 2) {
  107504. continue;
  107505. }
  107506. // Merge meshes
  107507. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107508. }
  107509. // Call the octree system optimization if it is defined.
  107510. var sceneAsAny = scene;
  107511. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107512. if (updateSelectionTree != undefined) {
  107513. if (updateSelectionTree) {
  107514. sceneAsAny.createOrUpdateSelectionOctree();
  107515. }
  107516. }
  107517. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107518. sceneAsAny.createOrUpdateSelectionOctree();
  107519. }
  107520. }
  107521. return true;
  107522. };
  107523. ;
  107524. MergeMeshesOptimization._UpdateSelectionTree = false;
  107525. return MergeMeshesOptimization;
  107526. }(SceneOptimization));
  107527. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107528. /**
  107529. * Defines a list of options used by SceneOptimizer
  107530. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107531. */
  107532. var SceneOptimizerOptions = /** @class */ (function () {
  107533. /**
  107534. * Creates a new list of options used by SceneOptimizer
  107535. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107536. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107537. */
  107538. function SceneOptimizerOptions(
  107539. /**
  107540. * Defines the target frame rate to reach (60 by default)
  107541. */
  107542. targetFrameRate,
  107543. /**
  107544. * Defines the interval between two checkes (2000ms by default)
  107545. */
  107546. trackerDuration) {
  107547. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107548. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107549. this.targetFrameRate = targetFrameRate;
  107550. this.trackerDuration = trackerDuration;
  107551. /**
  107552. * Gets the list of optimizations to apply
  107553. */
  107554. this.optimizations = new Array();
  107555. }
  107556. /**
  107557. * Add a new optimization
  107558. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107559. * @returns the current SceneOptimizerOptions
  107560. */
  107561. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107562. this.optimizations.push(optimization);
  107563. return this;
  107564. };
  107565. /**
  107566. * Add a new custom optimization
  107567. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107568. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107569. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107570. * @returns the current SceneOptimizerOptions
  107571. */
  107572. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  107573. if (priority === void 0) { priority = 0; }
  107574. var optimization = new CustomOptimization(priority);
  107575. optimization.onApply = onApply;
  107576. optimization.onGetDescription = onGetDescription;
  107577. this.optimizations.push(optimization);
  107578. return this;
  107579. };
  107580. /**
  107581. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  107582. * @param targetFrameRate defines the target frame rate (60 by default)
  107583. * @returns a SceneOptimizerOptions object
  107584. */
  107585. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  107586. var result = new SceneOptimizerOptions(targetFrameRate);
  107587. var priority = 0;
  107588. result.addOptimization(new MergeMeshesOptimization(priority));
  107589. result.addOptimization(new ShadowsOptimization(priority));
  107590. result.addOptimization(new LensFlaresOptimization(priority));
  107591. // Next priority
  107592. priority++;
  107593. result.addOptimization(new PostProcessesOptimization(priority));
  107594. result.addOptimization(new ParticlesOptimization(priority));
  107595. // Next priority
  107596. priority++;
  107597. result.addOptimization(new TextureOptimization(priority, 1024));
  107598. return result;
  107599. };
  107600. /**
  107601. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  107602. * @param targetFrameRate defines the target frame rate (60 by default)
  107603. * @returns a SceneOptimizerOptions object
  107604. */
  107605. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  107606. var result = new SceneOptimizerOptions(targetFrameRate);
  107607. var priority = 0;
  107608. result.addOptimization(new MergeMeshesOptimization(priority));
  107609. result.addOptimization(new ShadowsOptimization(priority));
  107610. result.addOptimization(new LensFlaresOptimization(priority));
  107611. // Next priority
  107612. priority++;
  107613. result.addOptimization(new PostProcessesOptimization(priority));
  107614. result.addOptimization(new ParticlesOptimization(priority));
  107615. // Next priority
  107616. priority++;
  107617. result.addOptimization(new TextureOptimization(priority, 512));
  107618. // Next priority
  107619. priority++;
  107620. result.addOptimization(new RenderTargetsOptimization(priority));
  107621. // Next priority
  107622. priority++;
  107623. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  107624. return result;
  107625. };
  107626. /**
  107627. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  107628. * @param targetFrameRate defines the target frame rate (60 by default)
  107629. * @returns a SceneOptimizerOptions object
  107630. */
  107631. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  107632. var result = new SceneOptimizerOptions(targetFrameRate);
  107633. var priority = 0;
  107634. result.addOptimization(new MergeMeshesOptimization(priority));
  107635. result.addOptimization(new ShadowsOptimization(priority));
  107636. result.addOptimization(new LensFlaresOptimization(priority));
  107637. // Next priority
  107638. priority++;
  107639. result.addOptimization(new PostProcessesOptimization(priority));
  107640. result.addOptimization(new ParticlesOptimization(priority));
  107641. // Next priority
  107642. priority++;
  107643. result.addOptimization(new TextureOptimization(priority, 256));
  107644. // Next priority
  107645. priority++;
  107646. result.addOptimization(new RenderTargetsOptimization(priority));
  107647. // Next priority
  107648. priority++;
  107649. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  107650. return result;
  107651. };
  107652. return SceneOptimizerOptions;
  107653. }());
  107654. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  107655. /**
  107656. * Class used to run optimizations in order to reach a target frame rate
  107657. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107658. */
  107659. var SceneOptimizer = /** @class */ (function () {
  107660. /**
  107661. * Creates a new SceneOptimizer
  107662. * @param scene defines the scene to work on
  107663. * @param options defines the options to use with the SceneOptimizer
  107664. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  107665. * @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)
  107666. */
  107667. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  107668. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  107669. if (improvementMode === void 0) { improvementMode = false; }
  107670. var _this = this;
  107671. this._isRunning = false;
  107672. this._currentPriorityLevel = 0;
  107673. this._targetFrameRate = 60;
  107674. this._trackerDuration = 2000;
  107675. this._currentFrameRate = 0;
  107676. this._improvementMode = false;
  107677. /**
  107678. * Defines an observable called when the optimizer reaches the target frame rate
  107679. */
  107680. this.onSuccessObservable = new BABYLON.Observable();
  107681. /**
  107682. * Defines an observable called when the optimizer enables an optimization
  107683. */
  107684. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  107685. /**
  107686. * Defines an observable called when the optimizer is not able to reach the target frame rate
  107687. */
  107688. this.onFailureObservable = new BABYLON.Observable();
  107689. if (!options) {
  107690. this._options = new SceneOptimizerOptions();
  107691. }
  107692. else {
  107693. this._options = options;
  107694. }
  107695. if (this._options.targetFrameRate) {
  107696. this._targetFrameRate = this._options.targetFrameRate;
  107697. }
  107698. if (this._options.trackerDuration) {
  107699. this._trackerDuration = this._options.trackerDuration;
  107700. }
  107701. if (autoGeneratePriorities) {
  107702. var priority = 0;
  107703. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  107704. var optim = _a[_i];
  107705. optim.priority = priority++;
  107706. }
  107707. }
  107708. this._improvementMode = improvementMode;
  107709. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107710. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  107711. _this._sceneDisposeObserver = null;
  107712. _this.dispose();
  107713. });
  107714. }
  107715. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  107716. /**
  107717. * Gets a boolean indicating if the optimizer is in improvement mode
  107718. */
  107719. get: function () {
  107720. return this._improvementMode;
  107721. },
  107722. enumerable: true,
  107723. configurable: true
  107724. });
  107725. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  107726. /**
  107727. * Gets the current priority level (0 at start)
  107728. */
  107729. get: function () {
  107730. return this._currentPriorityLevel;
  107731. },
  107732. enumerable: true,
  107733. configurable: true
  107734. });
  107735. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  107736. /**
  107737. * Gets the current frame rate checked by the SceneOptimizer
  107738. */
  107739. get: function () {
  107740. return this._currentFrameRate;
  107741. },
  107742. enumerable: true,
  107743. configurable: true
  107744. });
  107745. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  107746. /**
  107747. * Gets or sets the current target frame rate (60 by default)
  107748. */
  107749. get: function () {
  107750. return this._targetFrameRate;
  107751. },
  107752. /**
  107753. * Gets or sets the current target frame rate (60 by default)
  107754. */
  107755. set: function (value) {
  107756. this._targetFrameRate = value;
  107757. },
  107758. enumerable: true,
  107759. configurable: true
  107760. });
  107761. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  107762. /**
  107763. * Gets or sets the current interval between two checks (every 2000ms by default)
  107764. */
  107765. get: function () {
  107766. return this._trackerDuration;
  107767. },
  107768. /**
  107769. * Gets or sets the current interval between two checks (every 2000ms by default)
  107770. */
  107771. set: function (value) {
  107772. this._trackerDuration = value;
  107773. },
  107774. enumerable: true,
  107775. configurable: true
  107776. });
  107777. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  107778. /**
  107779. * Gets the list of active optimizations
  107780. */
  107781. get: function () {
  107782. return this._options.optimizations;
  107783. },
  107784. enumerable: true,
  107785. configurable: true
  107786. });
  107787. /**
  107788. * Stops the current optimizer
  107789. */
  107790. SceneOptimizer.prototype.stop = function () {
  107791. this._isRunning = false;
  107792. };
  107793. /**
  107794. * Reset the optimizer to initial step (current priority level = 0)
  107795. */
  107796. SceneOptimizer.prototype.reset = function () {
  107797. this._currentPriorityLevel = 0;
  107798. };
  107799. /**
  107800. * Start the optimizer. By default it will try to reach a specific framerate
  107801. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  107802. */
  107803. SceneOptimizer.prototype.start = function () {
  107804. var _this = this;
  107805. if (this._isRunning) {
  107806. return;
  107807. }
  107808. this._isRunning = true;
  107809. // Let's wait for the scene to be ready before running our check
  107810. this._scene.executeWhenReady(function () {
  107811. setTimeout(function () {
  107812. _this._checkCurrentState();
  107813. }, _this._trackerDuration);
  107814. });
  107815. };
  107816. SceneOptimizer.prototype._checkCurrentState = function () {
  107817. var _this = this;
  107818. if (!this._isRunning) {
  107819. return;
  107820. }
  107821. var scene = this._scene;
  107822. var options = this._options;
  107823. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  107824. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  107825. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  107826. this._isRunning = false;
  107827. this.onSuccessObservable.notifyObservers(this);
  107828. return;
  107829. }
  107830. // Apply current level of optimizations
  107831. var allDone = true;
  107832. var noOptimizationApplied = true;
  107833. for (var index = 0; index < options.optimizations.length; index++) {
  107834. var optimization = options.optimizations[index];
  107835. if (optimization.priority === this._currentPriorityLevel) {
  107836. noOptimizationApplied = false;
  107837. allDone = allDone && optimization.apply(scene, this);
  107838. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  107839. }
  107840. }
  107841. // If no optimization was applied, this is a failure :(
  107842. if (noOptimizationApplied) {
  107843. this._isRunning = false;
  107844. this.onFailureObservable.notifyObservers(this);
  107845. return;
  107846. }
  107847. // If all optimizations were done, move to next level
  107848. if (allDone) {
  107849. this._currentPriorityLevel++;
  107850. }
  107851. // Let's the system running for a specific amount of time before checking FPS
  107852. scene.executeWhenReady(function () {
  107853. setTimeout(function () {
  107854. _this._checkCurrentState();
  107855. }, _this._trackerDuration);
  107856. });
  107857. };
  107858. /**
  107859. * Release all resources
  107860. */
  107861. SceneOptimizer.prototype.dispose = function () {
  107862. this.stop();
  107863. this.onSuccessObservable.clear();
  107864. this.onFailureObservable.clear();
  107865. this.onNewOptimizationAppliedObservable.clear();
  107866. if (this._sceneDisposeObserver) {
  107867. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  107868. }
  107869. };
  107870. /**
  107871. * Helper function to create a SceneOptimizer with one single line of code
  107872. * @param scene defines the scene to work on
  107873. * @param options defines the options to use with the SceneOptimizer
  107874. * @param onSuccess defines a callback to call on success
  107875. * @param onFailure defines a callback to call on failure
  107876. * @returns the new SceneOptimizer object
  107877. */
  107878. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  107879. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  107880. if (onSuccess) {
  107881. optimizer.onSuccessObservable.add(function () {
  107882. onSuccess();
  107883. });
  107884. }
  107885. if (onFailure) {
  107886. optimizer.onFailureObservable.add(function () {
  107887. onFailure();
  107888. });
  107889. }
  107890. optimizer.start();
  107891. return optimizer;
  107892. };
  107893. return SceneOptimizer;
  107894. }());
  107895. BABYLON.SceneOptimizer = SceneOptimizer;
  107896. })(BABYLON || (BABYLON = {}));
  107897. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  107898. var BABYLON;
  107899. (function (BABYLON) {
  107900. /**
  107901. * Gets the outline renderer associated with the scene
  107902. * @returns a OutlineRenderer
  107903. */
  107904. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  107905. if (!this._outlineRenderer) {
  107906. this._outlineRenderer = new OutlineRenderer(this);
  107907. }
  107908. return this._outlineRenderer;
  107909. };
  107910. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  107911. get: function () {
  107912. return this._renderOutline;
  107913. },
  107914. set: function (value) {
  107915. if (value) {
  107916. // Lazy Load the component.
  107917. this.getScene().getOutlineRenderer();
  107918. }
  107919. this._renderOutline = value;
  107920. },
  107921. enumerable: true,
  107922. configurable: true
  107923. });
  107924. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  107925. get: function () {
  107926. return this._renderOverlay;
  107927. },
  107928. set: function (value) {
  107929. if (value) {
  107930. // Lazy Load the component.
  107931. this.getScene().getOutlineRenderer();
  107932. }
  107933. this._renderOverlay = value;
  107934. },
  107935. enumerable: true,
  107936. configurable: true
  107937. });
  107938. /**
  107939. * This class is responsible to draw bothe outline/overlay of meshes.
  107940. * It should not be used directly but through the available method on mesh.
  107941. */
  107942. var OutlineRenderer = /** @class */ (function () {
  107943. /**
  107944. * Instantiates a new outline renderer. (There could be only one per scene).
  107945. * @param scene Defines the scene it belongs to
  107946. */
  107947. function OutlineRenderer(scene) {
  107948. /**
  107949. * The name of the component. Each component must have a unique name.
  107950. */
  107951. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  107952. /**
  107953. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  107954. */
  107955. this.zOffset = 1;
  107956. this.scene = scene;
  107957. this._engine = scene.getEngine();
  107958. this.scene._addComponent(this);
  107959. }
  107960. /**
  107961. * Register the component to one instance of a scene.
  107962. */
  107963. OutlineRenderer.prototype.register = function () {
  107964. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  107965. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  107966. };
  107967. /**
  107968. * Rebuilds the elements related to this component in case of
  107969. * context lost for instance.
  107970. */
  107971. OutlineRenderer.prototype.rebuild = function () {
  107972. // Nothing to do here.
  107973. };
  107974. /**
  107975. * Disposes the component and the associated ressources.
  107976. */
  107977. OutlineRenderer.prototype.dispose = function () {
  107978. // Nothing to do here.
  107979. };
  107980. /**
  107981. * Renders the outline in the canvas.
  107982. * @param subMesh Defines the sumesh to render
  107983. * @param batch Defines the batch of meshes in case of instances
  107984. * @param useOverlay Defines if the rendering is for the overlay or the outline
  107985. */
  107986. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  107987. var _this = this;
  107988. if (useOverlay === void 0) { useOverlay = false; }
  107989. var scene = this.scene;
  107990. var engine = scene.getEngine();
  107991. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  107992. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  107993. return;
  107994. }
  107995. var mesh = subMesh.getRenderingMesh();
  107996. var material = subMesh.getMaterial();
  107997. if (!material || !scene.activeCamera) {
  107998. return;
  107999. }
  108000. engine.enableEffect(this._effect);
  108001. // Logarithmic depth
  108002. if (material.useLogarithmicDepth) {
  108003. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  108004. }
  108005. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  108006. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  108007. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  108008. // Bones
  108009. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  108010. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  108011. }
  108012. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  108013. // Alpha test
  108014. if (material && material.needAlphaTesting()) {
  108015. var alphaTexture = material.getAlphaTestTexture();
  108016. if (alphaTexture) {
  108017. this._effect.setTexture("diffuseSampler", alphaTexture);
  108018. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  108019. }
  108020. }
  108021. engine.setZOffset(-this.zOffset);
  108022. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  108023. engine.setZOffset(0);
  108024. };
  108025. /**
  108026. * Returns whether or not the outline renderer is ready for a given submesh.
  108027. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  108028. * @param subMesh Defines the submesh to check readyness for
  108029. * @param useInstances Defines wheter wee are trying to render instances or not
  108030. * @returns true if ready otherwise false
  108031. */
  108032. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108033. var defines = [];
  108034. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108035. var mesh = subMesh.getMesh();
  108036. var material = subMesh.getMaterial();
  108037. if (material) {
  108038. // Alpha test
  108039. if (material.needAlphaTesting()) {
  108040. defines.push("#define ALPHATEST");
  108041. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108042. attribs.push(BABYLON.VertexBuffer.UVKind);
  108043. defines.push("#define UV1");
  108044. }
  108045. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108047. defines.push("#define UV2");
  108048. }
  108049. }
  108050. //Logarithmic depth
  108051. if (material.useLogarithmicDepth) {
  108052. defines.push("#define LOGARITHMICDEPTH");
  108053. }
  108054. }
  108055. // Bones
  108056. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108057. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108058. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108059. if (mesh.numBoneInfluencers > 4) {
  108060. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108061. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108062. }
  108063. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108064. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108065. }
  108066. else {
  108067. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108068. }
  108069. // Instances
  108070. if (useInstances) {
  108071. defines.push("#define INSTANCES");
  108072. attribs.push("world0");
  108073. attribs.push("world1");
  108074. attribs.push("world2");
  108075. attribs.push("world3");
  108076. }
  108077. // Get correct effect
  108078. var join = defines.join("\n");
  108079. if (this._cachedDefines !== join) {
  108080. this._cachedDefines = join;
  108081. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108082. }
  108083. return this._effect.isReady();
  108084. };
  108085. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108086. // Outline - step 1
  108087. this._savedDepthWrite = this._engine.getDepthWrite();
  108088. if (mesh.renderOutline) {
  108089. this._engine.setDepthWrite(false);
  108090. this.render(subMesh, batch);
  108091. this._engine.setDepthWrite(this._savedDepthWrite);
  108092. }
  108093. };
  108094. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108095. // Outline - step 2
  108096. if (mesh.renderOutline && this._savedDepthWrite) {
  108097. this._engine.setDepthWrite(true);
  108098. this._engine.setColorWrite(false);
  108099. this.render(subMesh, batch);
  108100. this._engine.setColorWrite(true);
  108101. }
  108102. // Overlay
  108103. if (mesh.renderOverlay) {
  108104. var currentMode = this._engine.getAlphaMode();
  108105. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108106. this.render(subMesh, batch, true);
  108107. this._engine.setAlphaMode(currentMode);
  108108. }
  108109. };
  108110. return OutlineRenderer;
  108111. }());
  108112. BABYLON.OutlineRenderer = OutlineRenderer;
  108113. })(BABYLON || (BABYLON = {}));
  108114. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108115. var BABYLON;
  108116. (function (BABYLON) {
  108117. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108118. if (this._edgesRenderer) {
  108119. this._edgesRenderer.dispose();
  108120. this._edgesRenderer = null;
  108121. }
  108122. return this;
  108123. };
  108124. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108125. if (epsilon === void 0) { epsilon = 0.95; }
  108126. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108127. this.disableEdgesRendering();
  108128. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108129. return this;
  108130. };
  108131. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108132. get: function () {
  108133. return this._edgesRenderer;
  108134. },
  108135. enumerable: true,
  108136. configurable: true
  108137. });
  108138. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108139. if (epsilon === void 0) { epsilon = 0.95; }
  108140. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108141. this.disableEdgesRendering();
  108142. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108143. return this;
  108144. };
  108145. /**
  108146. * FaceAdjacencies Helper class to generate edges
  108147. */
  108148. var FaceAdjacencies = /** @class */ (function () {
  108149. function FaceAdjacencies() {
  108150. this.edges = new Array();
  108151. this.edgesConnectedCount = 0;
  108152. }
  108153. return FaceAdjacencies;
  108154. }());
  108155. /**
  108156. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108157. */
  108158. var EdgesRenderer = /** @class */ (function () {
  108159. /**
  108160. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108161. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108162. * @param source Mesh used to create edges
  108163. * @param epsilon sum of angles in adjacency to check for edge
  108164. * @param checkVerticesInsteadOfIndices
  108165. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108166. */
  108167. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108168. if (epsilon === void 0) { epsilon = 0.95; }
  108169. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108170. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108171. var _this = this;
  108172. /**
  108173. * Define the size of the edges with an orthographic camera
  108174. */
  108175. this.edgesWidthScalerForOrthographic = 1000.0;
  108176. /**
  108177. * Define the size of the edges with a perspective camera
  108178. */
  108179. this.edgesWidthScalerForPerspective = 50.0;
  108180. this._linesPositions = new Array();
  108181. this._linesNormals = new Array();
  108182. this._linesIndices = new Array();
  108183. this._buffers = {};
  108184. this._checkVerticesInsteadOfIndices = false;
  108185. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108186. this.isEnabled = true;
  108187. this._source = source;
  108188. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108189. this._epsilon = epsilon;
  108190. this._prepareRessources();
  108191. if (generateEdgesLines) {
  108192. this._generateEdgesLines();
  108193. }
  108194. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108195. _this._rebuild();
  108196. });
  108197. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108198. _this.dispose();
  108199. });
  108200. }
  108201. EdgesRenderer.prototype._prepareRessources = function () {
  108202. if (this._lineShader) {
  108203. return;
  108204. }
  108205. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108206. attributes: ["position", "normal"],
  108207. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108208. });
  108209. this._lineShader.disableDepthWrite = true;
  108210. this._lineShader.backFaceCulling = false;
  108211. };
  108212. /** @hidden */
  108213. EdgesRenderer.prototype._rebuild = function () {
  108214. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108215. if (buffer) {
  108216. buffer._rebuild();
  108217. }
  108218. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108219. if (buffer) {
  108220. buffer._rebuild();
  108221. }
  108222. var scene = this._source.getScene();
  108223. var engine = scene.getEngine();
  108224. this._ib = engine.createIndexBuffer(this._linesIndices);
  108225. };
  108226. /**
  108227. * Releases the required resources for the edges renderer
  108228. */
  108229. EdgesRenderer.prototype.dispose = function () {
  108230. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108231. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108232. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108233. if (buffer) {
  108234. buffer.dispose();
  108235. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108236. }
  108237. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108238. if (buffer) {
  108239. buffer.dispose();
  108240. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108241. }
  108242. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108243. this._lineShader.dispose();
  108244. };
  108245. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108246. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108247. return 0;
  108248. }
  108249. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108250. return 1;
  108251. }
  108252. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108253. return 2;
  108254. }
  108255. return -1;
  108256. };
  108257. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108258. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108259. return 0;
  108260. }
  108261. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108262. return 1;
  108263. }
  108264. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108265. return 2;
  108266. }
  108267. return -1;
  108268. };
  108269. /**
  108270. * Checks if the pair of p0 and p1 is en edge
  108271. * @param faceIndex
  108272. * @param edge
  108273. * @param faceNormals
  108274. * @param p0
  108275. * @param p1
  108276. * @private
  108277. */
  108278. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108279. var needToCreateLine;
  108280. if (edge === undefined) {
  108281. needToCreateLine = true;
  108282. }
  108283. else {
  108284. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108285. needToCreateLine = dotProduct < this._epsilon;
  108286. }
  108287. if (needToCreateLine) {
  108288. var offset = this._linesPositions.length / 3;
  108289. var normal = p0.subtract(p1);
  108290. normal.normalize();
  108291. // Positions
  108292. this._linesPositions.push(p0.x);
  108293. this._linesPositions.push(p0.y);
  108294. this._linesPositions.push(p0.z);
  108295. this._linesPositions.push(p0.x);
  108296. this._linesPositions.push(p0.y);
  108297. this._linesPositions.push(p0.z);
  108298. this._linesPositions.push(p1.x);
  108299. this._linesPositions.push(p1.y);
  108300. this._linesPositions.push(p1.z);
  108301. this._linesPositions.push(p1.x);
  108302. this._linesPositions.push(p1.y);
  108303. this._linesPositions.push(p1.z);
  108304. // Normals
  108305. this._linesNormals.push(p1.x);
  108306. this._linesNormals.push(p1.y);
  108307. this._linesNormals.push(p1.z);
  108308. this._linesNormals.push(-1);
  108309. this._linesNormals.push(p1.x);
  108310. this._linesNormals.push(p1.y);
  108311. this._linesNormals.push(p1.z);
  108312. this._linesNormals.push(1);
  108313. this._linesNormals.push(p0.x);
  108314. this._linesNormals.push(p0.y);
  108315. this._linesNormals.push(p0.z);
  108316. this._linesNormals.push(-1);
  108317. this._linesNormals.push(p0.x);
  108318. this._linesNormals.push(p0.y);
  108319. this._linesNormals.push(p0.z);
  108320. this._linesNormals.push(1);
  108321. // Indices
  108322. this._linesIndices.push(offset);
  108323. this._linesIndices.push(offset + 1);
  108324. this._linesIndices.push(offset + 2);
  108325. this._linesIndices.push(offset);
  108326. this._linesIndices.push(offset + 2);
  108327. this._linesIndices.push(offset + 3);
  108328. }
  108329. };
  108330. /**
  108331. * Generates lines edges from adjacencjes
  108332. * @private
  108333. */
  108334. EdgesRenderer.prototype._generateEdgesLines = function () {
  108335. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108336. var indices = this._source.getIndices();
  108337. if (!indices || !positions) {
  108338. return;
  108339. }
  108340. // First let's find adjacencies
  108341. var adjacencies = new Array();
  108342. var faceNormals = new Array();
  108343. var index;
  108344. var faceAdjacencies;
  108345. // Prepare faces
  108346. for (index = 0; index < indices.length; index += 3) {
  108347. faceAdjacencies = new FaceAdjacencies();
  108348. var p0Index = indices[index];
  108349. var p1Index = indices[index + 1];
  108350. var p2Index = indices[index + 2];
  108351. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108352. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108353. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108354. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108355. faceNormal.normalize();
  108356. faceNormals.push(faceNormal);
  108357. adjacencies.push(faceAdjacencies);
  108358. }
  108359. // Scan
  108360. for (index = 0; index < adjacencies.length; index++) {
  108361. faceAdjacencies = adjacencies[index];
  108362. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108363. var otherFaceAdjacencies = adjacencies[otherIndex];
  108364. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108365. break;
  108366. }
  108367. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108368. continue;
  108369. }
  108370. var otherP0 = indices[otherIndex * 3];
  108371. var otherP1 = indices[otherIndex * 3 + 1];
  108372. var otherP2 = indices[otherIndex * 3 + 2];
  108373. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108374. var otherEdgeIndex = 0;
  108375. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108376. continue;
  108377. }
  108378. switch (edgeIndex) {
  108379. case 0:
  108380. if (this._checkVerticesInsteadOfIndices) {
  108381. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108382. }
  108383. else {
  108384. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108385. }
  108386. break;
  108387. case 1:
  108388. if (this._checkVerticesInsteadOfIndices) {
  108389. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108390. }
  108391. else {
  108392. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108393. }
  108394. break;
  108395. case 2:
  108396. if (this._checkVerticesInsteadOfIndices) {
  108397. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108398. }
  108399. else {
  108400. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108401. }
  108402. break;
  108403. }
  108404. if (otherEdgeIndex === -1) {
  108405. continue;
  108406. }
  108407. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108408. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108409. faceAdjacencies.edgesConnectedCount++;
  108410. otherFaceAdjacencies.edgesConnectedCount++;
  108411. if (faceAdjacencies.edgesConnectedCount === 3) {
  108412. break;
  108413. }
  108414. }
  108415. }
  108416. }
  108417. // Create lines
  108418. for (index = 0; index < adjacencies.length; index++) {
  108419. // 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
  108420. var current = adjacencies[index];
  108421. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108422. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108423. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108424. }
  108425. // Merge into a single mesh
  108426. var engine = this._source.getScene().getEngine();
  108427. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108428. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108429. this._ib = engine.createIndexBuffer(this._linesIndices);
  108430. this._indicesCount = this._linesIndices.length;
  108431. };
  108432. /**
  108433. * Checks wether or not the edges renderer is ready to render.
  108434. * @return true if ready, otherwise false.
  108435. */
  108436. EdgesRenderer.prototype.isReady = function () {
  108437. return this._lineShader.isReady();
  108438. };
  108439. /**
  108440. * Renders the edges of the attached mesh,
  108441. */
  108442. EdgesRenderer.prototype.render = function () {
  108443. var scene = this._source.getScene();
  108444. if (!this.isReady() || !scene.activeCamera) {
  108445. return;
  108446. }
  108447. var engine = scene.getEngine();
  108448. this._lineShader._preBind();
  108449. if (this._source.edgesColor.a !== 1) {
  108450. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108451. }
  108452. else {
  108453. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108454. }
  108455. // VBOs
  108456. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108457. scene.resetCachedMaterial();
  108458. this._lineShader.setColor4("color", this._source.edgesColor);
  108459. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108460. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108461. }
  108462. else {
  108463. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108464. }
  108465. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108466. this._lineShader.bind(this._source.getWorldMatrix());
  108467. // Draw order
  108468. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108469. this._lineShader.unbind();
  108470. };
  108471. return EdgesRenderer;
  108472. }());
  108473. BABYLON.EdgesRenderer = EdgesRenderer;
  108474. })(BABYLON || (BABYLON = {}));
  108475. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108476. var BABYLON;
  108477. (function (BABYLON) {
  108478. /**
  108479. * FaceAdjacencies Helper class to generate edges
  108480. */
  108481. var FaceAdjacencies = /** @class */ (function () {
  108482. function FaceAdjacencies() {
  108483. this.edges = new Array();
  108484. this.edgesConnectedCount = 0;
  108485. }
  108486. return FaceAdjacencies;
  108487. }());
  108488. /**
  108489. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108490. */
  108491. var LineEdgesRenderer = /** @class */ (function (_super) {
  108492. __extends(LineEdgesRenderer, _super);
  108493. /**
  108494. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108495. * @param source LineMesh used to generate edges
  108496. * @param epsilon not important (specified angle for edge detection)
  108497. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108498. */
  108499. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108500. if (epsilon === void 0) { epsilon = 0.95; }
  108501. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108502. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108503. _this._generateEdgesLines();
  108504. return _this;
  108505. }
  108506. /**
  108507. * Always create the edge since its a line so only important things are p0 and p1
  108508. * @param faceIndex not important for LineMesh
  108509. * @param edge not important for LineMesh
  108510. * @param faceNormals not important for LineMesh
  108511. * @param p0 beginnig of line
  108512. * @param p1 end of line
  108513. */
  108514. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108515. var offset = this._linesPositions.length / 3;
  108516. var normal = p0.subtract(p1);
  108517. normal.normalize();
  108518. // Positions
  108519. this._linesPositions.push(p0.x);
  108520. this._linesPositions.push(p0.y);
  108521. this._linesPositions.push(p0.z);
  108522. this._linesPositions.push(p0.x);
  108523. this._linesPositions.push(p0.y);
  108524. this._linesPositions.push(p0.z);
  108525. this._linesPositions.push(p1.x);
  108526. this._linesPositions.push(p1.y);
  108527. this._linesPositions.push(p1.z);
  108528. this._linesPositions.push(p1.x);
  108529. this._linesPositions.push(p1.y);
  108530. this._linesPositions.push(p1.z);
  108531. // Normals
  108532. this._linesNormals.push(p1.x);
  108533. this._linesNormals.push(p1.y);
  108534. this._linesNormals.push(p1.z);
  108535. this._linesNormals.push(-1);
  108536. this._linesNormals.push(p1.x);
  108537. this._linesNormals.push(p1.y);
  108538. this._linesNormals.push(p1.z);
  108539. this._linesNormals.push(1);
  108540. this._linesNormals.push(p0.x);
  108541. this._linesNormals.push(p0.y);
  108542. this._linesNormals.push(p0.z);
  108543. this._linesNormals.push(-1);
  108544. this._linesNormals.push(p0.x);
  108545. this._linesNormals.push(p0.y);
  108546. this._linesNormals.push(p0.z);
  108547. this._linesNormals.push(1);
  108548. // Indices
  108549. this._linesIndices.push(offset);
  108550. this._linesIndices.push(offset + 1);
  108551. this._linesIndices.push(offset + 2);
  108552. this._linesIndices.push(offset);
  108553. this._linesIndices.push(offset + 2);
  108554. this._linesIndices.push(offset + 3);
  108555. };
  108556. /**
  108557. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108558. */
  108559. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108560. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108561. var indices = this._source.getIndices();
  108562. if (!indices || !positions) {
  108563. return;
  108564. }
  108565. // First let's find adjacencies
  108566. var adjacencies = new Array();
  108567. var faceNormals = new Array();
  108568. var index;
  108569. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108570. var currentAdjecancy = new FaceAdjacencies();
  108571. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  108572. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  108573. adjacencies.push(currentAdjecancy);
  108574. }
  108575. // Create lines
  108576. for (index = 0; index < adjacencies.length; index++) {
  108577. // 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
  108578. var current = adjacencies[index];
  108579. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108580. }
  108581. // Merge into a single mesh
  108582. var engine = this._source.getScene().getEngine();
  108583. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108584. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108585. this._ib = engine.createIndexBuffer(this._linesIndices);
  108586. this._indicesCount = this._linesIndices.length;
  108587. };
  108588. return LineEdgesRenderer;
  108589. }(BABYLON.EdgesRenderer));
  108590. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  108591. })(BABYLON || (BABYLON = {}));
  108592. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  108593. var BABYLON;
  108594. (function (BABYLON) {
  108595. // Adds the parser to the scene parsers.
  108596. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  108597. if (parsedData.effectLayers) {
  108598. if (!container.effectLayers) {
  108599. container.effectLayers = new Array();
  108600. }
  108601. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  108602. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  108603. container.effectLayers.push(effectLayer);
  108604. }
  108605. }
  108606. });
  108607. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  108608. var index = this.effectLayers.indexOf(toRemove);
  108609. if (index !== -1) {
  108610. this.effectLayers.splice(index, 1);
  108611. }
  108612. return index;
  108613. };
  108614. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  108615. this.effectLayers.push(newEffectLayer);
  108616. };
  108617. /**
  108618. * Defines the layer scene component responsible to manage any effect layers
  108619. * in a given scene.
  108620. */
  108621. var EffectLayerSceneComponent = /** @class */ (function () {
  108622. /**
  108623. * Creates a new instance of the component for the given scene
  108624. * @param scene Defines the scene to register the component in
  108625. */
  108626. function EffectLayerSceneComponent(scene) {
  108627. /**
  108628. * The component name helpfull to identify the component in the list of scene components.
  108629. */
  108630. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  108631. this._renderEffects = false;
  108632. this._needStencil = false;
  108633. this._previousStencilState = false;
  108634. this.scene = scene;
  108635. this._engine = scene.getEngine();
  108636. scene.effectLayers = new Array();
  108637. }
  108638. /**
  108639. * Registers the component in a given scene
  108640. */
  108641. EffectLayerSceneComponent.prototype.register = function () {
  108642. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  108643. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  108644. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  108645. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  108646. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  108647. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  108648. };
  108649. /**
  108650. * Rebuilds the elements related to this component in case of
  108651. * context lost for instance.
  108652. */
  108653. EffectLayerSceneComponent.prototype.rebuild = function () {
  108654. var layers = this.scene.effectLayers;
  108655. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108656. var effectLayer = layers_1[_i];
  108657. effectLayer._rebuild();
  108658. }
  108659. };
  108660. /**
  108661. * Serializes the component data to the specified json object
  108662. * @param serializationObject The object to serialize to
  108663. */
  108664. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  108665. // Effect layers
  108666. serializationObject.effectLayers = [];
  108667. var layers = this.scene.effectLayers;
  108668. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108669. var effectLayer = layers_2[_i];
  108670. if (effectLayer.serialize) {
  108671. serializationObject.effectLayers.push(effectLayer.serialize());
  108672. }
  108673. }
  108674. };
  108675. /**
  108676. * Adds all the element from the container to the scene
  108677. * @param container the container holding the elements
  108678. */
  108679. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  108680. var _this = this;
  108681. if (!container.effectLayers) {
  108682. return;
  108683. }
  108684. container.effectLayers.forEach(function (o) {
  108685. _this.scene.addEffectLayer(o);
  108686. });
  108687. };
  108688. /**
  108689. * Removes all the elements in the container from the scene
  108690. * @param container contains the elements to remove
  108691. */
  108692. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  108693. var _this = this;
  108694. if (!container.effectLayers) {
  108695. return;
  108696. }
  108697. container.effectLayers.forEach(function (o) {
  108698. _this.scene.removeEffectLayer(o);
  108699. });
  108700. };
  108701. /**
  108702. * Disposes the component and the associated ressources.
  108703. */
  108704. EffectLayerSceneComponent.prototype.dispose = function () {
  108705. var layers = this.scene.effectLayers;
  108706. while (layers.length) {
  108707. layers[0].dispose();
  108708. }
  108709. };
  108710. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  108711. var layers = this.scene.effectLayers;
  108712. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  108713. var layer = layers_3[_i];
  108714. if (!layer.hasMesh(mesh)) {
  108715. continue;
  108716. }
  108717. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  108718. var subMesh = _b[_a];
  108719. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  108720. return false;
  108721. }
  108722. }
  108723. }
  108724. return true;
  108725. };
  108726. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  108727. this._renderEffects = false;
  108728. this._needStencil = false;
  108729. var layers = this.scene.effectLayers;
  108730. if (layers && layers.length > 0) {
  108731. this._previousStencilState = this._engine.getStencilBuffer();
  108732. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  108733. var effectLayer = layers_4[_i];
  108734. if (effectLayer.shouldRender() &&
  108735. (!effectLayer.camera ||
  108736. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  108737. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  108738. this._renderEffects = true;
  108739. this._needStencil = this._needStencil || effectLayer.needStencil();
  108740. var renderTarget = effectLayer._mainTexture;
  108741. if (renderTarget._shouldRender()) {
  108742. this.scene.incrementRenderId();
  108743. renderTarget.render(false, false);
  108744. }
  108745. }
  108746. }
  108747. this.scene.incrementRenderId();
  108748. }
  108749. };
  108750. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  108751. // Activate effect Layer stencil
  108752. if (this._needStencil) {
  108753. this._engine.setStencilBuffer(true);
  108754. }
  108755. };
  108756. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  108757. // Restore effect Layer stencil
  108758. if (this._needStencil) {
  108759. this._engine.setStencilBuffer(this._previousStencilState);
  108760. }
  108761. };
  108762. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  108763. if (this._renderEffects) {
  108764. this._engine.setDepthBuffer(false);
  108765. var layers = this.scene.effectLayers;
  108766. for (var i = 0; i < layers.length; i++) {
  108767. var effectLayer = layers[i];
  108768. if (effectLayer.renderingGroupId === renderingGroupId) {
  108769. if (effectLayer.shouldRender()) {
  108770. effectLayer.render();
  108771. }
  108772. }
  108773. }
  108774. this._engine.setDepthBuffer(true);
  108775. }
  108776. };
  108777. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  108778. if (this._renderEffects) {
  108779. this._draw(-1);
  108780. }
  108781. };
  108782. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  108783. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  108784. this._draw(index);
  108785. }
  108786. };
  108787. return EffectLayerSceneComponent;
  108788. }());
  108789. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  108790. })(BABYLON || (BABYLON = {}));
  108791. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  108792. var __assign = (this && this.__assign) || function () {
  108793. __assign = Object.assign || function(t) {
  108794. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108795. s = arguments[i];
  108796. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108797. t[p] = s[p];
  108798. }
  108799. return t;
  108800. };
  108801. return __assign.apply(this, arguments);
  108802. };
  108803. var BABYLON;
  108804. (function (BABYLON) {
  108805. /**
  108806. * The effect layer Helps adding post process effect blended with the main pass.
  108807. *
  108808. * This can be for instance use to generate glow or higlight effects on the scene.
  108809. *
  108810. * The effect layer class can not be used directly and is intented to inherited from to be
  108811. * customized per effects.
  108812. */
  108813. var EffectLayer = /** @class */ (function () {
  108814. /**
  108815. * Instantiates a new effect Layer and references it in the scene.
  108816. * @param name The name of the layer
  108817. * @param scene The scene to use the layer in
  108818. */
  108819. function EffectLayer(
  108820. /** The Friendly of the effect in the scene */
  108821. name, scene) {
  108822. this._vertexBuffers = {};
  108823. this._maxSize = 0;
  108824. this._mainTextureDesiredSize = { width: 0, height: 0 };
  108825. this._shouldRender = true;
  108826. this._postProcesses = [];
  108827. this._textures = [];
  108828. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  108829. /**
  108830. * The clear color of the texture used to generate the glow map.
  108831. */
  108832. this.neutralColor = new BABYLON.Color4();
  108833. /**
  108834. * Specifies wether the highlight layer is enabled or not.
  108835. */
  108836. this.isEnabled = true;
  108837. /**
  108838. * An event triggered when the effect layer has been disposed.
  108839. */
  108840. this.onDisposeObservable = new BABYLON.Observable();
  108841. /**
  108842. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  108843. */
  108844. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  108845. /**
  108846. * An event triggered when the generated texture is being merged in the scene.
  108847. */
  108848. this.onBeforeComposeObservable = new BABYLON.Observable();
  108849. /**
  108850. * An event triggered when the generated texture has been merged in the scene.
  108851. */
  108852. this.onAfterComposeObservable = new BABYLON.Observable();
  108853. /**
  108854. * An event triggered when the efffect layer changes its size.
  108855. */
  108856. this.onSizeChangedObservable = new BABYLON.Observable();
  108857. this.name = name;
  108858. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108859. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  108860. if (!component) {
  108861. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  108862. this._scene._addComponent(component);
  108863. }
  108864. this._engine = this._scene.getEngine();
  108865. this._maxSize = this._engine.getCaps().maxTextureSize;
  108866. this._scene.effectLayers.push(this);
  108867. // Generate Buffers
  108868. this._generateIndexBuffer();
  108869. this._genrateVertexBuffer();
  108870. }
  108871. Object.defineProperty(EffectLayer.prototype, "camera", {
  108872. /**
  108873. * Gets the camera attached to the layer.
  108874. */
  108875. get: function () {
  108876. return this._effectLayerOptions.camera;
  108877. },
  108878. enumerable: true,
  108879. configurable: true
  108880. });
  108881. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  108882. /**
  108883. * Gets the rendering group id the layer should render in.
  108884. */
  108885. get: function () {
  108886. return this._effectLayerOptions.renderingGroupId;
  108887. },
  108888. enumerable: true,
  108889. configurable: true
  108890. });
  108891. /**
  108892. * Initializes the effect layer with the required options.
  108893. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  108894. */
  108895. EffectLayer.prototype._init = function (options) {
  108896. // Adapt options
  108897. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  108898. this._setMainTextureSize();
  108899. this._createMainTexture();
  108900. this._createTextureAndPostProcesses();
  108901. this._mergeEffect = this._createMergeEffect();
  108902. };
  108903. /**
  108904. * Generates the index buffer of the full screen quad blending to the main canvas.
  108905. */
  108906. EffectLayer.prototype._generateIndexBuffer = function () {
  108907. // Indices
  108908. var indices = [];
  108909. indices.push(0);
  108910. indices.push(1);
  108911. indices.push(2);
  108912. indices.push(0);
  108913. indices.push(2);
  108914. indices.push(3);
  108915. this._indexBuffer = this._engine.createIndexBuffer(indices);
  108916. };
  108917. /**
  108918. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  108919. */
  108920. EffectLayer.prototype._genrateVertexBuffer = function () {
  108921. // VBO
  108922. var vertices = [];
  108923. vertices.push(1, 1);
  108924. vertices.push(-1, 1);
  108925. vertices.push(-1, -1);
  108926. vertices.push(1, -1);
  108927. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108928. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108929. };
  108930. /**
  108931. * Sets the main texture desired size which is the closest power of two
  108932. * of the engine canvas size.
  108933. */
  108934. EffectLayer.prototype._setMainTextureSize = function () {
  108935. if (this._effectLayerOptions.mainTextureFixedSize) {
  108936. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  108937. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  108938. }
  108939. else {
  108940. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  108941. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  108942. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  108943. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  108944. }
  108945. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  108946. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  108947. };
  108948. /**
  108949. * Creates the main texture for the effect layer.
  108950. */
  108951. EffectLayer.prototype._createMainTexture = function () {
  108952. var _this = this;
  108953. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  108954. width: this._mainTextureDesiredSize.width,
  108955. height: this._mainTextureDesiredSize.height
  108956. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108957. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  108958. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108959. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108960. this._mainTexture.anisotropicFilteringLevel = 1;
  108961. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108962. this._mainTexture.renderParticles = false;
  108963. this._mainTexture.renderList = null;
  108964. this._mainTexture.ignoreCameraViewport = true;
  108965. // Custom render function
  108966. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  108967. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  108968. var index;
  108969. var engine = _this._scene.getEngine();
  108970. if (depthOnlySubMeshes.length) {
  108971. engine.setColorWrite(false);
  108972. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  108973. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  108974. }
  108975. engine.setColorWrite(true);
  108976. }
  108977. for (index = 0; index < opaqueSubMeshes.length; index++) {
  108978. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  108979. }
  108980. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  108981. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  108982. }
  108983. for (index = 0; index < transparentSubMeshes.length; index++) {
  108984. _this._renderSubMesh(transparentSubMeshes.data[index]);
  108985. }
  108986. };
  108987. this._mainTexture.onClearObservable.add(function (engine) {
  108988. engine.clear(_this.neutralColor, true, true, true);
  108989. });
  108990. };
  108991. /**
  108992. * Checks for the readiness of the element composing the layer.
  108993. * @param subMesh the mesh to check for
  108994. * @param useInstances specify wether or not to use instances to render the mesh
  108995. * @param emissiveTexture the associated emissive texture used to generate the glow
  108996. * @return true if ready otherwise, false
  108997. */
  108998. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  108999. var material = subMesh.getMaterial();
  109000. if (!material) {
  109001. return false;
  109002. }
  109003. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  109004. return false;
  109005. }
  109006. var defines = [];
  109007. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109008. var mesh = subMesh.getMesh();
  109009. var uv1 = false;
  109010. var uv2 = false;
  109011. // Alpha test
  109012. if (material && material.needAlphaTesting()) {
  109013. var alphaTexture = material.getAlphaTestTexture();
  109014. if (alphaTexture) {
  109015. defines.push("#define ALPHATEST");
  109016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109017. alphaTexture.coordinatesIndex === 1) {
  109018. defines.push("#define DIFFUSEUV2");
  109019. uv2 = true;
  109020. }
  109021. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109022. defines.push("#define DIFFUSEUV1");
  109023. uv1 = true;
  109024. }
  109025. }
  109026. }
  109027. // Emissive
  109028. if (emissiveTexture) {
  109029. defines.push("#define EMISSIVE");
  109030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109031. emissiveTexture.coordinatesIndex === 1) {
  109032. defines.push("#define EMISSIVEUV2");
  109033. uv2 = true;
  109034. }
  109035. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109036. defines.push("#define EMISSIVEUV1");
  109037. uv1 = true;
  109038. }
  109039. }
  109040. if (uv1) {
  109041. attribs.push(BABYLON.VertexBuffer.UVKind);
  109042. defines.push("#define UV1");
  109043. }
  109044. if (uv2) {
  109045. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109046. defines.push("#define UV2");
  109047. }
  109048. // Bones
  109049. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109050. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109051. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109052. if (mesh.numBoneInfluencers > 4) {
  109053. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109054. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109055. }
  109056. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109057. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109058. }
  109059. else {
  109060. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109061. }
  109062. // Morph targets
  109063. var manager = mesh.morphTargetManager;
  109064. var morphInfluencers = 0;
  109065. if (manager) {
  109066. if (manager.numInfluencers > 0) {
  109067. defines.push("#define MORPHTARGETS");
  109068. morphInfluencers = manager.numInfluencers;
  109069. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109070. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109071. }
  109072. }
  109073. // Instances
  109074. if (useInstances) {
  109075. defines.push("#define INSTANCES");
  109076. attribs.push("world0");
  109077. attribs.push("world1");
  109078. attribs.push("world2");
  109079. attribs.push("world3");
  109080. }
  109081. // Get correct effect
  109082. var join = defines.join("\n");
  109083. if (this._cachedDefines !== join) {
  109084. this._cachedDefines = join;
  109085. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109086. }
  109087. return this._effectLayerMapGenerationEffect.isReady();
  109088. };
  109089. /**
  109090. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109091. */
  109092. EffectLayer.prototype.render = function () {
  109093. var currentEffect = this._mergeEffect;
  109094. // Check
  109095. if (!currentEffect.isReady())
  109096. return;
  109097. for (var i = 0; i < this._postProcesses.length; i++) {
  109098. if (!this._postProcesses[i].isReady()) {
  109099. return;
  109100. }
  109101. }
  109102. var engine = this._scene.getEngine();
  109103. this.onBeforeComposeObservable.notifyObservers(this);
  109104. // Render
  109105. engine.enableEffect(currentEffect);
  109106. engine.setState(false);
  109107. // VBOs
  109108. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109109. // Cache
  109110. var previousAlphaMode = engine.getAlphaMode();
  109111. // Go Blend.
  109112. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109113. // Blends the map on the main canvas.
  109114. this._internalRender(currentEffect);
  109115. // Restore Alpha
  109116. engine.setAlphaMode(previousAlphaMode);
  109117. this.onAfterComposeObservable.notifyObservers(this);
  109118. // Handle size changes.
  109119. var size = this._mainTexture.getSize();
  109120. this._setMainTextureSize();
  109121. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109122. // Recreate RTT and post processes on size change.
  109123. this.onSizeChangedObservable.notifyObservers(this);
  109124. this._disposeTextureAndPostProcesses();
  109125. this._createMainTexture();
  109126. this._createTextureAndPostProcesses();
  109127. }
  109128. };
  109129. /**
  109130. * Determine if a given mesh will be used in the current effect.
  109131. * @param mesh mesh to test
  109132. * @returns true if the mesh will be used
  109133. */
  109134. EffectLayer.prototype.hasMesh = function (mesh) {
  109135. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109136. return true;
  109137. }
  109138. return false;
  109139. };
  109140. /**
  109141. * Returns true if the layer contains information to display, otherwise false.
  109142. * @returns true if the glow layer should be rendered
  109143. */
  109144. EffectLayer.prototype.shouldRender = function () {
  109145. return this.isEnabled && this._shouldRender;
  109146. };
  109147. /**
  109148. * Returns true if the mesh should render, otherwise false.
  109149. * @param mesh The mesh to render
  109150. * @returns true if it should render otherwise false
  109151. */
  109152. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109153. return true;
  109154. };
  109155. /**
  109156. * Returns true if the mesh should render, otherwise false.
  109157. * @param mesh The mesh to render
  109158. * @returns true if it should render otherwise false
  109159. */
  109160. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109161. return true;
  109162. };
  109163. /**
  109164. * Renders the submesh passed in parameter to the generation map.
  109165. */
  109166. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109167. var _this = this;
  109168. if (!this.shouldRender()) {
  109169. return;
  109170. }
  109171. var material = subMesh.getMaterial();
  109172. var mesh = subMesh.getRenderingMesh();
  109173. var scene = this._scene;
  109174. var engine = scene.getEngine();
  109175. if (!material) {
  109176. return;
  109177. }
  109178. // Do not block in blend mode.
  109179. if (material.needAlphaBlendingForMesh(mesh)) {
  109180. return;
  109181. }
  109182. // Culling
  109183. engine.setState(material.backFaceCulling);
  109184. // Managing instances
  109185. var batch = mesh._getInstancesRenderList(subMesh._id);
  109186. if (batch.mustReturn) {
  109187. return;
  109188. }
  109189. // Early Exit per mesh
  109190. if (!this._shouldRenderMesh(mesh)) {
  109191. return;
  109192. }
  109193. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109194. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109195. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109196. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109197. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109198. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109199. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109200. // Alpha test
  109201. if (material && material.needAlphaTesting()) {
  109202. var alphaTexture = material.getAlphaTestTexture();
  109203. if (alphaTexture) {
  109204. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109205. var textureMatrix = alphaTexture.getTextureMatrix();
  109206. if (textureMatrix) {
  109207. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109208. }
  109209. }
  109210. }
  109211. // Glow emissive only
  109212. if (this._emissiveTextureAndColor.texture) {
  109213. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109214. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109215. }
  109216. // Bones
  109217. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109218. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109219. }
  109220. // Morph targets
  109221. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109222. // Draw
  109223. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109224. }
  109225. else {
  109226. // Need to reset refresh rate of the main map
  109227. this._mainTexture.resetRefreshCounter();
  109228. }
  109229. };
  109230. /**
  109231. * Rebuild the required buffers.
  109232. * @hidden Internal use only.
  109233. */
  109234. EffectLayer.prototype._rebuild = function () {
  109235. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109236. if (vb) {
  109237. vb._rebuild();
  109238. }
  109239. this._generateIndexBuffer();
  109240. };
  109241. /**
  109242. * Dispose only the render target textures and post process.
  109243. */
  109244. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109245. this._mainTexture.dispose();
  109246. for (var i = 0; i < this._postProcesses.length; i++) {
  109247. if (this._postProcesses[i]) {
  109248. this._postProcesses[i].dispose();
  109249. }
  109250. }
  109251. this._postProcesses = [];
  109252. for (var i = 0; i < this._textures.length; i++) {
  109253. if (this._textures[i]) {
  109254. this._textures[i].dispose();
  109255. }
  109256. }
  109257. this._textures = [];
  109258. };
  109259. /**
  109260. * Dispose the highlight layer and free resources.
  109261. */
  109262. EffectLayer.prototype.dispose = function () {
  109263. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109264. if (vertexBuffer) {
  109265. vertexBuffer.dispose();
  109266. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109267. }
  109268. if (this._indexBuffer) {
  109269. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109270. this._indexBuffer = null;
  109271. }
  109272. // Clean textures and post processes
  109273. this._disposeTextureAndPostProcesses();
  109274. // Remove from scene
  109275. var index = this._scene.effectLayers.indexOf(this, 0);
  109276. if (index > -1) {
  109277. this._scene.effectLayers.splice(index, 1);
  109278. }
  109279. // Callback
  109280. this.onDisposeObservable.notifyObservers(this);
  109281. this.onDisposeObservable.clear();
  109282. this.onBeforeRenderMainTextureObservable.clear();
  109283. this.onBeforeComposeObservable.clear();
  109284. this.onAfterComposeObservable.clear();
  109285. this.onSizeChangedObservable.clear();
  109286. };
  109287. /**
  109288. * Gets the class name of the effect layer
  109289. * @returns the string with the class name of the effect layer
  109290. */
  109291. EffectLayer.prototype.getClassName = function () {
  109292. return "EffectLayer";
  109293. };
  109294. /**
  109295. * Creates an effect layer from parsed effect layer data
  109296. * @param parsedEffectLayer defines effect layer data
  109297. * @param scene defines the current scene
  109298. * @param rootUrl defines the root URL containing the effect layer information
  109299. * @returns a parsed effect Layer
  109300. */
  109301. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109302. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109303. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109304. };
  109305. __decorate([
  109306. BABYLON.serialize()
  109307. ], EffectLayer.prototype, "name", void 0);
  109308. __decorate([
  109309. BABYLON.serializeAsColor4()
  109310. ], EffectLayer.prototype, "neutralColor", void 0);
  109311. __decorate([
  109312. BABYLON.serialize()
  109313. ], EffectLayer.prototype, "isEnabled", void 0);
  109314. __decorate([
  109315. BABYLON.serializeAsCameraReference()
  109316. ], EffectLayer.prototype, "camera", null);
  109317. __decorate([
  109318. BABYLON.serialize()
  109319. ], EffectLayer.prototype, "renderingGroupId", null);
  109320. return EffectLayer;
  109321. }());
  109322. BABYLON.EffectLayer = EffectLayer;
  109323. })(BABYLON || (BABYLON = {}));
  109324. //# sourceMappingURL=babylon.effectLayer.js.map
  109325. var BABYLON;
  109326. (function (BABYLON) {
  109327. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109328. for (var index = 0; index < this.effectLayers.length; index++) {
  109329. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109330. return this.effectLayers[index];
  109331. }
  109332. }
  109333. return null;
  109334. };
  109335. /**
  109336. * Special Glow Blur post process only blurring the alpha channel
  109337. * It enforces keeping the most luminous color in the color channel.
  109338. */
  109339. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109340. __extends(GlowBlurPostProcess, _super);
  109341. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109343. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109344. _this.direction = direction;
  109345. _this.kernel = kernel;
  109346. _this.onApplyObservable.add(function (effect) {
  109347. effect.setFloat2("screenSize", _this.width, _this.height);
  109348. effect.setVector2("direction", _this.direction);
  109349. effect.setFloat("blurWidth", _this.kernel);
  109350. });
  109351. return _this;
  109352. }
  109353. return GlowBlurPostProcess;
  109354. }(BABYLON.PostProcess));
  109355. /**
  109356. * The highlight layer Helps adding a glow effect around a mesh.
  109357. *
  109358. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109359. * glowy meshes to your scene.
  109360. *
  109361. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109362. */
  109363. var HighlightLayer = /** @class */ (function (_super) {
  109364. __extends(HighlightLayer, _super);
  109365. /**
  109366. * Instantiates a new highlight Layer and references it to the scene..
  109367. * @param name The name of the layer
  109368. * @param scene The scene to use the layer in
  109369. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109370. */
  109371. function HighlightLayer(name, scene, options) {
  109372. var _this = _super.call(this, name, scene) || this;
  109373. _this.name = name;
  109374. /**
  109375. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109376. */
  109377. _this.innerGlow = true;
  109378. /**
  109379. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109380. */
  109381. _this.outerGlow = true;
  109382. /**
  109383. * An event triggered when the highlight layer is being blurred.
  109384. */
  109385. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109386. /**
  109387. * An event triggered when the highlight layer has been blurred.
  109388. */
  109389. _this.onAfterBlurObservable = new BABYLON.Observable();
  109390. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109391. _this._meshes = {};
  109392. _this._excludedMeshes = {};
  109393. _this.neutralColor = HighlightLayer.NeutralColor;
  109394. // Warn on stencil
  109395. if (!_this._engine.isStencilEnable) {
  109396. 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 }");
  109397. }
  109398. // Adapt options
  109399. _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);
  109400. // Initialize the layer
  109401. _this._init({
  109402. alphaBlendingMode: _this._options.alphaBlendingMode,
  109403. camera: _this._options.camera,
  109404. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109405. mainTextureRatio: _this._options.mainTextureRatio,
  109406. renderingGroupId: _this._options.renderingGroupId
  109407. });
  109408. // Do not render as long as no meshes have been added
  109409. _this._shouldRender = false;
  109410. return _this;
  109411. }
  109412. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109413. /**
  109414. * Gets the horizontal size of the blur.
  109415. */
  109416. get: function () {
  109417. return this._horizontalBlurPostprocess.kernel;
  109418. },
  109419. /**
  109420. * Specifies the horizontal size of the blur.
  109421. */
  109422. set: function (value) {
  109423. this._horizontalBlurPostprocess.kernel = value;
  109424. },
  109425. enumerable: true,
  109426. configurable: true
  109427. });
  109428. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109429. /**
  109430. * Gets the vertical size of the blur.
  109431. */
  109432. get: function () {
  109433. return this._verticalBlurPostprocess.kernel;
  109434. },
  109435. /**
  109436. * Specifies the vertical size of the blur.
  109437. */
  109438. set: function (value) {
  109439. this._verticalBlurPostprocess.kernel = value;
  109440. },
  109441. enumerable: true,
  109442. configurable: true
  109443. });
  109444. /**
  109445. * Get the effect name of the layer.
  109446. * @return The effect name
  109447. */
  109448. HighlightLayer.prototype.getEffectName = function () {
  109449. return HighlightLayer.EffectName;
  109450. };
  109451. /**
  109452. * Create the merge effect. This is the shader use to blit the information back
  109453. * to the main canvas at the end of the scene rendering.
  109454. */
  109455. HighlightLayer.prototype._createMergeEffect = function () {
  109456. // Effect
  109457. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109458. };
  109459. /**
  109460. * Creates the render target textures and post processes used in the highlight layer.
  109461. */
  109462. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109463. var _this = this;
  109464. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109465. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109466. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109467. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109468. var textureType = 0;
  109469. if (this._engine.getCaps().textureHalfFloatRender) {
  109470. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109471. }
  109472. else {
  109473. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109474. }
  109475. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109476. width: blurTextureWidth,
  109477. height: blurTextureHeight
  109478. }, this._scene, false, true, textureType);
  109479. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109480. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109481. this._blurTexture.anisotropicFilteringLevel = 16;
  109482. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109483. this._blurTexture.renderParticles = false;
  109484. this._blurTexture.ignoreCameraViewport = true;
  109485. this._textures = [this._blurTexture];
  109486. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109487. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109488. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109489. effect.setTexture("textureSampler", _this._mainTexture);
  109490. });
  109491. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109492. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109493. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109494. });
  109495. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109496. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109497. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109498. });
  109499. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109500. }
  109501. else {
  109502. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109503. width: blurTextureWidth,
  109504. height: blurTextureHeight
  109505. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109506. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109507. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109508. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109509. effect.setTexture("textureSampler", _this._mainTexture);
  109510. });
  109511. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109512. width: blurTextureWidth,
  109513. height: blurTextureHeight
  109514. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109515. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109516. }
  109517. this._mainTexture.onAfterUnbindObservable.add(function () {
  109518. _this.onBeforeBlurObservable.notifyObservers(_this);
  109519. var internalTexture = _this._blurTexture.getInternalTexture();
  109520. if (internalTexture) {
  109521. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109522. }
  109523. _this.onAfterBlurObservable.notifyObservers(_this);
  109524. });
  109525. // Prevent autoClear.
  109526. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109527. };
  109528. /**
  109529. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109530. */
  109531. HighlightLayer.prototype.needStencil = function () {
  109532. return true;
  109533. };
  109534. /**
  109535. * Checks for the readiness of the element composing the layer.
  109536. * @param subMesh the mesh to check for
  109537. * @param useInstances specify wether or not to use instances to render the mesh
  109538. * @param emissiveTexture the associated emissive texture used to generate the glow
  109539. * @return true if ready otherwise, false
  109540. */
  109541. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109542. var material = subMesh.getMaterial();
  109543. var mesh = subMesh.getRenderingMesh();
  109544. if (!material || !mesh || !this._meshes) {
  109545. return false;
  109546. }
  109547. var emissiveTexture = null;
  109548. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109549. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109550. emissiveTexture = material.emissiveTexture;
  109551. }
  109552. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109553. };
  109554. /**
  109555. * Implementation specific of rendering the generating effect on the main canvas.
  109556. * @param effect The effect used to render through
  109557. */
  109558. HighlightLayer.prototype._internalRender = function (effect) {
  109559. // Texture
  109560. effect.setTexture("textureSampler", this._blurTexture);
  109561. // Cache
  109562. var engine = this._engine;
  109563. var previousStencilBuffer = engine.getStencilBuffer();
  109564. var previousStencilFunction = engine.getStencilFunction();
  109565. var previousStencilMask = engine.getStencilMask();
  109566. var previousStencilOperationPass = engine.getStencilOperationPass();
  109567. var previousStencilOperationFail = engine.getStencilOperationFail();
  109568. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109569. var previousStencilReference = engine.getStencilFunctionReference();
  109570. // Stencil operations
  109571. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  109572. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  109573. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  109574. // Draw order
  109575. engine.setStencilMask(0x00);
  109576. engine.setStencilBuffer(true);
  109577. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  109578. // 2 passes inner outer
  109579. if (this.outerGlow) {
  109580. effect.setFloat("offset", 0);
  109581. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  109582. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109583. }
  109584. if (this.innerGlow) {
  109585. effect.setFloat("offset", 1);
  109586. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  109587. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109588. }
  109589. // Restore Cache
  109590. engine.setStencilFunction(previousStencilFunction);
  109591. engine.setStencilMask(previousStencilMask);
  109592. engine.setStencilBuffer(previousStencilBuffer);
  109593. engine.setStencilOperationPass(previousStencilOperationPass);
  109594. engine.setStencilOperationFail(previousStencilOperationFail);
  109595. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  109596. engine.setStencilFunctionReference(previousStencilReference);
  109597. };
  109598. /**
  109599. * Returns true if the layer contains information to display, otherwise false.
  109600. */
  109601. HighlightLayer.prototype.shouldRender = function () {
  109602. if (_super.prototype.shouldRender.call(this)) {
  109603. return this._meshes ? true : false;
  109604. }
  109605. return false;
  109606. };
  109607. /**
  109608. * Returns true if the mesh should render, otherwise false.
  109609. * @param mesh The mesh to render
  109610. * @returns true if it should render otherwise false
  109611. */
  109612. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  109613. // Excluded Mesh
  109614. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  109615. return false;
  109616. }
  109617. ;
  109618. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109619. return false;
  109620. }
  109621. return true;
  109622. };
  109623. /**
  109624. * Sets the required values for both the emissive texture and and the main color.
  109625. */
  109626. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  109627. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109628. if (highlightLayerMesh) {
  109629. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  109630. }
  109631. else {
  109632. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  109633. }
  109634. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109635. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  109636. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  109637. }
  109638. else {
  109639. this._emissiveTextureAndColor.texture = null;
  109640. }
  109641. };
  109642. /**
  109643. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  109644. * @param mesh The mesh to exclude from the highlight layer
  109645. */
  109646. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  109647. if (!this._excludedMeshes) {
  109648. return;
  109649. }
  109650. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109651. if (!meshExcluded) {
  109652. this._excludedMeshes[mesh.uniqueId] = {
  109653. mesh: mesh,
  109654. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  109655. mesh.getEngine().setStencilBuffer(false);
  109656. }),
  109657. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  109658. mesh.getEngine().setStencilBuffer(true);
  109659. }),
  109660. };
  109661. }
  109662. };
  109663. /**
  109664. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  109665. * @param mesh The mesh to highlight
  109666. */
  109667. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  109668. if (!this._excludedMeshes) {
  109669. return;
  109670. }
  109671. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109672. if (meshExcluded) {
  109673. if (meshExcluded.beforeRender) {
  109674. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  109675. }
  109676. if (meshExcluded.afterRender) {
  109677. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  109678. }
  109679. }
  109680. this._excludedMeshes[mesh.uniqueId] = null;
  109681. };
  109682. /**
  109683. * Determine if a given mesh will be highlighted by the current HighlightLayer
  109684. * @param mesh mesh to test
  109685. * @returns true if the mesh will be highlighted by the current HighlightLayer
  109686. */
  109687. HighlightLayer.prototype.hasMesh = function (mesh) {
  109688. if (!this._meshes) {
  109689. return false;
  109690. }
  109691. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109692. return false;
  109693. }
  109694. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  109695. };
  109696. /**
  109697. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  109698. * @param mesh The mesh to highlight
  109699. * @param color The color of the highlight
  109700. * @param glowEmissiveOnly Extract the glow from the emissive texture
  109701. */
  109702. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  109703. var _this = this;
  109704. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  109705. if (!this._meshes) {
  109706. return;
  109707. }
  109708. var meshHighlight = this._meshes[mesh.uniqueId];
  109709. if (meshHighlight) {
  109710. meshHighlight.color = color;
  109711. }
  109712. else {
  109713. this._meshes[mesh.uniqueId] = {
  109714. mesh: mesh,
  109715. color: color,
  109716. // Lambda required for capture due to Observable this context
  109717. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  109718. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  109719. _this._defaultStencilReference(mesh);
  109720. }
  109721. else {
  109722. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  109723. }
  109724. }),
  109725. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  109726. glowEmissiveOnly: glowEmissiveOnly
  109727. };
  109728. mesh.onDisposeObservable.add(function () {
  109729. _this._disposeMesh(mesh);
  109730. });
  109731. }
  109732. this._shouldRender = true;
  109733. };
  109734. /**
  109735. * Remove a mesh from the highlight layer in order to make it stop glowing.
  109736. * @param mesh The mesh to highlight
  109737. */
  109738. HighlightLayer.prototype.removeMesh = function (mesh) {
  109739. if (!this._meshes) {
  109740. return;
  109741. }
  109742. var meshHighlight = this._meshes[mesh.uniqueId];
  109743. if (meshHighlight) {
  109744. if (meshHighlight.observerHighlight) {
  109745. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  109746. }
  109747. if (meshHighlight.observerDefault) {
  109748. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  109749. }
  109750. delete this._meshes[mesh.uniqueId];
  109751. }
  109752. this._shouldRender = false;
  109753. for (var meshHighlightToCheck in this._meshes) {
  109754. if (this._meshes[meshHighlightToCheck]) {
  109755. this._shouldRender = true;
  109756. break;
  109757. }
  109758. }
  109759. };
  109760. /**
  109761. * Force the stencil to the normal expected value for none glowing parts
  109762. */
  109763. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  109764. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  109765. };
  109766. /**
  109767. * Free any resources and references associated to a mesh.
  109768. * Internal use
  109769. * @param mesh The mesh to free.
  109770. * @hidden
  109771. */
  109772. HighlightLayer.prototype._disposeMesh = function (mesh) {
  109773. this.removeMesh(mesh);
  109774. this.removeExcludedMesh(mesh);
  109775. };
  109776. /**
  109777. * Dispose the highlight layer and free resources.
  109778. */
  109779. HighlightLayer.prototype.dispose = function () {
  109780. if (this._meshes) {
  109781. // Clean mesh references
  109782. for (var id in this._meshes) {
  109783. var meshHighlight = this._meshes[id];
  109784. if (meshHighlight && meshHighlight.mesh) {
  109785. if (meshHighlight.observerHighlight) {
  109786. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  109787. }
  109788. if (meshHighlight.observerDefault) {
  109789. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  109790. }
  109791. }
  109792. }
  109793. this._meshes = null;
  109794. }
  109795. if (this._excludedMeshes) {
  109796. for (var id in this._excludedMeshes) {
  109797. var meshHighlight = this._excludedMeshes[id];
  109798. if (meshHighlight) {
  109799. if (meshHighlight.beforeRender) {
  109800. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  109801. }
  109802. if (meshHighlight.afterRender) {
  109803. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  109804. }
  109805. }
  109806. }
  109807. this._excludedMeshes = null;
  109808. }
  109809. _super.prototype.dispose.call(this);
  109810. };
  109811. /**
  109812. * Gets the class name of the effect layer
  109813. * @returns the string with the class name of the effect layer
  109814. */
  109815. HighlightLayer.prototype.getClassName = function () {
  109816. return "HighlightLayer";
  109817. };
  109818. /**
  109819. * Serializes this Highlight layer
  109820. * @returns a serialized Highlight layer object
  109821. */
  109822. HighlightLayer.prototype.serialize = function () {
  109823. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  109824. serializationObject.customType = "BABYLON.HighlightLayer";
  109825. // Highlighted meshes
  109826. serializationObject.meshes = [];
  109827. if (this._meshes) {
  109828. for (var m in this._meshes) {
  109829. var mesh = this._meshes[m];
  109830. if (mesh) {
  109831. serializationObject.meshes.push({
  109832. glowEmissiveOnly: mesh.glowEmissiveOnly,
  109833. color: mesh.color.asArray(),
  109834. meshId: mesh.mesh.id
  109835. });
  109836. }
  109837. }
  109838. }
  109839. // Excluded meshes
  109840. serializationObject.excludedMeshes = [];
  109841. if (this._excludedMeshes) {
  109842. for (var e in this._excludedMeshes) {
  109843. var excludedMesh = this._excludedMeshes[e];
  109844. if (excludedMesh) {
  109845. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  109846. }
  109847. }
  109848. }
  109849. return serializationObject;
  109850. };
  109851. /**
  109852. * Creates a Highlight layer from parsed Highlight layer data
  109853. * @param parsedHightlightLayer defines the Highlight layer data
  109854. * @param scene defines the current scene
  109855. * @param rootUrl defines the root URL containing the Highlight layer information
  109856. * @returns a parsed Highlight layer
  109857. */
  109858. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  109859. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  109860. var index;
  109861. // Excluded meshes
  109862. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  109863. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  109864. if (mesh) {
  109865. hl.addExcludedMesh(mesh);
  109866. }
  109867. }
  109868. // Included meshes
  109869. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  109870. var highlightedMesh = parsedHightlightLayer.meshes[index];
  109871. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  109872. if (mesh) {
  109873. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  109874. }
  109875. }
  109876. return hl;
  109877. };
  109878. /**
  109879. * Effect Name of the highlight layer.
  109880. */
  109881. HighlightLayer.EffectName = "HighlightLayer";
  109882. /**
  109883. * The neutral color used during the preparation of the glow effect.
  109884. * This is black by default as the blend operation is a blend operation.
  109885. */
  109886. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  109887. /**
  109888. * Stencil value used for glowing meshes.
  109889. */
  109890. HighlightLayer.GlowingMeshStencilReference = 0x02;
  109891. /**
  109892. * Stencil value used for the other meshes in the scene.
  109893. */
  109894. HighlightLayer.NormalMeshStencilReference = 0x01;
  109895. __decorate([
  109896. BABYLON.serialize()
  109897. ], HighlightLayer.prototype, "innerGlow", void 0);
  109898. __decorate([
  109899. BABYLON.serialize()
  109900. ], HighlightLayer.prototype, "outerGlow", void 0);
  109901. __decorate([
  109902. BABYLON.serialize()
  109903. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  109904. __decorate([
  109905. BABYLON.serialize()
  109906. ], HighlightLayer.prototype, "blurVerticalSize", null);
  109907. __decorate([
  109908. BABYLON.serialize("options")
  109909. ], HighlightLayer.prototype, "_options", void 0);
  109910. return HighlightLayer;
  109911. }(BABYLON.EffectLayer));
  109912. BABYLON.HighlightLayer = HighlightLayer;
  109913. })(BABYLON || (BABYLON = {}));
  109914. //# sourceMappingURL=babylon.highlightLayer.js.map
  109915. var BABYLON;
  109916. (function (BABYLON) {
  109917. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  109918. for (var index = 0; index < this.effectLayers.length; index++) {
  109919. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  109920. return this.effectLayers[index];
  109921. }
  109922. }
  109923. return null;
  109924. };
  109925. /**
  109926. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  109927. *
  109928. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109929. * glowy meshes to your scene.
  109930. *
  109931. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  109932. */
  109933. var GlowLayer = /** @class */ (function (_super) {
  109934. __extends(GlowLayer, _super);
  109935. /**
  109936. * Instantiates a new glow Layer and references it to the scene.
  109937. * @param name The name of the layer
  109938. * @param scene The scene to use the layer in
  109939. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  109940. */
  109941. function GlowLayer(name, scene, options) {
  109942. var _this = _super.call(this, name, scene) || this;
  109943. _this._intensity = 1.0;
  109944. _this._includedOnlyMeshes = [];
  109945. _this._excludedMeshes = [];
  109946. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  109947. // Adapt options
  109948. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  109949. // Initialize the layer
  109950. _this._init({
  109951. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  109952. camera: _this._options.camera,
  109953. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109954. mainTextureRatio: _this._options.mainTextureRatio,
  109955. renderingGroupId: _this._options.renderingGroupId
  109956. });
  109957. return _this;
  109958. }
  109959. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  109960. /**
  109961. * Gets the kernel size of the blur.
  109962. */
  109963. get: function () {
  109964. return this._horizontalBlurPostprocess1.kernel;
  109965. },
  109966. /**
  109967. * Sets the kernel size of the blur.
  109968. */
  109969. set: function (value) {
  109970. this._horizontalBlurPostprocess1.kernel = value;
  109971. this._verticalBlurPostprocess1.kernel = value;
  109972. this._horizontalBlurPostprocess2.kernel = value;
  109973. this._verticalBlurPostprocess2.kernel = value;
  109974. },
  109975. enumerable: true,
  109976. configurable: true
  109977. });
  109978. Object.defineProperty(GlowLayer.prototype, "intensity", {
  109979. /**
  109980. * Gets the glow intensity.
  109981. */
  109982. get: function () {
  109983. return this._intensity;
  109984. },
  109985. /**
  109986. * Sets the glow intensity.
  109987. */
  109988. set: function (value) {
  109989. this._intensity = value;
  109990. },
  109991. enumerable: true,
  109992. configurable: true
  109993. });
  109994. /**
  109995. * Get the effect name of the layer.
  109996. * @return The effect name
  109997. */
  109998. GlowLayer.prototype.getEffectName = function () {
  109999. return GlowLayer.EffectName;
  110000. };
  110001. /**
  110002. * Create the merge effect. This is the shader use to blit the information back
  110003. * to the main canvas at the end of the scene rendering.
  110004. */
  110005. GlowLayer.prototype._createMergeEffect = function () {
  110006. // Effect
  110007. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  110008. };
  110009. /**
  110010. * Creates the render target textures and post processes used in the glow layer.
  110011. */
  110012. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  110013. var _this = this;
  110014. var blurTextureWidth = this._mainTextureDesiredSize.width;
  110015. var blurTextureHeight = this._mainTextureDesiredSize.height;
  110016. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  110017. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  110018. var textureType = 0;
  110019. if (this._engine.getCaps().textureHalfFloatRender) {
  110020. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  110021. }
  110022. else {
  110023. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110024. }
  110025. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  110026. width: blurTextureWidth,
  110027. height: blurTextureHeight
  110028. }, this._scene, false, true, textureType);
  110029. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110030. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110031. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110032. this._blurTexture1.renderParticles = false;
  110033. this._blurTexture1.ignoreCameraViewport = true;
  110034. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110035. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110036. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110037. width: blurTextureWidth2,
  110038. height: blurTextureHeight2
  110039. }, this._scene, false, true, textureType);
  110040. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110041. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110042. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110043. this._blurTexture2.renderParticles = false;
  110044. this._blurTexture2.ignoreCameraViewport = true;
  110045. this._textures = [this._blurTexture1, this._blurTexture2];
  110046. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110047. width: blurTextureWidth,
  110048. height: blurTextureHeight
  110049. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110050. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110051. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110052. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110053. effect.setTexture("textureSampler", _this._mainTexture);
  110054. });
  110055. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110056. width: blurTextureWidth,
  110057. height: blurTextureHeight
  110058. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110059. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110060. width: blurTextureWidth2,
  110061. height: blurTextureHeight2
  110062. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110063. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110064. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110065. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110066. effect.setTexture("textureSampler", _this._blurTexture1);
  110067. });
  110068. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110069. width: blurTextureWidth2,
  110070. height: blurTextureHeight2
  110071. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110072. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110073. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110074. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110075. this._mainTexture.samples = this._options.mainTextureSamples;
  110076. this._mainTexture.onAfterUnbindObservable.add(function () {
  110077. var internalTexture = _this._blurTexture1.getInternalTexture();
  110078. if (internalTexture) {
  110079. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110080. internalTexture = _this._blurTexture2.getInternalTexture();
  110081. if (internalTexture) {
  110082. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110083. }
  110084. }
  110085. });
  110086. // Prevent autoClear.
  110087. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110088. };
  110089. /**
  110090. * Checks for the readiness of the element composing the layer.
  110091. * @param subMesh the mesh to check for
  110092. * @param useInstances specify wether or not to use instances to render the mesh
  110093. * @param emissiveTexture the associated emissive texture used to generate the glow
  110094. * @return true if ready otherwise, false
  110095. */
  110096. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110097. var material = subMesh.getMaterial();
  110098. var mesh = subMesh.getRenderingMesh();
  110099. if (!material || !mesh) {
  110100. return false;
  110101. }
  110102. var emissiveTexture = material.emissiveTexture;
  110103. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110104. };
  110105. /**
  110106. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110107. */
  110108. GlowLayer.prototype.needStencil = function () {
  110109. return false;
  110110. };
  110111. /**
  110112. * Implementation specific of rendering the generating effect on the main canvas.
  110113. * @param effect The effect used to render through
  110114. */
  110115. GlowLayer.prototype._internalRender = function (effect) {
  110116. // Texture
  110117. effect.setTexture("textureSampler", this._blurTexture1);
  110118. effect.setTexture("textureSampler2", this._blurTexture2);
  110119. effect.setFloat("offset", this._intensity);
  110120. // Cache
  110121. var engine = this._engine;
  110122. var previousStencilBuffer = engine.getStencilBuffer();
  110123. // Draw order
  110124. engine.setStencilBuffer(false);
  110125. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110126. // Draw order
  110127. engine.setStencilBuffer(previousStencilBuffer);
  110128. };
  110129. /**
  110130. * Sets the required values for both the emissive texture and and the main color.
  110131. */
  110132. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110133. var textureLevel = 1.0;
  110134. if (this.customEmissiveTextureSelector) {
  110135. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110136. }
  110137. else {
  110138. if (material) {
  110139. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110140. if (this._emissiveTextureAndColor.texture) {
  110141. textureLevel = this._emissiveTextureAndColor.texture.level;
  110142. }
  110143. }
  110144. else {
  110145. this._emissiveTextureAndColor.texture = null;
  110146. }
  110147. }
  110148. if (this.customEmissiveColorSelector) {
  110149. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110150. }
  110151. else {
  110152. if (material.emissiveColor) {
  110153. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110154. }
  110155. else {
  110156. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110157. }
  110158. }
  110159. };
  110160. /**
  110161. * Returns true if the mesh should render, otherwise false.
  110162. * @param mesh The mesh to render
  110163. * @returns true if it should render otherwise false
  110164. */
  110165. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110166. return this.hasMesh(mesh);
  110167. };
  110168. /**
  110169. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110170. * @param mesh The mesh to exclude from the glow layer
  110171. */
  110172. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110173. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110174. this._excludedMeshes.push(mesh.uniqueId);
  110175. }
  110176. };
  110177. /**
  110178. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110179. * @param mesh The mesh to remove
  110180. */
  110181. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110182. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110183. if (index !== -1) {
  110184. this._excludedMeshes.splice(index, 1);
  110185. }
  110186. };
  110187. /**
  110188. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110189. * @param mesh The mesh to include in the glow layer
  110190. */
  110191. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110192. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110193. this._includedOnlyMeshes.push(mesh.uniqueId);
  110194. }
  110195. };
  110196. /**
  110197. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110198. * @param mesh The mesh to remove
  110199. */
  110200. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110201. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110202. if (index !== -1) {
  110203. this._includedOnlyMeshes.splice(index, 1);
  110204. }
  110205. };
  110206. /**
  110207. * Determine if a given mesh will be used in the glow layer
  110208. * @param mesh The mesh to test
  110209. * @returns true if the mesh will be highlighted by the current glow layer
  110210. */
  110211. GlowLayer.prototype.hasMesh = function (mesh) {
  110212. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110213. return false;
  110214. }
  110215. // Included Mesh
  110216. if (this._includedOnlyMeshes.length) {
  110217. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110218. }
  110219. ;
  110220. // Excluded Mesh
  110221. if (this._excludedMeshes.length) {
  110222. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110223. }
  110224. ;
  110225. return true;
  110226. };
  110227. /**
  110228. * Free any resources and references associated to a mesh.
  110229. * Internal use
  110230. * @param mesh The mesh to free.
  110231. * @hidden
  110232. */
  110233. GlowLayer.prototype._disposeMesh = function (mesh) {
  110234. this.removeIncludedOnlyMesh(mesh);
  110235. this.removeExcludedMesh(mesh);
  110236. };
  110237. /**
  110238. * Gets the class name of the effect layer
  110239. * @returns the string with the class name of the effect layer
  110240. */
  110241. GlowLayer.prototype.getClassName = function () {
  110242. return "GlowLayer";
  110243. };
  110244. /**
  110245. * Serializes this glow layer
  110246. * @returns a serialized glow layer object
  110247. */
  110248. GlowLayer.prototype.serialize = function () {
  110249. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110250. serializationObject.customType = "BABYLON.GlowLayer";
  110251. var index;
  110252. // Included meshes
  110253. serializationObject.includedMeshes = [];
  110254. if (this._includedOnlyMeshes.length) {
  110255. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110256. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110257. if (mesh) {
  110258. serializationObject.includedMeshes.push(mesh.id);
  110259. }
  110260. }
  110261. }
  110262. // Excluded meshes
  110263. serializationObject.excludedMeshes = [];
  110264. if (this._excludedMeshes.length) {
  110265. for (index = 0; index < this._excludedMeshes.length; index++) {
  110266. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110267. if (mesh) {
  110268. serializationObject.excludedMeshes.push(mesh.id);
  110269. }
  110270. }
  110271. }
  110272. return serializationObject;
  110273. };
  110274. /**
  110275. * Creates a Glow Layer from parsed glow layer data
  110276. * @param parsedGlowLayer defines glow layer data
  110277. * @param scene defines the current scene
  110278. * @param rootUrl defines the root URL containing the glow layer information
  110279. * @returns a parsed Glow Layer
  110280. */
  110281. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110282. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110283. var index;
  110284. // Excluded meshes
  110285. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110286. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110287. if (mesh) {
  110288. gl.addExcludedMesh(mesh);
  110289. }
  110290. }
  110291. // Included meshes
  110292. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110293. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110294. if (mesh) {
  110295. gl.addIncludedOnlyMesh(mesh);
  110296. }
  110297. }
  110298. return gl;
  110299. };
  110300. /**
  110301. * Effect Name of the layer.
  110302. */
  110303. GlowLayer.EffectName = "GlowLayer";
  110304. /**
  110305. * The default blur kernel size used for the glow.
  110306. */
  110307. GlowLayer.DefaultBlurKernelSize = 32;
  110308. /**
  110309. * The default texture size ratio used for the glow.
  110310. */
  110311. GlowLayer.DefaultTextureRatio = 0.5;
  110312. __decorate([
  110313. BABYLON.serialize()
  110314. ], GlowLayer.prototype, "blurKernelSize", null);
  110315. __decorate([
  110316. BABYLON.serialize()
  110317. ], GlowLayer.prototype, "intensity", null);
  110318. __decorate([
  110319. BABYLON.serialize("options")
  110320. ], GlowLayer.prototype, "_options", void 0);
  110321. return GlowLayer;
  110322. }(BABYLON.EffectLayer));
  110323. BABYLON.GlowLayer = GlowLayer;
  110324. })(BABYLON || (BABYLON = {}));
  110325. //# sourceMappingURL=babylon.glowLayer.js.map
  110326. var BABYLON;
  110327. (function (BABYLON) {
  110328. /**
  110329. * Defines the list of states available for a task inside a AssetsManager
  110330. */
  110331. var AssetTaskState;
  110332. (function (AssetTaskState) {
  110333. /**
  110334. * Initialization
  110335. */
  110336. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110337. /**
  110338. * Running
  110339. */
  110340. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110341. /**
  110342. * Done
  110343. */
  110344. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110345. /**
  110346. * Error
  110347. */
  110348. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110349. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110350. /**
  110351. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  110352. */
  110353. var AbstractAssetTask = /** @class */ (function () {
  110354. /**
  110355. * Creates a new AssetsManager
  110356. * @param name defines the name of the task
  110357. */
  110358. function AbstractAssetTask(
  110359. /**
  110360. * Task name
  110361. */ name) {
  110362. this.name = name;
  110363. this._isCompleted = false;
  110364. this._taskState = AssetTaskState.INIT;
  110365. }
  110366. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110367. /**
  110368. * Get if the task is completed
  110369. */
  110370. get: function () {
  110371. return this._isCompleted;
  110372. },
  110373. enumerable: true,
  110374. configurable: true
  110375. });
  110376. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110377. /**
  110378. * Gets the current state of the task
  110379. */
  110380. get: function () {
  110381. return this._taskState;
  110382. },
  110383. enumerable: true,
  110384. configurable: true
  110385. });
  110386. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110387. /**
  110388. * Gets the current error object (if task is in error)
  110389. */
  110390. get: function () {
  110391. return this._errorObject;
  110392. },
  110393. enumerable: true,
  110394. configurable: true
  110395. });
  110396. /**
  110397. * Internal only
  110398. * @hidden
  110399. */
  110400. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110401. if (this._errorObject) {
  110402. return;
  110403. }
  110404. this._errorObject = {
  110405. message: message,
  110406. exception: exception
  110407. };
  110408. };
  110409. /**
  110410. * Execute the current task
  110411. * @param scene defines the scene where you want your assets to be loaded
  110412. * @param onSuccess is a callback called when the task is successfully executed
  110413. * @param onError is a callback called if an error occurs
  110414. */
  110415. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110416. var _this = this;
  110417. this._taskState = AssetTaskState.RUNNING;
  110418. this.runTask(scene, function () {
  110419. _this.onDoneCallback(onSuccess, onError);
  110420. }, function (msg, exception) {
  110421. _this.onErrorCallback(onError, msg, exception);
  110422. });
  110423. };
  110424. /**
  110425. * Execute the current task
  110426. * @param scene defines the scene where you want your assets to be loaded
  110427. * @param onSuccess is a callback called when the task is successfully executed
  110428. * @param onError is a callback called if an error occurs
  110429. */
  110430. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110431. throw new Error("runTask is not implemented");
  110432. };
  110433. /**
  110434. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110435. * This can be used with failed tasks that have the reason for failure fixed.
  110436. */
  110437. AbstractAssetTask.prototype.reset = function () {
  110438. this._taskState = AssetTaskState.INIT;
  110439. };
  110440. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110441. this._taskState = AssetTaskState.ERROR;
  110442. this._errorObject = {
  110443. message: message,
  110444. exception: exception
  110445. };
  110446. if (this.onError) {
  110447. this.onError(this, message, exception);
  110448. }
  110449. onError();
  110450. };
  110451. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110452. try {
  110453. this._taskState = AssetTaskState.DONE;
  110454. this._isCompleted = true;
  110455. if (this.onSuccess) {
  110456. this.onSuccess(this);
  110457. }
  110458. onSuccess();
  110459. }
  110460. catch (e) {
  110461. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110462. }
  110463. };
  110464. return AbstractAssetTask;
  110465. }());
  110466. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110467. /**
  110468. * Class used to share progress information about assets loading
  110469. */
  110470. var AssetsProgressEvent = /** @class */ (function () {
  110471. /**
  110472. * Creates a AssetsProgressEvent
  110473. * @param remainingCount defines the number of remaining tasks to process
  110474. * @param totalCount defines the total number of tasks
  110475. * @param task defines the task that was just processed
  110476. */
  110477. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110478. this.remainingCount = remainingCount;
  110479. this.totalCount = totalCount;
  110480. this.task = task;
  110481. }
  110482. return AssetsProgressEvent;
  110483. }());
  110484. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110485. /**
  110486. * Define a task used by AssetsManager to load meshes
  110487. */
  110488. var MeshAssetTask = /** @class */ (function (_super) {
  110489. __extends(MeshAssetTask, _super);
  110490. /**
  110491. * Creates a new MeshAssetTask
  110492. * @param name defines the name of the task
  110493. * @param meshesNames defines the list of mesh's names you want to load
  110494. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110495. * @param sceneFilename defines the filename of the scene to load from
  110496. */
  110497. function MeshAssetTask(
  110498. /**
  110499. * Defines the name of the task
  110500. */
  110501. name,
  110502. /**
  110503. * Defines the list of mesh's names you want to load
  110504. */
  110505. meshesNames,
  110506. /**
  110507. * Defines the root url to use as a base to load your meshes and associated resources
  110508. */
  110509. rootUrl,
  110510. /**
  110511. * Defines the filename of the scene to load from
  110512. */
  110513. sceneFilename) {
  110514. var _this = _super.call(this, name) || this;
  110515. _this.name = name;
  110516. _this.meshesNames = meshesNames;
  110517. _this.rootUrl = rootUrl;
  110518. _this.sceneFilename = sceneFilename;
  110519. return _this;
  110520. }
  110521. /**
  110522. * Execute the current task
  110523. * @param scene defines the scene where you want your assets to be loaded
  110524. * @param onSuccess is a callback called when the task is successfully executed
  110525. * @param onError is a callback called if an error occurs
  110526. */
  110527. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110528. var _this = this;
  110529. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110530. _this.loadedMeshes = meshes;
  110531. _this.loadedParticleSystems = particleSystems;
  110532. _this.loadedSkeletons = skeletons;
  110533. onSuccess();
  110534. }, null, function (scene, message, exception) {
  110535. onError(message, exception);
  110536. });
  110537. };
  110538. return MeshAssetTask;
  110539. }(AbstractAssetTask));
  110540. BABYLON.MeshAssetTask = MeshAssetTask;
  110541. /**
  110542. * Define a task used by AssetsManager to load text content
  110543. */
  110544. var TextFileAssetTask = /** @class */ (function (_super) {
  110545. __extends(TextFileAssetTask, _super);
  110546. /**
  110547. * Creates a new TextFileAssetTask object
  110548. * @param name defines the name of the task
  110549. * @param url defines the location of the file to load
  110550. */
  110551. function TextFileAssetTask(
  110552. /**
  110553. * Defines the name of the task
  110554. */
  110555. name,
  110556. /**
  110557. * Defines the location of the file to load
  110558. */
  110559. url) {
  110560. var _this = _super.call(this, name) || this;
  110561. _this.name = name;
  110562. _this.url = url;
  110563. return _this;
  110564. }
  110565. /**
  110566. * Execute the current task
  110567. * @param scene defines the scene where you want your assets to be loaded
  110568. * @param onSuccess is a callback called when the task is successfully executed
  110569. * @param onError is a callback called if an error occurs
  110570. */
  110571. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110572. var _this = this;
  110573. scene._loadFile(this.url, function (data) {
  110574. _this.text = data;
  110575. onSuccess();
  110576. }, undefined, false, false, function (request, exception) {
  110577. if (request) {
  110578. onError(request.status + " " + request.statusText, exception);
  110579. }
  110580. });
  110581. };
  110582. return TextFileAssetTask;
  110583. }(AbstractAssetTask));
  110584. BABYLON.TextFileAssetTask = TextFileAssetTask;
  110585. /**
  110586. * Define a task used by AssetsManager to load binary data
  110587. */
  110588. var BinaryFileAssetTask = /** @class */ (function (_super) {
  110589. __extends(BinaryFileAssetTask, _super);
  110590. /**
  110591. * Creates a new BinaryFileAssetTask object
  110592. * @param name defines the name of the new task
  110593. * @param url defines the location of the file to load
  110594. */
  110595. function BinaryFileAssetTask(
  110596. /**
  110597. * Defines the name of the task
  110598. */
  110599. name,
  110600. /**
  110601. * Defines the location of the file to load
  110602. */
  110603. url) {
  110604. var _this = _super.call(this, name) || this;
  110605. _this.name = name;
  110606. _this.url = url;
  110607. return _this;
  110608. }
  110609. /**
  110610. * Execute the current task
  110611. * @param scene defines the scene where you want your assets to be loaded
  110612. * @param onSuccess is a callback called when the task is successfully executed
  110613. * @param onError is a callback called if an error occurs
  110614. */
  110615. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110616. var _this = this;
  110617. scene._loadFile(this.url, function (data) {
  110618. _this.data = data;
  110619. onSuccess();
  110620. }, undefined, true, true, function (request, exception) {
  110621. if (request) {
  110622. onError(request.status + " " + request.statusText, exception);
  110623. }
  110624. });
  110625. };
  110626. return BinaryFileAssetTask;
  110627. }(AbstractAssetTask));
  110628. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  110629. /**
  110630. * Define a task used by AssetsManager to load images
  110631. */
  110632. var ImageAssetTask = /** @class */ (function (_super) {
  110633. __extends(ImageAssetTask, _super);
  110634. /**
  110635. * Creates a new ImageAssetTask
  110636. * @param name defines the name of the task
  110637. * @param url defines the location of the image to load
  110638. */
  110639. function ImageAssetTask(
  110640. /**
  110641. * Defines the name of the task
  110642. */
  110643. name,
  110644. /**
  110645. * Defines the location of the image to load
  110646. */
  110647. url) {
  110648. var _this = _super.call(this, name) || this;
  110649. _this.name = name;
  110650. _this.url = url;
  110651. return _this;
  110652. }
  110653. /**
  110654. * Execute the current task
  110655. * @param scene defines the scene where you want your assets to be loaded
  110656. * @param onSuccess is a callback called when the task is successfully executed
  110657. * @param onError is a callback called if an error occurs
  110658. */
  110659. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110660. var _this = this;
  110661. var img = new Image();
  110662. BABYLON.Tools.SetCorsBehavior(this.url, img);
  110663. img.onload = function () {
  110664. _this.image = img;
  110665. onSuccess();
  110666. };
  110667. img.onerror = function (err) {
  110668. onError("Error loading image", err);
  110669. };
  110670. img.src = this.url;
  110671. };
  110672. return ImageAssetTask;
  110673. }(AbstractAssetTask));
  110674. BABYLON.ImageAssetTask = ImageAssetTask;
  110675. /**
  110676. * Define a task used by AssetsManager to load 2D textures
  110677. */
  110678. var TextureAssetTask = /** @class */ (function (_super) {
  110679. __extends(TextureAssetTask, _super);
  110680. /**
  110681. * Creates a new TextureAssetTask object
  110682. * @param name defines the name of the task
  110683. * @param url defines the location of the file to load
  110684. * @param noMipmap defines if mipmap should not be generated (default is false)
  110685. * @param invertY defines if texture must be inverted on Y axis (default is false)
  110686. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110687. */
  110688. function TextureAssetTask(
  110689. /**
  110690. * Defines the name of the task
  110691. */
  110692. name,
  110693. /**
  110694. * Defines the location of the file to load
  110695. */
  110696. url,
  110697. /**
  110698. * Defines if mipmap should not be generated (default is false)
  110699. */
  110700. noMipmap,
  110701. /**
  110702. * Defines if texture must be inverted on Y axis (default is false)
  110703. */
  110704. invertY,
  110705. /**
  110706. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110707. */
  110708. samplingMode) {
  110709. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110710. var _this = _super.call(this, name) || this;
  110711. _this.name = name;
  110712. _this.url = url;
  110713. _this.noMipmap = noMipmap;
  110714. _this.invertY = invertY;
  110715. _this.samplingMode = samplingMode;
  110716. return _this;
  110717. }
  110718. /**
  110719. * Execute the current task
  110720. * @param scene defines the scene where you want your assets to be loaded
  110721. * @param onSuccess is a callback called when the task is successfully executed
  110722. * @param onError is a callback called if an error occurs
  110723. */
  110724. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110725. var onload = function () {
  110726. onSuccess();
  110727. };
  110728. var onerror = function (message, exception) {
  110729. onError(message, exception);
  110730. };
  110731. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  110732. };
  110733. return TextureAssetTask;
  110734. }(AbstractAssetTask));
  110735. BABYLON.TextureAssetTask = TextureAssetTask;
  110736. /**
  110737. * Define a task used by AssetsManager to load cube textures
  110738. */
  110739. var CubeTextureAssetTask = /** @class */ (function (_super) {
  110740. __extends(CubeTextureAssetTask, _super);
  110741. /**
  110742. * Creates a new CubeTextureAssetTask
  110743. * @param name defines the name of the task
  110744. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  110745. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  110746. * @param noMipmap defines if mipmaps should not be generated (default is false)
  110747. * @param files defines the explicit list of files (undefined by default)
  110748. */
  110749. function CubeTextureAssetTask(
  110750. /**
  110751. * Defines the name of the task
  110752. */
  110753. name,
  110754. /**
  110755. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  110756. */
  110757. url,
  110758. /**
  110759. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  110760. */
  110761. extensions,
  110762. /**
  110763. * Defines if mipmaps should not be generated (default is false)
  110764. */
  110765. noMipmap,
  110766. /**
  110767. * Defines the explicit list of files (undefined by default)
  110768. */
  110769. files) {
  110770. var _this = _super.call(this, name) || this;
  110771. _this.name = name;
  110772. _this.url = url;
  110773. _this.extensions = extensions;
  110774. _this.noMipmap = noMipmap;
  110775. _this.files = files;
  110776. return _this;
  110777. }
  110778. /**
  110779. * Execute the current task
  110780. * @param scene defines the scene where you want your assets to be loaded
  110781. * @param onSuccess is a callback called when the task is successfully executed
  110782. * @param onError is a callback called if an error occurs
  110783. */
  110784. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110785. var onload = function () {
  110786. onSuccess();
  110787. };
  110788. var onerror = function (message, exception) {
  110789. onError(message, exception);
  110790. };
  110791. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  110792. };
  110793. return CubeTextureAssetTask;
  110794. }(AbstractAssetTask));
  110795. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  110796. /**
  110797. * Define a task used by AssetsManager to load HDR cube textures
  110798. */
  110799. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  110800. __extends(HDRCubeTextureAssetTask, _super);
  110801. /**
  110802. * Creates a new HDRCubeTextureAssetTask object
  110803. * @param name defines the name of the task
  110804. * @param url defines the location of the file to load
  110805. * @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.
  110806. * @param noMipmap defines if mipmaps should not be generated (default is false)
  110807. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  110808. * @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)
  110809. * @param reserved Internal use only
  110810. */
  110811. function HDRCubeTextureAssetTask(
  110812. /**
  110813. * Defines the name of the task
  110814. */
  110815. name,
  110816. /**
  110817. * Defines the location of the file to load
  110818. */
  110819. url,
  110820. /**
  110821. * Defines the desired size (the more it increases the longer the generation will be)
  110822. */
  110823. size,
  110824. /**
  110825. * Defines if mipmaps should not be generated (default is false)
  110826. */
  110827. noMipmap,
  110828. /**
  110829. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  110830. */
  110831. generateHarmonics,
  110832. /**
  110833. * 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)
  110834. */
  110835. gammaSpace,
  110836. /**
  110837. * Internal Use Only
  110838. */
  110839. reserved) {
  110840. if (noMipmap === void 0) { noMipmap = false; }
  110841. if (generateHarmonics === void 0) { generateHarmonics = true; }
  110842. if (gammaSpace === void 0) { gammaSpace = false; }
  110843. if (reserved === void 0) { reserved = false; }
  110844. var _this = _super.call(this, name) || this;
  110845. _this.name = name;
  110846. _this.url = url;
  110847. _this.size = size;
  110848. _this.noMipmap = noMipmap;
  110849. _this.generateHarmonics = generateHarmonics;
  110850. _this.gammaSpace = gammaSpace;
  110851. _this.reserved = reserved;
  110852. return _this;
  110853. }
  110854. /**
  110855. * Execute the current task
  110856. * @param scene defines the scene where you want your assets to be loaded
  110857. * @param onSuccess is a callback called when the task is successfully executed
  110858. * @param onError is a callback called if an error occurs
  110859. */
  110860. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110861. var onload = function () {
  110862. onSuccess();
  110863. };
  110864. var onerror = function (message, exception) {
  110865. onError(message, exception);
  110866. };
  110867. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  110868. };
  110869. return HDRCubeTextureAssetTask;
  110870. }(AbstractAssetTask));
  110871. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  110872. /**
  110873. * This class can be used to easily import assets into a scene
  110874. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  110875. */
  110876. var AssetsManager = /** @class */ (function () {
  110877. /**
  110878. * Creates a new AssetsManager
  110879. * @param scene defines the scene to work on
  110880. */
  110881. function AssetsManager(scene) {
  110882. this._isLoading = false;
  110883. this._tasks = new Array();
  110884. this._waitingTasksCount = 0;
  110885. this._totalTasksCount = 0;
  110886. /**
  110887. * Observable called when all tasks are processed
  110888. */
  110889. this.onTaskSuccessObservable = new BABYLON.Observable();
  110890. /**
  110891. * Observable called when a task had an error
  110892. */
  110893. this.onTaskErrorObservable = new BABYLON.Observable();
  110894. /**
  110895. * Observable called when a task is successful
  110896. */
  110897. this.onTasksDoneObservable = new BABYLON.Observable();
  110898. /**
  110899. * Observable called when a task is done (whatever the result is)
  110900. */
  110901. this.onProgressObservable = new BABYLON.Observable();
  110902. /**
  110903. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  110904. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  110905. */
  110906. this.useDefaultLoadingScreen = true;
  110907. this._scene = scene;
  110908. }
  110909. /**
  110910. * Add a MeshAssetTask to the list of active tasks
  110911. * @param taskName defines the name of the new task
  110912. * @param meshesNames defines the name of meshes to load
  110913. * @param rootUrl defines the root url to use to locate files
  110914. * @param sceneFilename defines the filename of the scene file
  110915. * @returns a new MeshAssetTask object
  110916. */
  110917. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  110918. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  110919. this._tasks.push(task);
  110920. return task;
  110921. };
  110922. /**
  110923. * Add a TextFileAssetTask to the list of active tasks
  110924. * @param taskName defines the name of the new task
  110925. * @param url defines the url of the file to load
  110926. * @returns a new TextFileAssetTask object
  110927. */
  110928. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  110929. var task = new TextFileAssetTask(taskName, url);
  110930. this._tasks.push(task);
  110931. return task;
  110932. };
  110933. /**
  110934. * Add a BinaryFileAssetTask to the list of active tasks
  110935. * @param taskName defines the name of the new task
  110936. * @param url defines the url of the file to load
  110937. * @returns a new BinaryFileAssetTask object
  110938. */
  110939. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  110940. var task = new BinaryFileAssetTask(taskName, url);
  110941. this._tasks.push(task);
  110942. return task;
  110943. };
  110944. /**
  110945. * Add a ImageAssetTask to the list of active tasks
  110946. * @param taskName defines the name of the new task
  110947. * @param url defines the url of the file to load
  110948. * @returns a new ImageAssetTask object
  110949. */
  110950. AssetsManager.prototype.addImageTask = function (taskName, url) {
  110951. var task = new ImageAssetTask(taskName, url);
  110952. this._tasks.push(task);
  110953. return task;
  110954. };
  110955. /**
  110956. * Add a TextureAssetTask to the list of active tasks
  110957. * @param taskName defines the name of the new task
  110958. * @param url defines the url of the file to load
  110959. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110960. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  110961. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  110962. * @returns a new TextureAssetTask object
  110963. */
  110964. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  110965. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110966. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  110967. this._tasks.push(task);
  110968. return task;
  110969. };
  110970. /**
  110971. * Add a CubeTextureAssetTask to the list of active tasks
  110972. * @param taskName defines the name of the new task
  110973. * @param url defines the url of the file to load
  110974. * @param extensions defines the extension to use to load the cube map (can be null)
  110975. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110976. * @param files defines the list of files to load (can be null)
  110977. * @returns a new CubeTextureAssetTask object
  110978. */
  110979. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  110980. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  110981. this._tasks.push(task);
  110982. return task;
  110983. };
  110984. /**
  110985. *
  110986. * Add a HDRCubeTextureAssetTask to the list of active tasks
  110987. * @param taskName defines the name of the new task
  110988. * @param url defines the url of the file to load
  110989. * @param size defines the size you want for the cubemap (can be null)
  110990. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110991. * @param generateHarmonics defines if you want to automatically generate (true by default)
  110992. * @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)
  110993. * @param reserved Internal use only
  110994. * @returns a new HDRCubeTextureAssetTask object
  110995. */
  110996. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  110997. if (noMipmap === void 0) { noMipmap = false; }
  110998. if (generateHarmonics === void 0) { generateHarmonics = true; }
  110999. if (gammaSpace === void 0) { gammaSpace = false; }
  111000. if (reserved === void 0) { reserved = false; }
  111001. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  111002. this._tasks.push(task);
  111003. return task;
  111004. };
  111005. /**
  111006. * Remove a task from the assets manager.
  111007. * @param task the task to remove
  111008. */
  111009. AssetsManager.prototype.removeTask = function (task) {
  111010. var index = this._tasks.indexOf(task);
  111011. if (index > -1) {
  111012. this._tasks.splice(index, 1);
  111013. }
  111014. };
  111015. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  111016. this._waitingTasksCount--;
  111017. try {
  111018. if (this.onProgress) {
  111019. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  111020. }
  111021. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  111022. }
  111023. catch (e) {
  111024. BABYLON.Tools.Error("Error running progress callbacks.");
  111025. console.log(e);
  111026. }
  111027. if (this._waitingTasksCount === 0) {
  111028. try {
  111029. if (this.onFinish) {
  111030. this.onFinish(this._tasks);
  111031. }
  111032. // Let's remove successfull tasks
  111033. var currentTasks = this._tasks.slice();
  111034. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111035. var task = currentTasks_1[_i];
  111036. if (task.taskState === AssetTaskState.DONE) {
  111037. var index = this._tasks.indexOf(task);
  111038. if (index > -1) {
  111039. this._tasks.splice(index, 1);
  111040. }
  111041. }
  111042. }
  111043. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111044. }
  111045. catch (e) {
  111046. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111047. console.log(e);
  111048. }
  111049. this._isLoading = false;
  111050. this._scene.getEngine().hideLoadingUI();
  111051. }
  111052. };
  111053. AssetsManager.prototype._runTask = function (task) {
  111054. var _this = this;
  111055. var done = function () {
  111056. try {
  111057. if (_this.onTaskSuccess) {
  111058. _this.onTaskSuccess(task);
  111059. }
  111060. _this.onTaskSuccessObservable.notifyObservers(task);
  111061. _this._decreaseWaitingTasksCount(task);
  111062. }
  111063. catch (e) {
  111064. error("Error executing task success callbacks", e);
  111065. }
  111066. };
  111067. var error = function (message, exception) {
  111068. task._setErrorObject(message, exception);
  111069. if (_this.onTaskError) {
  111070. _this.onTaskError(task);
  111071. }
  111072. _this.onTaskErrorObservable.notifyObservers(task);
  111073. _this._decreaseWaitingTasksCount(task);
  111074. };
  111075. task.run(this._scene, done, error);
  111076. };
  111077. /**
  111078. * Reset the AssetsManager and remove all tasks
  111079. * @return the current instance of the AssetsManager
  111080. */
  111081. AssetsManager.prototype.reset = function () {
  111082. this._isLoading = false;
  111083. this._tasks = new Array();
  111084. return this;
  111085. };
  111086. /**
  111087. * Start the loading process
  111088. * @return the current instance of the AssetsManager
  111089. */
  111090. AssetsManager.prototype.load = function () {
  111091. if (this._isLoading) {
  111092. return this;
  111093. }
  111094. this._isLoading = true;
  111095. this._waitingTasksCount = this._tasks.length;
  111096. this._totalTasksCount = this._tasks.length;
  111097. if (this._waitingTasksCount === 0) {
  111098. this._isLoading = false;
  111099. if (this.onFinish) {
  111100. this.onFinish(this._tasks);
  111101. }
  111102. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111103. return this;
  111104. }
  111105. if (this.useDefaultLoadingScreen) {
  111106. this._scene.getEngine().displayLoadingUI();
  111107. }
  111108. for (var index = 0; index < this._tasks.length; index++) {
  111109. var task = this._tasks[index];
  111110. if (task.taskState === AssetTaskState.INIT) {
  111111. this._runTask(task);
  111112. }
  111113. }
  111114. return this;
  111115. };
  111116. return AssetsManager;
  111117. }());
  111118. BABYLON.AssetsManager = AssetsManager;
  111119. })(BABYLON || (BABYLON = {}));
  111120. //# sourceMappingURL=babylon.assetsManager.js.map
  111121. var BABYLON;
  111122. (function (BABYLON) {
  111123. var serializedGeometries = [];
  111124. var serializeGeometry = function (geometry, serializationGeometries) {
  111125. if (serializedGeometries[geometry.id]) {
  111126. return;
  111127. }
  111128. if (geometry.doNotSerialize) {
  111129. return;
  111130. }
  111131. if (geometry instanceof BABYLON.BoxGeometry) {
  111132. serializationGeometries.boxes.push(geometry.serialize());
  111133. }
  111134. else if (geometry instanceof BABYLON.SphereGeometry) {
  111135. serializationGeometries.spheres.push(geometry.serialize());
  111136. }
  111137. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111138. serializationGeometries.cylinders.push(geometry.serialize());
  111139. }
  111140. else if (geometry instanceof BABYLON.TorusGeometry) {
  111141. serializationGeometries.toruses.push(geometry.serialize());
  111142. }
  111143. else if (geometry instanceof BABYLON.GroundGeometry) {
  111144. serializationGeometries.grounds.push(geometry.serialize());
  111145. }
  111146. else if (geometry instanceof BABYLON.Plane) {
  111147. serializationGeometries.planes.push(geometry.serialize());
  111148. }
  111149. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111150. serializationGeometries.torusKnots.push(geometry.serialize());
  111151. }
  111152. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111153. throw new Error("Unknown primitive type");
  111154. }
  111155. else {
  111156. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111157. }
  111158. serializedGeometries[geometry.id] = true;
  111159. };
  111160. var serializeMesh = function (mesh, serializationScene) {
  111161. var serializationObject = {};
  111162. // Geometry
  111163. var geometry = mesh._geometry;
  111164. if (geometry) {
  111165. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111166. // 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
  111167. serializeGeometry(geometry, serializationScene.geometries);
  111168. }
  111169. }
  111170. // Custom
  111171. if (mesh.serialize) {
  111172. mesh.serialize(serializationObject);
  111173. }
  111174. return serializationObject;
  111175. };
  111176. var finalizeSingleMesh = function (mesh, serializationObject) {
  111177. //only works if the mesh is already loaded
  111178. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111179. //serialize material
  111180. if (mesh.material) {
  111181. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111182. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111183. serializationObject.materials = serializationObject.materials || [];
  111184. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111185. serializationObject.multiMaterials.push(mesh.material.serialize());
  111186. var _loop_1 = function (submaterial) {
  111187. if (submaterial) {
  111188. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111189. serializationObject.materials.push(submaterial.serialize());
  111190. }
  111191. }
  111192. };
  111193. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111194. var submaterial = _a[_i];
  111195. _loop_1(submaterial);
  111196. }
  111197. }
  111198. }
  111199. else {
  111200. serializationObject.materials = serializationObject.materials || [];
  111201. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111202. serializationObject.materials.push(mesh.material.serialize());
  111203. }
  111204. }
  111205. }
  111206. //serialize geometry
  111207. var geometry = mesh._geometry;
  111208. if (geometry) {
  111209. if (!serializationObject.geometries) {
  111210. serializationObject.geometries = {};
  111211. serializationObject.geometries.boxes = [];
  111212. serializationObject.geometries.spheres = [];
  111213. serializationObject.geometries.cylinders = [];
  111214. serializationObject.geometries.toruses = [];
  111215. serializationObject.geometries.grounds = [];
  111216. serializationObject.geometries.planes = [];
  111217. serializationObject.geometries.torusKnots = [];
  111218. serializationObject.geometries.vertexData = [];
  111219. }
  111220. serializeGeometry(geometry, serializationObject.geometries);
  111221. }
  111222. // Skeletons
  111223. if (mesh.skeleton) {
  111224. serializationObject.skeletons = serializationObject.skeletons || [];
  111225. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111226. }
  111227. //serialize the actual mesh
  111228. serializationObject.meshes = serializationObject.meshes || [];
  111229. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111230. }
  111231. };
  111232. /**
  111233. * Class used to serialize a scene into a string
  111234. */
  111235. var SceneSerializer = /** @class */ (function () {
  111236. function SceneSerializer() {
  111237. }
  111238. /**
  111239. * Clear cache used by a previous serialization
  111240. */
  111241. SceneSerializer.ClearCache = function () {
  111242. serializedGeometries = [];
  111243. };
  111244. /**
  111245. * Serialize a scene into a JSON compatible object
  111246. * @param scene defines the scene to serialize
  111247. * @returns a JSON compatible object
  111248. */
  111249. SceneSerializer.Serialize = function (scene) {
  111250. var serializationObject = {};
  111251. SceneSerializer.ClearCache();
  111252. // Scene
  111253. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111254. serializationObject.autoClear = scene.autoClear;
  111255. serializationObject.clearColor = scene.clearColor.asArray();
  111256. serializationObject.ambientColor = scene.ambientColor.asArray();
  111257. serializationObject.gravity = scene.gravity.asArray();
  111258. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111259. serializationObject.workerCollisions = scene.workerCollisions;
  111260. // Fog
  111261. if (scene.fogMode && scene.fogMode !== 0) {
  111262. serializationObject.fogMode = scene.fogMode;
  111263. serializationObject.fogColor = scene.fogColor.asArray();
  111264. serializationObject.fogStart = scene.fogStart;
  111265. serializationObject.fogEnd = scene.fogEnd;
  111266. serializationObject.fogDensity = scene.fogDensity;
  111267. }
  111268. //Physics
  111269. if (scene.isPhysicsEnabled()) {
  111270. var physicEngine = scene.getPhysicsEngine();
  111271. if (physicEngine) {
  111272. serializationObject.physicsEnabled = true;
  111273. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111274. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111275. }
  111276. }
  111277. // Metadata
  111278. if (scene.metadata) {
  111279. serializationObject.metadata = scene.metadata;
  111280. }
  111281. // Morph targets
  111282. serializationObject.morphTargetManagers = [];
  111283. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111284. var abstractMesh = _a[_i];
  111285. var manager = abstractMesh.morphTargetManager;
  111286. if (manager) {
  111287. serializationObject.morphTargetManagers.push(manager.serialize());
  111288. }
  111289. }
  111290. // Lights
  111291. serializationObject.lights = [];
  111292. var index;
  111293. var light;
  111294. for (index = 0; index < scene.lights.length; index++) {
  111295. light = scene.lights[index];
  111296. if (!light.doNotSerialize) {
  111297. serializationObject.lights.push(light.serialize());
  111298. }
  111299. }
  111300. // Cameras
  111301. serializationObject.cameras = [];
  111302. for (index = 0; index < scene.cameras.length; index++) {
  111303. var camera = scene.cameras[index];
  111304. if (!camera.doNotSerialize) {
  111305. serializationObject.cameras.push(camera.serialize());
  111306. }
  111307. }
  111308. if (scene.activeCamera) {
  111309. serializationObject.activeCameraID = scene.activeCamera.id;
  111310. }
  111311. // Animations
  111312. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111313. // Materials
  111314. serializationObject.materials = [];
  111315. serializationObject.multiMaterials = [];
  111316. var material;
  111317. for (index = 0; index < scene.materials.length; index++) {
  111318. material = scene.materials[index];
  111319. if (!material.doNotSerialize) {
  111320. serializationObject.materials.push(material.serialize());
  111321. }
  111322. }
  111323. // MultiMaterials
  111324. serializationObject.multiMaterials = [];
  111325. for (index = 0; index < scene.multiMaterials.length; index++) {
  111326. var multiMaterial = scene.multiMaterials[index];
  111327. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111328. }
  111329. // Environment texture
  111330. if (scene.environmentTexture) {
  111331. serializationObject.environmentTexture = scene.environmentTexture.name;
  111332. }
  111333. // Skeletons
  111334. serializationObject.skeletons = [];
  111335. for (index = 0; index < scene.skeletons.length; index++) {
  111336. var skeleton = scene.skeletons[index];
  111337. if (!skeleton.doNotSerialize) {
  111338. serializationObject.skeletons.push(skeleton.serialize());
  111339. }
  111340. }
  111341. // Transform nodes
  111342. serializationObject.transformNodes = [];
  111343. for (index = 0; index < scene.transformNodes.length; index++) {
  111344. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111345. }
  111346. // Geometries
  111347. serializationObject.geometries = {};
  111348. serializationObject.geometries.boxes = [];
  111349. serializationObject.geometries.spheres = [];
  111350. serializationObject.geometries.cylinders = [];
  111351. serializationObject.geometries.toruses = [];
  111352. serializationObject.geometries.grounds = [];
  111353. serializationObject.geometries.planes = [];
  111354. serializationObject.geometries.torusKnots = [];
  111355. serializationObject.geometries.vertexData = [];
  111356. serializedGeometries = [];
  111357. var geometries = scene.getGeometries();
  111358. for (index = 0; index < geometries.length; index++) {
  111359. var geometry = geometries[index];
  111360. if (geometry.isReady()) {
  111361. serializeGeometry(geometry, serializationObject.geometries);
  111362. }
  111363. }
  111364. // Meshes
  111365. serializationObject.meshes = [];
  111366. for (index = 0; index < scene.meshes.length; index++) {
  111367. var abstractMesh = scene.meshes[index];
  111368. if (abstractMesh instanceof BABYLON.Mesh) {
  111369. var mesh = abstractMesh;
  111370. if (!mesh.doNotSerialize) {
  111371. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111372. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111373. }
  111374. }
  111375. }
  111376. }
  111377. // Particles Systems
  111378. serializationObject.particleSystems = [];
  111379. for (index = 0; index < scene.particleSystems.length; index++) {
  111380. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111381. }
  111382. // Action Manager
  111383. if (scene.actionManager) {
  111384. serializationObject.actions = scene.actionManager.serialize("scene");
  111385. }
  111386. // Components
  111387. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111388. var component = _c[_b];
  111389. component.serialize(serializationObject);
  111390. }
  111391. return serializationObject;
  111392. };
  111393. /**
  111394. * Serialize a mesh into a JSON compatible object
  111395. * @param toSerialize defines the mesh to serialize
  111396. * @param withParents defines if parents must be serialized as well
  111397. * @param withChildren defines if children must be serialized as well
  111398. * @returns a JSON compatible object
  111399. */
  111400. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111401. if (withParents === void 0) { withParents = false; }
  111402. if (withChildren === void 0) { withChildren = false; }
  111403. var serializationObject = {};
  111404. SceneSerializer.ClearCache();
  111405. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111406. if (withParents || withChildren) {
  111407. //deliberate for loop! not for each, appended should be processed as well.
  111408. for (var i = 0; i < toSerialize.length; ++i) {
  111409. if (withChildren) {
  111410. toSerialize[i].getDescendants().forEach(function (node) {
  111411. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111412. toSerialize.push(node);
  111413. }
  111414. });
  111415. }
  111416. //make sure the array doesn't contain the object already
  111417. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111418. toSerialize.push(toSerialize[i].parent);
  111419. }
  111420. }
  111421. }
  111422. toSerialize.forEach(function (mesh) {
  111423. finalizeSingleMesh(mesh, serializationObject);
  111424. });
  111425. return serializationObject;
  111426. };
  111427. return SceneSerializer;
  111428. }());
  111429. BABYLON.SceneSerializer = SceneSerializer;
  111430. })(BABYLON || (BABYLON = {}));
  111431. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111432. var BABYLON;
  111433. (function (BABYLON) {
  111434. /**
  111435. * Class used to generate realtime reflection / refraction cube textures
  111436. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111437. */
  111438. var ReflectionProbe = /** @class */ (function () {
  111439. /**
  111440. * Creates a new reflection probe
  111441. * @param name defines the name of the probe
  111442. * @param size defines the texture resolution (for each face)
  111443. * @param scene defines the hosting scene
  111444. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111445. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111446. */
  111447. function ReflectionProbe(
  111448. /** defines the name of the probe */
  111449. name, size, scene, generateMipMaps, useFloat) {
  111450. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111451. if (useFloat === void 0) { useFloat = false; }
  111452. var _this = this;
  111453. this.name = name;
  111454. this._viewMatrix = BABYLON.Matrix.Identity();
  111455. this._target = BABYLON.Vector3.Zero();
  111456. this._add = BABYLON.Vector3.Zero();
  111457. this._invertYAxis = false;
  111458. /** Gets or sets probe position (center of the cube map) */
  111459. this.position = BABYLON.Vector3.Zero();
  111460. this._scene = scene;
  111461. // Create the scene field if not exist.
  111462. if (!this._scene.reflectionProbes) {
  111463. this._scene.reflectionProbes = new Array();
  111464. }
  111465. this._scene.reflectionProbes.push(this);
  111466. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111467. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111468. switch (faceIndex) {
  111469. case 0:
  111470. _this._add.copyFromFloats(1, 0, 0);
  111471. break;
  111472. case 1:
  111473. _this._add.copyFromFloats(-1, 0, 0);
  111474. break;
  111475. case 2:
  111476. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111477. break;
  111478. case 3:
  111479. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111480. break;
  111481. case 4:
  111482. _this._add.copyFromFloats(0, 0, 1);
  111483. break;
  111484. case 5:
  111485. _this._add.copyFromFloats(0, 0, -1);
  111486. break;
  111487. }
  111488. if (_this._attachedMesh) {
  111489. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111490. }
  111491. _this.position.addToRef(_this._add, _this._target);
  111492. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111493. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111494. scene._forcedViewPosition = _this.position;
  111495. });
  111496. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111497. scene._forcedViewPosition = null;
  111498. scene.updateTransformMatrix(true);
  111499. });
  111500. if (scene.activeCamera) {
  111501. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111502. }
  111503. }
  111504. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111505. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111506. get: function () {
  111507. return this._renderTargetTexture.samples;
  111508. },
  111509. set: function (value) {
  111510. this._renderTargetTexture.samples = value;
  111511. },
  111512. enumerable: true,
  111513. configurable: true
  111514. });
  111515. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111516. /** Gets or sets the refresh rate to use (on every frame by default) */
  111517. get: function () {
  111518. return this._renderTargetTexture.refreshRate;
  111519. },
  111520. set: function (value) {
  111521. this._renderTargetTexture.refreshRate = value;
  111522. },
  111523. enumerable: true,
  111524. configurable: true
  111525. });
  111526. /**
  111527. * Gets the hosting scene
  111528. * @returns a Scene
  111529. */
  111530. ReflectionProbe.prototype.getScene = function () {
  111531. return this._scene;
  111532. };
  111533. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111534. /** Gets the internal CubeTexture used to render to */
  111535. get: function () {
  111536. return this._renderTargetTexture;
  111537. },
  111538. enumerable: true,
  111539. configurable: true
  111540. });
  111541. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111542. /** Gets the list of meshes to render */
  111543. get: function () {
  111544. return this._renderTargetTexture.renderList;
  111545. },
  111546. enumerable: true,
  111547. configurable: true
  111548. });
  111549. /**
  111550. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111551. * @param mesh defines the mesh to attach to
  111552. */
  111553. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111554. this._attachedMesh = mesh;
  111555. };
  111556. /**
  111557. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111558. * @param renderingGroupId The rendering group id corresponding to its index
  111559. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111560. */
  111561. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111562. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111563. };
  111564. /**
  111565. * Clean all associated resources
  111566. */
  111567. ReflectionProbe.prototype.dispose = function () {
  111568. var index = this._scene.reflectionProbes.indexOf(this);
  111569. if (index !== -1) {
  111570. // Remove from the scene if found
  111571. this._scene.reflectionProbes.splice(index, 1);
  111572. }
  111573. if (this._renderTargetTexture) {
  111574. this._renderTargetTexture.dispose();
  111575. this._renderTargetTexture = null;
  111576. }
  111577. };
  111578. return ReflectionProbe;
  111579. }());
  111580. BABYLON.ReflectionProbe = ReflectionProbe;
  111581. })(BABYLON || (BABYLON = {}));
  111582. //# sourceMappingURL=babylon.reflectionProbe.js.map
  111583. var BABYLON;
  111584. (function (BABYLON) {
  111585. /**
  111586. * Defines the layer scene component responsible to manage any layers
  111587. * in a given scene.
  111588. */
  111589. var LayerSceneComponent = /** @class */ (function () {
  111590. /**
  111591. * Creates a new instance of the component for the given scene
  111592. * @param scene Defines the scene to register the component in
  111593. */
  111594. function LayerSceneComponent(scene) {
  111595. /**
  111596. * The component name helpfull to identify the component in the list of scene components.
  111597. */
  111598. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  111599. this.scene = scene;
  111600. this._engine = scene.getEngine();
  111601. scene.layers = new Array();
  111602. }
  111603. /**
  111604. * Registers the component in a given scene
  111605. */
  111606. LayerSceneComponent.prototype.register = function () {
  111607. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  111608. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  111609. };
  111610. /**
  111611. * Rebuilds the elements related to this component in case of
  111612. * context lost for instance.
  111613. */
  111614. LayerSceneComponent.prototype.rebuild = function () {
  111615. var layers = this.scene.layers;
  111616. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111617. var layer = layers_1[_i];
  111618. layer._rebuild();
  111619. }
  111620. };
  111621. /**
  111622. * Disposes the component and the associated ressources.
  111623. */
  111624. LayerSceneComponent.prototype.dispose = function () {
  111625. var layers = this.scene.layers;
  111626. while (layers.length) {
  111627. layers[0].dispose();
  111628. }
  111629. };
  111630. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  111631. var layers = this.scene.layers;
  111632. if (layers.length) {
  111633. this._engine.setDepthBuffer(false);
  111634. var cameraLayerMask = camera.layerMask;
  111635. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111636. var layer = layers_2[_i];
  111637. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  111638. layer.render();
  111639. }
  111640. }
  111641. this._engine.setDepthBuffer(true);
  111642. }
  111643. };
  111644. LayerSceneComponent.prototype._drawBackground = function (camera) {
  111645. this._draw(camera, true);
  111646. };
  111647. LayerSceneComponent.prototype._drawForeground = function (camera) {
  111648. this._draw(camera, false);
  111649. };
  111650. return LayerSceneComponent;
  111651. }());
  111652. BABYLON.LayerSceneComponent = LayerSceneComponent;
  111653. })(BABYLON || (BABYLON = {}));
  111654. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  111655. var BABYLON;
  111656. (function (BABYLON) {
  111657. /**
  111658. * This represents a full screen 2d layer.
  111659. * This can be usefull to display a picture in the background of your scene for instance.
  111660. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111661. */
  111662. var Layer = /** @class */ (function () {
  111663. /**
  111664. * Instantiates a new layer.
  111665. * This represents a full screen 2d layer.
  111666. * This can be usefull to display a picture in the background of your scene for instance.
  111667. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111668. * @param name Define the name of the layer in the scene
  111669. * @param imgUrl Define the url of the texture to display in the layer
  111670. * @param scene Define the scene the layer belongs to
  111671. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  111672. * @param color Defines a color for the layer
  111673. */
  111674. function Layer(
  111675. /**
  111676. * Define the name of the layer.
  111677. */
  111678. name, imgUrl, scene, isBackground, color) {
  111679. this.name = name;
  111680. /**
  111681. * Define the scale of the layer in order to zoom in out of the texture.
  111682. */
  111683. this.scale = new BABYLON.Vector2(1, 1);
  111684. /**
  111685. * Define an offset for the layer in order to shift the texture.
  111686. */
  111687. this.offset = new BABYLON.Vector2(0, 0);
  111688. /**
  111689. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  111690. */
  111691. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  111692. /**
  111693. * Define a mask to restrict the layer to only some of the scene cameras.
  111694. */
  111695. this.layerMask = 0x0FFFFFFF;
  111696. this._vertexBuffers = {};
  111697. /**
  111698. * An event triggered when the layer is disposed.
  111699. */
  111700. this.onDisposeObservable = new BABYLON.Observable();
  111701. /**
  111702. * An event triggered before rendering the scene
  111703. */
  111704. this.onBeforeRenderObservable = new BABYLON.Observable();
  111705. /**
  111706. * An event triggered after rendering the scene
  111707. */
  111708. this.onAfterRenderObservable = new BABYLON.Observable();
  111709. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  111710. this.isBackground = isBackground === undefined ? true : isBackground;
  111711. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  111712. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  111713. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  111714. if (!layerComponent) {
  111715. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  111716. this._scene._addComponent(layerComponent);
  111717. }
  111718. this._scene.layers.push(this);
  111719. var engine = this._scene.getEngine();
  111720. // VBO
  111721. var vertices = [];
  111722. vertices.push(1, 1);
  111723. vertices.push(-1, 1);
  111724. vertices.push(-1, -1);
  111725. vertices.push(1, -1);
  111726. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111727. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111728. this._createIndexBuffer();
  111729. // Effects
  111730. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  111731. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  111732. }
  111733. Object.defineProperty(Layer.prototype, "onDispose", {
  111734. /**
  111735. * Back compatibility with callback before the onDisposeObservable existed.
  111736. * The set callback will be triggered when the layer has been disposed.
  111737. */
  111738. set: function (callback) {
  111739. if (this._onDisposeObserver) {
  111740. this.onDisposeObservable.remove(this._onDisposeObserver);
  111741. }
  111742. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  111743. },
  111744. enumerable: true,
  111745. configurable: true
  111746. });
  111747. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  111748. /**
  111749. * Back compatibility with callback before the onBeforeRenderObservable existed.
  111750. * The set callback will be triggered just before rendering the layer.
  111751. */
  111752. set: function (callback) {
  111753. if (this._onBeforeRenderObserver) {
  111754. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  111755. }
  111756. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  111757. },
  111758. enumerable: true,
  111759. configurable: true
  111760. });
  111761. Object.defineProperty(Layer.prototype, "onAfterRender", {
  111762. /**
  111763. * Back compatibility with callback before the onAfterRenderObservable existed.
  111764. * The set callback will be triggered just after rendering the layer.
  111765. */
  111766. set: function (callback) {
  111767. if (this._onAfterRenderObserver) {
  111768. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  111769. }
  111770. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  111771. },
  111772. enumerable: true,
  111773. configurable: true
  111774. });
  111775. Layer.prototype._createIndexBuffer = function () {
  111776. var engine = this._scene.getEngine();
  111777. // Indices
  111778. var indices = [];
  111779. indices.push(0);
  111780. indices.push(1);
  111781. indices.push(2);
  111782. indices.push(0);
  111783. indices.push(2);
  111784. indices.push(3);
  111785. this._indexBuffer = engine.createIndexBuffer(indices);
  111786. };
  111787. /** @hidden */
  111788. Layer.prototype._rebuild = function () {
  111789. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111790. if (vb) {
  111791. vb._rebuild();
  111792. }
  111793. this._createIndexBuffer();
  111794. };
  111795. /**
  111796. * Renders the layer in the scene.
  111797. */
  111798. Layer.prototype.render = function () {
  111799. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  111800. // Check
  111801. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  111802. return;
  111803. var engine = this._scene.getEngine();
  111804. this.onBeforeRenderObservable.notifyObservers(this);
  111805. // Render
  111806. engine.enableEffect(currentEffect);
  111807. engine.setState(false);
  111808. // Texture
  111809. currentEffect.setTexture("textureSampler", this.texture);
  111810. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  111811. // Color
  111812. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  111813. // Scale / offset
  111814. currentEffect.setVector2("offset", this.offset);
  111815. currentEffect.setVector2("scale", this.scale);
  111816. // VBOs
  111817. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111818. // Draw order
  111819. if (!this.alphaTest) {
  111820. engine.setAlphaMode(this.alphaBlendingMode);
  111821. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111822. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  111823. }
  111824. else {
  111825. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111826. }
  111827. this.onAfterRenderObservable.notifyObservers(this);
  111828. };
  111829. /**
  111830. * Disposes and releases the associated ressources.
  111831. */
  111832. Layer.prototype.dispose = function () {
  111833. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111834. if (vertexBuffer) {
  111835. vertexBuffer.dispose();
  111836. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111837. }
  111838. if (this._indexBuffer) {
  111839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111840. this._indexBuffer = null;
  111841. }
  111842. if (this.texture) {
  111843. this.texture.dispose();
  111844. this.texture = null;
  111845. }
  111846. // Remove from scene
  111847. var index = this._scene.layers.indexOf(this);
  111848. this._scene.layers.splice(index, 1);
  111849. // Callback
  111850. this.onDisposeObservable.notifyObservers(this);
  111851. this.onDisposeObservable.clear();
  111852. this.onAfterRenderObservable.clear();
  111853. this.onBeforeRenderObservable.clear();
  111854. };
  111855. return Layer;
  111856. }());
  111857. BABYLON.Layer = Layer;
  111858. })(BABYLON || (BABYLON = {}));
  111859. //# sourceMappingURL=babylon.layer.js.map
  111860. var BABYLON;
  111861. (function (BABYLON) {
  111862. /**
  111863. * Class used to host texture specific utilities
  111864. */
  111865. var TextureTools = /** @class */ (function () {
  111866. function TextureTools() {
  111867. }
  111868. /**
  111869. * Uses the GPU to create a copy texture rescaled at a given size
  111870. * @param texture Texture to copy from
  111871. * @param width defines the desired width
  111872. * @param height defines the desired height
  111873. * @param useBilinearMode defines if bilinear mode has to be used
  111874. * @return the generated texture
  111875. */
  111876. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  111877. if (useBilinearMode === void 0) { useBilinearMode = true; }
  111878. var scene = texture.getScene();
  111879. var engine = scene.getEngine();
  111880. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  111881. rtt.wrapU = texture.wrapU;
  111882. rtt.wrapV = texture.wrapV;
  111883. rtt.uOffset = texture.uOffset;
  111884. rtt.vOffset = texture.vOffset;
  111885. rtt.uScale = texture.uScale;
  111886. rtt.vScale = texture.vScale;
  111887. rtt.uAng = texture.uAng;
  111888. rtt.vAng = texture.vAng;
  111889. rtt.wAng = texture.wAng;
  111890. rtt.coordinatesIndex = texture.coordinatesIndex;
  111891. rtt.level = texture.level;
  111892. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  111893. rtt._texture.isReady = false;
  111894. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111895. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111896. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111897. passPostProcess.getEffect().executeWhenCompiled(function () {
  111898. passPostProcess.onApply = function (effect) {
  111899. effect.setTexture("textureSampler", texture);
  111900. };
  111901. var internalTexture = rtt.getInternalTexture();
  111902. if (internalTexture) {
  111903. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  111904. engine.unBindFramebuffer(internalTexture);
  111905. rtt.disposeFramebufferObjects();
  111906. passPostProcess.dispose();
  111907. internalTexture.isReady = true;
  111908. }
  111909. });
  111910. return rtt;
  111911. };
  111912. /**
  111913. * Gets an environment BRDF texture for a given scene
  111914. * @param scene defines the hosting scene
  111915. * @returns the environment BRDF texture
  111916. */
  111917. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  111918. if (!scene._environmentBRDFTexture) {
  111919. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111920. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111921. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111922. scene._environmentBRDFTexture = texture;
  111923. }
  111924. return scene._environmentBRDFTexture;
  111925. };
  111926. 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=";
  111927. return TextureTools;
  111928. }());
  111929. BABYLON.TextureTools = TextureTools;
  111930. })(BABYLON || (BABYLON = {}));
  111931. //# sourceMappingURL=babylon.textureTools.js.map
  111932. var BABYLON;
  111933. (function (BABYLON) {
  111934. /**
  111935. * 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.
  111936. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  111937. */
  111938. var FramingBehavior = /** @class */ (function () {
  111939. function FramingBehavior() {
  111940. this._mode = FramingBehavior.FitFrustumSidesMode;
  111941. this._radiusScale = 1.0;
  111942. this._positionScale = 0.5;
  111943. this._defaultElevation = 0.3;
  111944. this._elevationReturnTime = 1500;
  111945. this._elevationReturnWaitTime = 1000;
  111946. this._zoomStopsAnimation = false;
  111947. this._framingTime = 1500;
  111948. /**
  111949. * Define if the behavior should automatically change the configured
  111950. * camera limits and sensibilities.
  111951. */
  111952. this.autoCorrectCameraLimitsAndSensibility = true;
  111953. this._isPointerDown = false;
  111954. this._lastInteractionTime = -Infinity;
  111955. // Framing control
  111956. this._animatables = new Array();
  111957. this._betaIsAnimating = false;
  111958. }
  111959. Object.defineProperty(FramingBehavior.prototype, "name", {
  111960. /**
  111961. * Gets the name of the behavior.
  111962. */
  111963. get: function () {
  111964. return "Framing";
  111965. },
  111966. enumerable: true,
  111967. configurable: true
  111968. });
  111969. Object.defineProperty(FramingBehavior.prototype, "mode", {
  111970. /**
  111971. * Gets current mode used by the behavior.
  111972. */
  111973. get: function () {
  111974. return this._mode;
  111975. },
  111976. /**
  111977. * Sets the current mode used by the behavior
  111978. */
  111979. set: function (mode) {
  111980. this._mode = mode;
  111981. },
  111982. enumerable: true,
  111983. configurable: true
  111984. });
  111985. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  111986. /**
  111987. * Gets the scale applied to the radius
  111988. */
  111989. get: function () {
  111990. return this._radiusScale;
  111991. },
  111992. /**
  111993. * Sets the scale applied to the radius (1 by default)
  111994. */
  111995. set: function (radius) {
  111996. this._radiusScale = radius;
  111997. },
  111998. enumerable: true,
  111999. configurable: true
  112000. });
  112001. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  112002. /**
  112003. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112004. */
  112005. get: function () {
  112006. return this._positionScale;
  112007. },
  112008. /**
  112009. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112010. */
  112011. set: function (scale) {
  112012. this._positionScale = scale;
  112013. },
  112014. enumerable: true,
  112015. configurable: true
  112016. });
  112017. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  112018. /**
  112019. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112020. * behaviour is triggered, in radians.
  112021. */
  112022. get: function () {
  112023. return this._defaultElevation;
  112024. },
  112025. /**
  112026. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112027. * behaviour is triggered, in radians.
  112028. */
  112029. set: function (elevation) {
  112030. this._defaultElevation = elevation;
  112031. },
  112032. enumerable: true,
  112033. configurable: true
  112034. });
  112035. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112036. /**
  112037. * Gets the time (in milliseconds) taken to return to the default beta position.
  112038. * Negative value indicates camera should not return to default.
  112039. */
  112040. get: function () {
  112041. return this._elevationReturnTime;
  112042. },
  112043. /**
  112044. * Sets the time (in milliseconds) taken to return to the default beta position.
  112045. * Negative value indicates camera should not return to default.
  112046. */
  112047. set: function (speed) {
  112048. this._elevationReturnTime = speed;
  112049. },
  112050. enumerable: true,
  112051. configurable: true
  112052. });
  112053. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112054. /**
  112055. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112056. */
  112057. get: function () {
  112058. return this._elevationReturnWaitTime;
  112059. },
  112060. /**
  112061. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112062. */
  112063. set: function (time) {
  112064. this._elevationReturnWaitTime = time;
  112065. },
  112066. enumerable: true,
  112067. configurable: true
  112068. });
  112069. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112070. /**
  112071. * Gets the flag that indicates if user zooming should stop animation.
  112072. */
  112073. get: function () {
  112074. return this._zoomStopsAnimation;
  112075. },
  112076. /**
  112077. * Sets the flag that indicates if user zooming should stop animation.
  112078. */
  112079. set: function (flag) {
  112080. this._zoomStopsAnimation = flag;
  112081. },
  112082. enumerable: true,
  112083. configurable: true
  112084. });
  112085. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112086. /**
  112087. * Gets the transition time when framing the mesh, in milliseconds
  112088. */
  112089. get: function () {
  112090. return this._framingTime;
  112091. },
  112092. /**
  112093. * Sets the transition time when framing the mesh, in milliseconds
  112094. */
  112095. set: function (time) {
  112096. this._framingTime = time;
  112097. },
  112098. enumerable: true,
  112099. configurable: true
  112100. });
  112101. /**
  112102. * Initializes the behavior.
  112103. */
  112104. FramingBehavior.prototype.init = function () {
  112105. // Do notihng
  112106. };
  112107. /**
  112108. * Attaches the behavior to its arc rotate camera.
  112109. * @param camera Defines the camera to attach the behavior to
  112110. */
  112111. FramingBehavior.prototype.attach = function (camera) {
  112112. var _this = this;
  112113. this._attachedCamera = camera;
  112114. var scene = this._attachedCamera.getScene();
  112115. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112116. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112117. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112118. _this._isPointerDown = true;
  112119. return;
  112120. }
  112121. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112122. _this._isPointerDown = false;
  112123. }
  112124. });
  112125. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112126. if (mesh) {
  112127. _this.zoomOnMesh(mesh);
  112128. }
  112129. });
  112130. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112131. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112132. _this._applyUserInteraction();
  112133. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112134. // back to the default position after a given timeout
  112135. _this._maintainCameraAboveGround();
  112136. });
  112137. };
  112138. /**
  112139. * Detaches the behavior from its current arc rotate camera.
  112140. */
  112141. FramingBehavior.prototype.detach = function () {
  112142. if (!this._attachedCamera) {
  112143. return;
  112144. }
  112145. var scene = this._attachedCamera.getScene();
  112146. if (this._onPrePointerObservableObserver) {
  112147. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112148. }
  112149. if (this._onAfterCheckInputsObserver) {
  112150. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112151. }
  112152. if (this._onMeshTargetChangedObserver) {
  112153. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112154. }
  112155. this._attachedCamera = null;
  112156. };
  112157. /**
  112158. * Targets the given mesh and updates zoom level accordingly.
  112159. * @param mesh The mesh to target.
  112160. * @param radius Optional. If a cached radius position already exists, overrides default.
  112161. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112162. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112163. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112164. */
  112165. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112166. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112167. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112168. mesh.computeWorldMatrix(true);
  112169. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112170. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112171. };
  112172. /**
  112173. * Targets the given mesh with its children and updates zoom level accordingly.
  112174. * @param mesh The mesh to target.
  112175. * @param radius Optional. If a cached radius position already exists, overrides default.
  112176. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112177. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112178. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112179. */
  112180. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112181. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112182. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112183. mesh.computeWorldMatrix(true);
  112184. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112185. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112186. };
  112187. /**
  112188. * Targets the given meshes with their children and updates zoom level accordingly.
  112189. * @param meshes The mesh to target.
  112190. * @param radius Optional. If a cached radius position already exists, overrides default.
  112191. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112192. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112193. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112194. */
  112195. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112196. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112197. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112198. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112199. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112200. for (var i = 0; i < meshes.length; i++) {
  112201. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112202. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112203. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112204. }
  112205. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112206. };
  112207. /**
  112208. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112209. * @param minimumWorld Determines the smaller position of the bounding box extend
  112210. * @param maximumWorld Determines the bigger position of the bounding box extend
  112211. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112212. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112213. */
  112214. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112215. var _this = this;
  112216. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112217. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112218. var zoomTarget;
  112219. if (!this._attachedCamera) {
  112220. return;
  112221. }
  112222. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112223. var bottom = minimumWorld.y;
  112224. var top = maximumWorld.y;
  112225. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112226. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112227. if (focusOnOriginXZ) {
  112228. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112229. }
  112230. else {
  112231. var centerWorld = minimumWorld.add(radiusWorld);
  112232. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112233. }
  112234. if (!this._vectorTransition) {
  112235. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112236. }
  112237. this._betaIsAnimating = true;
  112238. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112239. if (animatable) {
  112240. this._animatables.push(animatable);
  112241. }
  112242. // sets the radius and lower radius bounds
  112243. // Small delta ensures camera is not always at lower zoom limit.
  112244. var radius = 0;
  112245. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112246. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112247. if (this.autoCorrectCameraLimitsAndSensibility) {
  112248. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112249. }
  112250. radius = position;
  112251. }
  112252. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112253. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112254. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112255. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112256. }
  112257. }
  112258. // Set sensibilities
  112259. if (this.autoCorrectCameraLimitsAndSensibility) {
  112260. var extend = maximumWorld.subtract(minimumWorld).length();
  112261. this._attachedCamera.panningSensibility = 5000 / extend;
  112262. this._attachedCamera.wheelPrecision = 100 / radius;
  112263. }
  112264. // transition to new radius
  112265. if (!this._radiusTransition) {
  112266. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112267. }
  112268. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112269. _this.stopAllAnimations();
  112270. if (onAnimationEnd) {
  112271. onAnimationEnd();
  112272. }
  112273. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112274. _this._attachedCamera.storeState();
  112275. }
  112276. });
  112277. if (animatable) {
  112278. this._animatables.push(animatable);
  112279. }
  112280. };
  112281. /**
  112282. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112283. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112284. * frustum width.
  112285. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112286. * to fully enclose the mesh in the viewing frustum.
  112287. */
  112288. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112289. var size = maximumWorld.subtract(minimumWorld);
  112290. var boxVectorGlobalDiagonal = size.length();
  112291. var frustumSlope = this._getFrustumSlope();
  112292. // Formula for setting distance
  112293. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112294. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112295. // Horizon distance
  112296. var radius = radiusWithoutFraming * this._radiusScale;
  112297. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112298. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112299. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112300. var camera = this._attachedCamera;
  112301. if (!camera) {
  112302. return 0;
  112303. }
  112304. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112305. // Don't exceed the requested limit
  112306. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112307. }
  112308. // Don't exceed the upper radius limit
  112309. if (camera.upperRadiusLimit) {
  112310. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112311. }
  112312. return distance;
  112313. };
  112314. /**
  112315. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112316. * is automatically returned to its default position (expected to be above ground plane).
  112317. */
  112318. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112319. var _this = this;
  112320. if (this._elevationReturnTime < 0) {
  112321. return;
  112322. }
  112323. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112324. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112325. var limitBeta = Math.PI * 0.5;
  112326. // Bring the camera back up if below the ground plane
  112327. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112328. this._betaIsAnimating = true;
  112329. //Transition to new position
  112330. this.stopAllAnimations();
  112331. if (!this._betaTransition) {
  112332. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112333. }
  112334. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112335. _this._clearAnimationLocks();
  112336. _this.stopAllAnimations();
  112337. });
  112338. if (animatabe) {
  112339. this._animatables.push(animatabe);
  112340. }
  112341. }
  112342. };
  112343. /**
  112344. * Returns the frustum slope based on the canvas ratio and camera FOV
  112345. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112346. */
  112347. FramingBehavior.prototype._getFrustumSlope = function () {
  112348. // Calculate the viewport ratio
  112349. // Aspect Ratio is Height/Width.
  112350. var camera = this._attachedCamera;
  112351. if (!camera) {
  112352. return BABYLON.Vector2.Zero();
  112353. }
  112354. var engine = camera.getScene().getEngine();
  112355. var aspectRatio = engine.getAspectRatio(camera);
  112356. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112357. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112358. var frustumSlopeY = Math.tan(camera.fov / 2);
  112359. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112360. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112361. // along the forward vector.
  112362. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112363. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112364. };
  112365. /**
  112366. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112367. */
  112368. FramingBehavior.prototype._clearAnimationLocks = function () {
  112369. this._betaIsAnimating = false;
  112370. };
  112371. /**
  112372. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112373. */
  112374. FramingBehavior.prototype._applyUserInteraction = function () {
  112375. if (this.isUserIsMoving) {
  112376. this._lastInteractionTime = BABYLON.Tools.Now;
  112377. this.stopAllAnimations();
  112378. this._clearAnimationLocks();
  112379. }
  112380. };
  112381. /**
  112382. * Stops and removes all animations that have been applied to the camera
  112383. */
  112384. FramingBehavior.prototype.stopAllAnimations = function () {
  112385. if (this._attachedCamera) {
  112386. this._attachedCamera.animations = [];
  112387. }
  112388. while (this._animatables.length) {
  112389. if (this._animatables[0]) {
  112390. this._animatables[0].onAnimationEnd = null;
  112391. this._animatables[0].stop();
  112392. }
  112393. this._animatables.shift();
  112394. }
  112395. };
  112396. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112397. /**
  112398. * Gets a value indicating if the user is moving the camera
  112399. */
  112400. get: function () {
  112401. if (!this._attachedCamera) {
  112402. return false;
  112403. }
  112404. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112405. this._attachedCamera.inertialBetaOffset !== 0 ||
  112406. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112407. this._attachedCamera.inertialPanningX !== 0 ||
  112408. this._attachedCamera.inertialPanningY !== 0 ||
  112409. this._isPointerDown;
  112410. },
  112411. enumerable: true,
  112412. configurable: true
  112413. });
  112414. /**
  112415. * The easing function used by animations
  112416. */
  112417. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112418. /**
  112419. * The easing mode used by animations
  112420. */
  112421. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112422. // Statics
  112423. /**
  112424. * The camera can move all the way towards the mesh.
  112425. */
  112426. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112427. /**
  112428. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112429. */
  112430. FramingBehavior.FitFrustumSidesMode = 1;
  112431. return FramingBehavior;
  112432. }());
  112433. BABYLON.FramingBehavior = FramingBehavior;
  112434. })(BABYLON || (BABYLON = {}));
  112435. //# sourceMappingURL=babylon.framingBehavior.js.map
  112436. var BABYLON;
  112437. (function (BABYLON) {
  112438. /**
  112439. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112440. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112441. */
  112442. var BouncingBehavior = /** @class */ (function () {
  112443. function BouncingBehavior() {
  112444. /**
  112445. * The duration of the animation, in milliseconds
  112446. */
  112447. this.transitionDuration = 450;
  112448. /**
  112449. * Length of the distance animated by the transition when lower radius is reached
  112450. */
  112451. this.lowerRadiusTransitionRange = 2;
  112452. /**
  112453. * Length of the distance animated by the transition when upper radius is reached
  112454. */
  112455. this.upperRadiusTransitionRange = -2;
  112456. this._autoTransitionRange = false;
  112457. // Animations
  112458. this._radiusIsAnimating = false;
  112459. this._radiusBounceTransition = null;
  112460. this._animatables = new Array();
  112461. }
  112462. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112463. /**
  112464. * Gets the name of the behavior.
  112465. */
  112466. get: function () {
  112467. return "Bouncing";
  112468. },
  112469. enumerable: true,
  112470. configurable: true
  112471. });
  112472. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112473. /**
  112474. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112475. */
  112476. get: function () {
  112477. return this._autoTransitionRange;
  112478. },
  112479. /**
  112480. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112481. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112482. */
  112483. set: function (value) {
  112484. var _this = this;
  112485. if (this._autoTransitionRange === value) {
  112486. return;
  112487. }
  112488. this._autoTransitionRange = value;
  112489. var camera = this._attachedCamera;
  112490. if (!camera) {
  112491. return;
  112492. }
  112493. if (value) {
  112494. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112495. if (!mesh) {
  112496. return;
  112497. }
  112498. mesh.computeWorldMatrix(true);
  112499. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112500. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112501. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112502. });
  112503. }
  112504. else if (this._onMeshTargetChangedObserver) {
  112505. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112506. }
  112507. },
  112508. enumerable: true,
  112509. configurable: true
  112510. });
  112511. /**
  112512. * Initializes the behavior.
  112513. */
  112514. BouncingBehavior.prototype.init = function () {
  112515. // Do notihng
  112516. };
  112517. /**
  112518. * Attaches the behavior to its arc rotate camera.
  112519. * @param camera Defines the camera to attach the behavior to
  112520. */
  112521. BouncingBehavior.prototype.attach = function (camera) {
  112522. var _this = this;
  112523. this._attachedCamera = camera;
  112524. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112525. if (!_this._attachedCamera) {
  112526. return;
  112527. }
  112528. // Add the bounce animation to the lower radius limit
  112529. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112530. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112531. }
  112532. // Add the bounce animation to the upper radius limit
  112533. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112534. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112535. }
  112536. });
  112537. };
  112538. /**
  112539. * Detaches the behavior from its current arc rotate camera.
  112540. */
  112541. BouncingBehavior.prototype.detach = function () {
  112542. if (!this._attachedCamera) {
  112543. return;
  112544. }
  112545. if (this._onAfterCheckInputsObserver) {
  112546. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112547. }
  112548. if (this._onMeshTargetChangedObserver) {
  112549. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112550. }
  112551. this._attachedCamera = null;
  112552. };
  112553. /**
  112554. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112555. * @param radiusLimit The limit to check against.
  112556. * @return Bool to indicate if at limit.
  112557. */
  112558. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112559. if (!this._attachedCamera) {
  112560. return false;
  112561. }
  112562. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112563. return true;
  112564. }
  112565. return false;
  112566. };
  112567. /**
  112568. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112569. * @param radiusDelta The delta by which to animate to. Can be negative.
  112570. */
  112571. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112572. var _this = this;
  112573. if (!this._attachedCamera) {
  112574. return;
  112575. }
  112576. if (!this._radiusBounceTransition) {
  112577. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  112578. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  112579. }
  112580. // Prevent zoom until bounce has completed
  112581. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  112582. this._attachedCamera.wheelPrecision = Infinity;
  112583. this._attachedCamera.inertialRadiusOffset = 0;
  112584. // Animate to the radius limit
  112585. this.stopAllAnimations();
  112586. this._radiusIsAnimating = true;
  112587. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  112588. if (animatable) {
  112589. this._animatables.push(animatable);
  112590. }
  112591. };
  112592. /**
  112593. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  112594. */
  112595. BouncingBehavior.prototype._clearAnimationLocks = function () {
  112596. this._radiusIsAnimating = false;
  112597. if (this._attachedCamera) {
  112598. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  112599. }
  112600. };
  112601. /**
  112602. * Stops and removes all animations that have been applied to the camera
  112603. */
  112604. BouncingBehavior.prototype.stopAllAnimations = function () {
  112605. if (this._attachedCamera) {
  112606. this._attachedCamera.animations = [];
  112607. }
  112608. while (this._animatables.length) {
  112609. this._animatables[0].onAnimationEnd = null;
  112610. this._animatables[0].stop();
  112611. this._animatables.shift();
  112612. }
  112613. };
  112614. /**
  112615. * The easing function used by animations
  112616. */
  112617. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  112618. /**
  112619. * The easing mode used by animations
  112620. */
  112621. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  112622. return BouncingBehavior;
  112623. }());
  112624. BABYLON.BouncingBehavior = BouncingBehavior;
  112625. })(BABYLON || (BABYLON = {}));
  112626. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  112627. var BABYLON;
  112628. (function (BABYLON) {
  112629. /**
  112630. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  112631. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  112632. */
  112633. var AutoRotationBehavior = /** @class */ (function () {
  112634. function AutoRotationBehavior() {
  112635. this._zoomStopsAnimation = false;
  112636. this._idleRotationSpeed = 0.05;
  112637. this._idleRotationWaitTime = 2000;
  112638. this._idleRotationSpinupTime = 2000;
  112639. this._isPointerDown = false;
  112640. this._lastFrameTime = null;
  112641. this._lastInteractionTime = -Infinity;
  112642. this._cameraRotationSpeed = 0;
  112643. this._lastFrameRadius = 0;
  112644. }
  112645. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  112646. /**
  112647. * Gets the name of the behavior.
  112648. */
  112649. get: function () {
  112650. return "AutoRotation";
  112651. },
  112652. enumerable: true,
  112653. configurable: true
  112654. });
  112655. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  112656. /**
  112657. * Gets the flag that indicates if user zooming should stop animation.
  112658. */
  112659. get: function () {
  112660. return this._zoomStopsAnimation;
  112661. },
  112662. /**
  112663. * Sets the flag that indicates if user zooming should stop animation.
  112664. */
  112665. set: function (flag) {
  112666. this._zoomStopsAnimation = flag;
  112667. },
  112668. enumerable: true,
  112669. configurable: true
  112670. });
  112671. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  112672. /**
  112673. * Gets the default speed at which the camera rotates around the model.
  112674. */
  112675. get: function () {
  112676. return this._idleRotationSpeed;
  112677. },
  112678. /**
  112679. * Sets the default speed at which the camera rotates around the model.
  112680. */
  112681. set: function (speed) {
  112682. this._idleRotationSpeed = speed;
  112683. },
  112684. enumerable: true,
  112685. configurable: true
  112686. });
  112687. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  112688. /**
  112689. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  112690. */
  112691. get: function () {
  112692. return this._idleRotationWaitTime;
  112693. },
  112694. /**
  112695. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  112696. */
  112697. set: function (time) {
  112698. this._idleRotationWaitTime = time;
  112699. },
  112700. enumerable: true,
  112701. configurable: true
  112702. });
  112703. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  112704. /**
  112705. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  112706. */
  112707. get: function () {
  112708. return this._idleRotationSpinupTime;
  112709. },
  112710. /**
  112711. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  112712. */
  112713. set: function (time) {
  112714. this._idleRotationSpinupTime = time;
  112715. },
  112716. enumerable: true,
  112717. configurable: true
  112718. });
  112719. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  112720. /**
  112721. * Gets a value indicating if the camera is currently rotating because of this behavior
  112722. */
  112723. get: function () {
  112724. return Math.abs(this._cameraRotationSpeed) > 0;
  112725. },
  112726. enumerable: true,
  112727. configurable: true
  112728. });
  112729. /**
  112730. * Initializes the behavior.
  112731. */
  112732. AutoRotationBehavior.prototype.init = function () {
  112733. // Do notihng
  112734. };
  112735. /**
  112736. * Attaches the behavior to its arc rotate camera.
  112737. * @param camera Defines the camera to attach the behavior to
  112738. */
  112739. AutoRotationBehavior.prototype.attach = function (camera) {
  112740. var _this = this;
  112741. this._attachedCamera = camera;
  112742. var scene = this._attachedCamera.getScene();
  112743. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112744. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112745. _this._isPointerDown = true;
  112746. return;
  112747. }
  112748. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112749. _this._isPointerDown = false;
  112750. }
  112751. });
  112752. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112753. var now = BABYLON.Tools.Now;
  112754. var dt = 0;
  112755. if (_this._lastFrameTime != null) {
  112756. dt = now - _this._lastFrameTime;
  112757. }
  112758. _this._lastFrameTime = now;
  112759. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112760. _this._applyUserInteraction();
  112761. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  112762. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  112763. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  112764. // Step camera rotation by rotation speed
  112765. if (_this._attachedCamera) {
  112766. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  112767. }
  112768. });
  112769. };
  112770. /**
  112771. * Detaches the behavior from its current arc rotate camera.
  112772. */
  112773. AutoRotationBehavior.prototype.detach = function () {
  112774. if (!this._attachedCamera) {
  112775. return;
  112776. }
  112777. var scene = this._attachedCamera.getScene();
  112778. if (this._onPrePointerObservableObserver) {
  112779. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112780. }
  112781. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112782. this._attachedCamera = null;
  112783. };
  112784. /**
  112785. * Returns true if user is scrolling.
  112786. * @return true if user is scrolling.
  112787. */
  112788. AutoRotationBehavior.prototype._userIsZooming = function () {
  112789. if (!this._attachedCamera) {
  112790. return false;
  112791. }
  112792. return this._attachedCamera.inertialRadiusOffset !== 0;
  112793. };
  112794. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  112795. if (!this._attachedCamera) {
  112796. return false;
  112797. }
  112798. var zoomHasHitLimit = false;
  112799. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  112800. zoomHasHitLimit = true;
  112801. }
  112802. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  112803. this._lastFrameRadius = this._attachedCamera.radius;
  112804. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  112805. };
  112806. /**
  112807. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112808. */
  112809. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  112810. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  112811. this._lastInteractionTime = BABYLON.Tools.Now;
  112812. }
  112813. };
  112814. // Tools
  112815. AutoRotationBehavior.prototype._userIsMoving = function () {
  112816. if (!this._attachedCamera) {
  112817. return false;
  112818. }
  112819. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112820. this._attachedCamera.inertialBetaOffset !== 0 ||
  112821. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112822. this._attachedCamera.inertialPanningX !== 0 ||
  112823. this._attachedCamera.inertialPanningY !== 0 ||
  112824. this._isPointerDown;
  112825. };
  112826. return AutoRotationBehavior;
  112827. }());
  112828. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  112829. })(BABYLON || (BABYLON = {}));
  112830. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  112831. var BABYLON;
  112832. (function (BABYLON) {
  112833. /**
  112834. * Options to create the null engine
  112835. */
  112836. var NullEngineOptions = /** @class */ (function () {
  112837. function NullEngineOptions() {
  112838. /**
  112839. * Render width (Default: 512)
  112840. */
  112841. this.renderWidth = 512;
  112842. /**
  112843. * Render height (Default: 256)
  112844. */
  112845. this.renderHeight = 256;
  112846. /**
  112847. * Texture size (Default: 512)
  112848. */
  112849. this.textureSize = 512;
  112850. /**
  112851. * If delta time between frames should be constant
  112852. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112853. */
  112854. this.deterministicLockstep = false;
  112855. /**
  112856. * Maximum about of steps between frames (Default: 4)
  112857. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112858. */
  112859. this.lockstepMaxSteps = 4;
  112860. }
  112861. return NullEngineOptions;
  112862. }());
  112863. BABYLON.NullEngineOptions = NullEngineOptions;
  112864. /**
  112865. * The null engine class provides support for headless version of babylon.js.
  112866. * This can be used in server side scenario or for testing purposes
  112867. */
  112868. var NullEngine = /** @class */ (function (_super) {
  112869. __extends(NullEngine, _super);
  112870. function NullEngine(options) {
  112871. if (options === void 0) { options = new NullEngineOptions(); }
  112872. var _this = _super.call(this, null) || this;
  112873. if (options.deterministicLockstep === undefined) {
  112874. options.deterministicLockstep = false;
  112875. }
  112876. if (options.lockstepMaxSteps === undefined) {
  112877. options.lockstepMaxSteps = 4;
  112878. }
  112879. _this._options = options;
  112880. // Init caps
  112881. // We consider we are on a webgl1 capable device
  112882. _this._caps = new BABYLON.EngineCapabilities();
  112883. _this._caps.maxTexturesImageUnits = 16;
  112884. _this._caps.maxVertexTextureImageUnits = 16;
  112885. _this._caps.maxTextureSize = 512;
  112886. _this._caps.maxCubemapTextureSize = 512;
  112887. _this._caps.maxRenderTextureSize = 512;
  112888. _this._caps.maxVertexAttribs = 16;
  112889. _this._caps.maxVaryingVectors = 16;
  112890. _this._caps.maxFragmentUniformVectors = 16;
  112891. _this._caps.maxVertexUniformVectors = 16;
  112892. // Extensions
  112893. _this._caps.standardDerivatives = false;
  112894. _this._caps.astc = null;
  112895. _this._caps.s3tc = null;
  112896. _this._caps.pvrtc = null;
  112897. _this._caps.etc1 = null;
  112898. _this._caps.etc2 = null;
  112899. _this._caps.textureAnisotropicFilterExtension = null;
  112900. _this._caps.maxAnisotropy = 0;
  112901. _this._caps.uintIndices = false;
  112902. _this._caps.fragmentDepthSupported = false;
  112903. _this._caps.highPrecisionShaderSupported = true;
  112904. _this._caps.colorBufferFloat = false;
  112905. _this._caps.textureFloat = false;
  112906. _this._caps.textureFloatLinearFiltering = false;
  112907. _this._caps.textureFloatRender = false;
  112908. _this._caps.textureHalfFloat = false;
  112909. _this._caps.textureHalfFloatLinearFiltering = false;
  112910. _this._caps.textureHalfFloatRender = false;
  112911. _this._caps.textureLOD = false;
  112912. _this._caps.drawBuffersExtension = false;
  112913. _this._caps.depthTextureExtension = false;
  112914. _this._caps.vertexArrayObject = false;
  112915. _this._caps.instancedArrays = false;
  112916. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  112917. // Wrappers
  112918. if (typeof URL === "undefined") {
  112919. URL = {
  112920. createObjectURL: function () { },
  112921. revokeObjectURL: function () { }
  112922. };
  112923. }
  112924. if (typeof Blob === "undefined") {
  112925. Blob = function () { };
  112926. }
  112927. return _this;
  112928. }
  112929. /**
  112930. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112931. */
  112932. NullEngine.prototype.isDeterministicLockStep = function () {
  112933. return this._options.deterministicLockstep;
  112934. };
  112935. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  112936. NullEngine.prototype.getLockstepMaxSteps = function () {
  112937. return this._options.lockstepMaxSteps;
  112938. };
  112939. /**
  112940. * Sets hardware scaling, used to save performance if needed
  112941. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  112942. */
  112943. NullEngine.prototype.getHardwareScalingLevel = function () {
  112944. return 1.0;
  112945. };
  112946. NullEngine.prototype.createVertexBuffer = function (vertices) {
  112947. return {
  112948. capacity: 0,
  112949. references: 1,
  112950. is32Bits: false
  112951. };
  112952. };
  112953. NullEngine.prototype.createIndexBuffer = function (indices) {
  112954. return {
  112955. capacity: 0,
  112956. references: 1,
  112957. is32Bits: false
  112958. };
  112959. };
  112960. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  112961. if (stencil === void 0) { stencil = false; }
  112962. };
  112963. NullEngine.prototype.getRenderWidth = function (useScreen) {
  112964. if (useScreen === void 0) { useScreen = false; }
  112965. if (!useScreen && this._currentRenderTarget) {
  112966. return this._currentRenderTarget.width;
  112967. }
  112968. return this._options.renderWidth;
  112969. };
  112970. NullEngine.prototype.getRenderHeight = function (useScreen) {
  112971. if (useScreen === void 0) { useScreen = false; }
  112972. if (!useScreen && this._currentRenderTarget) {
  112973. return this._currentRenderTarget.height;
  112974. }
  112975. return this._options.renderHeight;
  112976. };
  112977. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  112978. this._cachedViewport = viewport;
  112979. };
  112980. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  112981. return {
  112982. transformFeedback: null,
  112983. __SPECTOR_rebuildProgram: null
  112984. };
  112985. };
  112986. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  112987. return [];
  112988. };
  112989. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  112990. return [];
  112991. };
  112992. NullEngine.prototype.bindSamplers = function (effect) {
  112993. this._currentEffect = null;
  112994. };
  112995. NullEngine.prototype.enableEffect = function (effect) {
  112996. this._currentEffect = effect;
  112997. if (effect.onBind) {
  112998. effect.onBind(effect);
  112999. }
  113000. if (effect._onBindObservable) {
  113001. effect._onBindObservable.notifyObservers(effect);
  113002. }
  113003. };
  113004. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  113005. if (zOffset === void 0) { zOffset = 0; }
  113006. if (reverseSide === void 0) { reverseSide = false; }
  113007. };
  113008. NullEngine.prototype.setIntArray = function (uniform, array) {
  113009. };
  113010. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  113011. };
  113012. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  113013. };
  113014. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  113015. };
  113016. NullEngine.prototype.setFloatArray = function (uniform, array) {
  113017. };
  113018. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  113019. };
  113020. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  113021. };
  113022. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  113023. };
  113024. NullEngine.prototype.setArray = function (uniform, array) {
  113025. };
  113026. NullEngine.prototype.setArray2 = function (uniform, array) {
  113027. };
  113028. NullEngine.prototype.setArray3 = function (uniform, array) {
  113029. };
  113030. NullEngine.prototype.setArray4 = function (uniform, array) {
  113031. };
  113032. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113033. };
  113034. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113035. };
  113036. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113037. };
  113038. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113039. };
  113040. NullEngine.prototype.setFloat = function (uniform, value) {
  113041. };
  113042. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113043. };
  113044. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113045. };
  113046. NullEngine.prototype.setBool = function (uniform, bool) {
  113047. };
  113048. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113049. };
  113050. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113051. };
  113052. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113053. };
  113054. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113055. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113056. if (this._alphaMode === mode) {
  113057. return;
  113058. }
  113059. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113060. if (!noDepthWriteChange) {
  113061. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113062. }
  113063. this._alphaMode = mode;
  113064. };
  113065. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113066. };
  113067. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113068. if (this.preventCacheWipeBetweenFrames) {
  113069. return;
  113070. }
  113071. this.resetTextureCache();
  113072. this._currentEffect = null;
  113073. if (bruteForce) {
  113074. this._currentProgram = null;
  113075. this._stencilState.reset();
  113076. this._depthCullingState.reset();
  113077. this._alphaState.reset();
  113078. }
  113079. this._cachedVertexBuffers = null;
  113080. this._cachedIndexBuffer = null;
  113081. this._cachedEffectForVertexBuffers = null;
  113082. };
  113083. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113084. };
  113085. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113086. };
  113087. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113088. };
  113089. /** @hidden */
  113090. NullEngine.prototype._createTexture = function () {
  113091. return {};
  113092. };
  113093. /** @hidden */
  113094. NullEngine.prototype._releaseTexture = function (texture) {
  113095. };
  113096. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113097. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113098. if (onLoad === void 0) { onLoad = null; }
  113099. if (onError === void 0) { onError = null; }
  113100. if (buffer === void 0) { buffer = null; }
  113101. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113102. var url = String(urlArg);
  113103. texture.url = url;
  113104. texture.generateMipMaps = !noMipmap;
  113105. texture.samplingMode = samplingMode;
  113106. texture.invertY = invertY;
  113107. texture.baseWidth = this._options.textureSize;
  113108. texture.baseHeight = this._options.textureSize;
  113109. texture.width = this._options.textureSize;
  113110. texture.height = this._options.textureSize;
  113111. if (format) {
  113112. texture.format = format;
  113113. }
  113114. texture.isReady = true;
  113115. if (onLoad) {
  113116. onLoad();
  113117. }
  113118. this._internalTexturesCache.push(texture);
  113119. return texture;
  113120. };
  113121. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113122. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113123. if (options !== undefined && typeof options === "object") {
  113124. fullOptions.generateMipMaps = options.generateMipMaps;
  113125. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113126. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113127. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113128. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113129. }
  113130. else {
  113131. fullOptions.generateMipMaps = options;
  113132. fullOptions.generateDepthBuffer = true;
  113133. fullOptions.generateStencilBuffer = false;
  113134. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113135. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113136. }
  113137. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113138. var width = size.width || size;
  113139. var height = size.height || size;
  113140. texture._depthStencilBuffer = {};
  113141. texture._framebuffer = {};
  113142. texture.baseWidth = width;
  113143. texture.baseHeight = height;
  113144. texture.width = width;
  113145. texture.height = height;
  113146. texture.isReady = true;
  113147. texture.samples = 1;
  113148. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113149. texture.samplingMode = fullOptions.samplingMode;
  113150. texture.type = fullOptions.type;
  113151. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113152. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113153. this._internalTexturesCache.push(texture);
  113154. return texture;
  113155. };
  113156. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113157. texture.samplingMode = samplingMode;
  113158. };
  113159. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113160. if (this._currentRenderTarget) {
  113161. this.unBindFramebuffer(this._currentRenderTarget);
  113162. }
  113163. this._currentRenderTarget = texture;
  113164. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113165. if (this._cachedViewport && !forceFullscreenViewport) {
  113166. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113167. }
  113168. };
  113169. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113170. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113171. this._currentRenderTarget = null;
  113172. if (onBeforeUnbind) {
  113173. if (texture._MSAAFramebuffer) {
  113174. this._currentFramebuffer = texture._framebuffer;
  113175. }
  113176. onBeforeUnbind();
  113177. }
  113178. this._currentFramebuffer = null;
  113179. };
  113180. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113181. var vbo = {
  113182. capacity: 1,
  113183. references: 1,
  113184. is32Bits: false
  113185. };
  113186. return vbo;
  113187. };
  113188. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113189. if (premulAlpha === void 0) { premulAlpha = false; }
  113190. };
  113191. /**
  113192. * @hidden
  113193. * Get the current error code of the webGL context
  113194. * @returns the error code
  113195. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113196. */
  113197. NullEngine.prototype.getError = function () {
  113198. return 0;
  113199. };
  113200. /** @hidden */
  113201. NullEngine.prototype._getUnpackAlignement = function () {
  113202. return 1;
  113203. };
  113204. /** @hidden */
  113205. NullEngine.prototype._unpackFlipY = function (value) {
  113206. };
  113207. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113208. if (offset === void 0) { offset = 0; }
  113209. };
  113210. /**
  113211. * Updates a dynamic vertex buffer.
  113212. * @param vertexBuffer the vertex buffer to update
  113213. * @param data the data used to update the vertex buffer
  113214. * @param byteOffset the byte offset of the data (optional)
  113215. * @param byteLength the byte length of the data (optional)
  113216. */
  113217. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113218. };
  113219. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113220. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113221. this._boundTexturesCache[this._activeChannel] = texture;
  113222. return true;
  113223. }
  113224. return false;
  113225. };
  113226. /** @hidden */
  113227. NullEngine.prototype._bindTexture = function (channel, texture) {
  113228. if (channel < 0) {
  113229. return;
  113230. }
  113231. this._bindTextureDirectly(0, texture);
  113232. };
  113233. /** @hidden */
  113234. NullEngine.prototype._releaseBuffer = function (buffer) {
  113235. buffer.references--;
  113236. if (buffer.references === 0) {
  113237. return true;
  113238. }
  113239. return false;
  113240. };
  113241. NullEngine.prototype.releaseEffects = function () {
  113242. };
  113243. NullEngine.prototype.displayLoadingUI = function () {
  113244. };
  113245. NullEngine.prototype.hideLoadingUI = function () {
  113246. };
  113247. /** @hidden */
  113248. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113249. if (faceIndex === void 0) { faceIndex = 0; }
  113250. if (lod === void 0) { lod = 0; }
  113251. };
  113252. /** @hidden */
  113253. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113254. if (faceIndex === void 0) { faceIndex = 0; }
  113255. if (lod === void 0) { lod = 0; }
  113256. };
  113257. /** @hidden */
  113258. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113259. if (faceIndex === void 0) { faceIndex = 0; }
  113260. if (lod === void 0) { lod = 0; }
  113261. };
  113262. /** @hidden */
  113263. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113264. if (faceIndex === void 0) { faceIndex = 0; }
  113265. if (lod === void 0) { lod = 0; }
  113266. };
  113267. return NullEngine;
  113268. }(BABYLON.Engine));
  113269. BABYLON.NullEngine = NullEngine;
  113270. })(BABYLON || (BABYLON = {}));
  113271. //# sourceMappingURL=babylon.nullEngine.js.map
  113272. var BABYLON;
  113273. (function (BABYLON) {
  113274. /**
  113275. * This class can be used to get instrumentation data from a Babylon engine
  113276. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113277. */
  113278. var EngineInstrumentation = /** @class */ (function () {
  113279. /**
  113280. * Instantiates a new engine instrumentation.
  113281. * This class can be used to get instrumentation data from a Babylon engine
  113282. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113283. * @param engine Defines the engine to instrument
  113284. */
  113285. function EngineInstrumentation(
  113286. /**
  113287. * Define the instrumented engine.
  113288. */
  113289. engine) {
  113290. this.engine = engine;
  113291. this._captureGPUFrameTime = false;
  113292. this._gpuFrameTime = new BABYLON.PerfCounter();
  113293. this._captureShaderCompilationTime = false;
  113294. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113295. // Observers
  113296. this._onBeginFrameObserver = null;
  113297. this._onEndFrameObserver = null;
  113298. this._onBeforeShaderCompilationObserver = null;
  113299. this._onAfterShaderCompilationObserver = null;
  113300. }
  113301. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113302. // Properties
  113303. /**
  113304. * Gets the perf counter used for GPU frame time
  113305. */
  113306. get: function () {
  113307. return this._gpuFrameTime;
  113308. },
  113309. enumerable: true,
  113310. configurable: true
  113311. });
  113312. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113313. /**
  113314. * Gets the GPU frame time capture status
  113315. */
  113316. get: function () {
  113317. return this._captureGPUFrameTime;
  113318. },
  113319. /**
  113320. * Enable or disable the GPU frame time capture
  113321. */
  113322. set: function (value) {
  113323. var _this = this;
  113324. if (value === this._captureGPUFrameTime) {
  113325. return;
  113326. }
  113327. this._captureGPUFrameTime = value;
  113328. if (value) {
  113329. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113330. if (!_this._gpuFrameTimeToken) {
  113331. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113332. }
  113333. });
  113334. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113335. if (!_this._gpuFrameTimeToken) {
  113336. return;
  113337. }
  113338. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113339. if (time > -1) {
  113340. _this._gpuFrameTimeToken = null;
  113341. _this._gpuFrameTime.fetchNewFrame();
  113342. _this._gpuFrameTime.addCount(time, true);
  113343. }
  113344. });
  113345. }
  113346. else {
  113347. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113348. this._onBeginFrameObserver = null;
  113349. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113350. this._onEndFrameObserver = null;
  113351. }
  113352. },
  113353. enumerable: true,
  113354. configurable: true
  113355. });
  113356. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113357. /**
  113358. * Gets the perf counter used for shader compilation time
  113359. */
  113360. get: function () {
  113361. return this._shaderCompilationTime;
  113362. },
  113363. enumerable: true,
  113364. configurable: true
  113365. });
  113366. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113367. /**
  113368. * Gets the shader compilation time capture status
  113369. */
  113370. get: function () {
  113371. return this._captureShaderCompilationTime;
  113372. },
  113373. /**
  113374. * Enable or disable the shader compilation time capture
  113375. */
  113376. set: function (value) {
  113377. var _this = this;
  113378. if (value === this._captureShaderCompilationTime) {
  113379. return;
  113380. }
  113381. this._captureShaderCompilationTime = value;
  113382. if (value) {
  113383. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113384. _this._shaderCompilationTime.fetchNewFrame();
  113385. _this._shaderCompilationTime.beginMonitoring();
  113386. });
  113387. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113388. _this._shaderCompilationTime.endMonitoring();
  113389. });
  113390. }
  113391. else {
  113392. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113393. this._onBeforeShaderCompilationObserver = null;
  113394. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113395. this._onAfterShaderCompilationObserver = null;
  113396. }
  113397. },
  113398. enumerable: true,
  113399. configurable: true
  113400. });
  113401. /**
  113402. * Dispose and release associated resources.
  113403. */
  113404. EngineInstrumentation.prototype.dispose = function () {
  113405. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113406. this._onBeginFrameObserver = null;
  113407. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113408. this._onEndFrameObserver = null;
  113409. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113410. this._onBeforeShaderCompilationObserver = null;
  113411. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113412. this._onAfterShaderCompilationObserver = null;
  113413. this.engine = null;
  113414. };
  113415. return EngineInstrumentation;
  113416. }());
  113417. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113418. })(BABYLON || (BABYLON = {}));
  113419. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113420. var BABYLON;
  113421. (function (BABYLON) {
  113422. /**
  113423. * This class can be used to get instrumentation data from a Babylon engine
  113424. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113425. */
  113426. var SceneInstrumentation = /** @class */ (function () {
  113427. /**
  113428. * Instantiates a new scene instrumentation.
  113429. * This class can be used to get instrumentation data from a Babylon engine
  113430. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113431. * @param scene Defines the scene to instrument
  113432. */
  113433. function SceneInstrumentation(
  113434. /**
  113435. * Defines the scene to instrument
  113436. */
  113437. scene) {
  113438. var _this = this;
  113439. this.scene = scene;
  113440. this._captureActiveMeshesEvaluationTime = false;
  113441. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113442. this._captureRenderTargetsRenderTime = false;
  113443. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113444. this._captureFrameTime = false;
  113445. this._frameTime = new BABYLON.PerfCounter();
  113446. this._captureRenderTime = false;
  113447. this._renderTime = new BABYLON.PerfCounter();
  113448. this._captureInterFrameTime = false;
  113449. this._interFrameTime = new BABYLON.PerfCounter();
  113450. this._captureParticlesRenderTime = false;
  113451. this._particlesRenderTime = new BABYLON.PerfCounter();
  113452. this._captureSpritesRenderTime = false;
  113453. this._spritesRenderTime = new BABYLON.PerfCounter();
  113454. this._capturePhysicsTime = false;
  113455. this._physicsTime = new BABYLON.PerfCounter();
  113456. this._captureAnimationsTime = false;
  113457. this._animationsTime = new BABYLON.PerfCounter();
  113458. this._captureCameraRenderTime = false;
  113459. this._cameraRenderTime = new BABYLON.PerfCounter();
  113460. // Observers
  113461. this._onBeforeActiveMeshesEvaluationObserver = null;
  113462. this._onAfterActiveMeshesEvaluationObserver = null;
  113463. this._onBeforeRenderTargetsRenderObserver = null;
  113464. this._onAfterRenderTargetsRenderObserver = null;
  113465. this._onAfterRenderObserver = null;
  113466. this._onBeforeDrawPhaseObserver = null;
  113467. this._onAfterDrawPhaseObserver = null;
  113468. this._onBeforeAnimationsObserver = null;
  113469. this._onBeforeParticlesRenderingObserver = null;
  113470. this._onAfterParticlesRenderingObserver = null;
  113471. this._onBeforeSpritesRenderingObserver = null;
  113472. this._onAfterSpritesRenderingObserver = null;
  113473. this._onBeforePhysicsObserver = null;
  113474. this._onAfterPhysicsObserver = null;
  113475. this._onAfterAnimationsObserver = null;
  113476. this._onBeforeCameraRenderObserver = null;
  113477. this._onAfterCameraRenderObserver = null;
  113478. // Before render
  113479. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113480. if (_this._captureActiveMeshesEvaluationTime) {
  113481. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113482. }
  113483. if (_this._captureRenderTargetsRenderTime) {
  113484. _this._renderTargetsRenderTime.fetchNewFrame();
  113485. }
  113486. if (_this._captureFrameTime) {
  113487. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113488. _this._frameTime.beginMonitoring();
  113489. }
  113490. if (_this._captureInterFrameTime) {
  113491. _this._interFrameTime.endMonitoring();
  113492. }
  113493. if (_this._captureParticlesRenderTime) {
  113494. _this._particlesRenderTime.fetchNewFrame();
  113495. }
  113496. if (_this._captureSpritesRenderTime) {
  113497. _this._spritesRenderTime.fetchNewFrame();
  113498. }
  113499. if (_this._captureAnimationsTime) {
  113500. _this._animationsTime.beginMonitoring();
  113501. }
  113502. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113503. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113504. });
  113505. // After render
  113506. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113507. if (_this._captureFrameTime) {
  113508. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113509. _this._frameTime.endMonitoring();
  113510. }
  113511. if (_this._captureRenderTime) {
  113512. _this._renderTime.endMonitoring(false);
  113513. }
  113514. if (_this._captureInterFrameTime) {
  113515. _this._interFrameTime.beginMonitoring();
  113516. }
  113517. });
  113518. }
  113519. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113520. // Properties
  113521. /**
  113522. * Gets the perf counter used for active meshes evaluation time
  113523. */
  113524. get: function () {
  113525. return this._activeMeshesEvaluationTime;
  113526. },
  113527. enumerable: true,
  113528. configurable: true
  113529. });
  113530. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113531. /**
  113532. * Gets the active meshes evaluation time capture status
  113533. */
  113534. get: function () {
  113535. return this._captureActiveMeshesEvaluationTime;
  113536. },
  113537. /**
  113538. * Enable or disable the active meshes evaluation time capture
  113539. */
  113540. set: function (value) {
  113541. var _this = this;
  113542. if (value === this._captureActiveMeshesEvaluationTime) {
  113543. return;
  113544. }
  113545. this._captureActiveMeshesEvaluationTime = value;
  113546. if (value) {
  113547. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113548. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113549. _this._activeMeshesEvaluationTime.beginMonitoring();
  113550. });
  113551. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113552. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113553. _this._activeMeshesEvaluationTime.endMonitoring();
  113554. });
  113555. }
  113556. else {
  113557. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113558. this._onBeforeActiveMeshesEvaluationObserver = null;
  113559. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113560. this._onAfterActiveMeshesEvaluationObserver = null;
  113561. }
  113562. },
  113563. enumerable: true,
  113564. configurable: true
  113565. });
  113566. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113567. /**
  113568. * Gets the perf counter used for render targets render time
  113569. */
  113570. get: function () {
  113571. return this._renderTargetsRenderTime;
  113572. },
  113573. enumerable: true,
  113574. configurable: true
  113575. });
  113576. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  113577. /**
  113578. * Gets the render targets render time capture status
  113579. */
  113580. get: function () {
  113581. return this._captureRenderTargetsRenderTime;
  113582. },
  113583. /**
  113584. * Enable or disable the render targets render time capture
  113585. */
  113586. set: function (value) {
  113587. var _this = this;
  113588. if (value === this._captureRenderTargetsRenderTime) {
  113589. return;
  113590. }
  113591. this._captureRenderTargetsRenderTime = value;
  113592. if (value) {
  113593. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  113594. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  113595. _this._renderTargetsRenderTime.beginMonitoring();
  113596. });
  113597. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  113598. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  113599. _this._renderTargetsRenderTime.endMonitoring(false);
  113600. });
  113601. }
  113602. else {
  113603. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113604. this._onBeforeRenderTargetsRenderObserver = null;
  113605. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113606. this._onAfterRenderTargetsRenderObserver = null;
  113607. }
  113608. },
  113609. enumerable: true,
  113610. configurable: true
  113611. });
  113612. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  113613. /**
  113614. * Gets the perf counter used for particles render time
  113615. */
  113616. get: function () {
  113617. return this._particlesRenderTime;
  113618. },
  113619. enumerable: true,
  113620. configurable: true
  113621. });
  113622. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  113623. /**
  113624. * Gets the particles render time capture status
  113625. */
  113626. get: function () {
  113627. return this._captureParticlesRenderTime;
  113628. },
  113629. /**
  113630. * Enable or disable the particles render time capture
  113631. */
  113632. set: function (value) {
  113633. var _this = this;
  113634. if (value === this._captureParticlesRenderTime) {
  113635. return;
  113636. }
  113637. this._captureParticlesRenderTime = value;
  113638. if (value) {
  113639. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  113640. BABYLON.Tools.StartPerformanceCounter("Particles");
  113641. _this._particlesRenderTime.beginMonitoring();
  113642. });
  113643. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  113644. BABYLON.Tools.EndPerformanceCounter("Particles");
  113645. _this._particlesRenderTime.endMonitoring(false);
  113646. });
  113647. }
  113648. else {
  113649. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113650. this._onBeforeParticlesRenderingObserver = null;
  113651. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113652. this._onAfterParticlesRenderingObserver = null;
  113653. }
  113654. },
  113655. enumerable: true,
  113656. configurable: true
  113657. });
  113658. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  113659. /**
  113660. * Gets the perf counter used for sprites render time
  113661. */
  113662. get: function () {
  113663. return this._spritesRenderTime;
  113664. },
  113665. enumerable: true,
  113666. configurable: true
  113667. });
  113668. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  113669. /**
  113670. * Gets the sprites render time capture status
  113671. */
  113672. get: function () {
  113673. return this._captureSpritesRenderTime;
  113674. },
  113675. /**
  113676. * Enable or disable the sprites render time capture
  113677. */
  113678. set: function (value) {
  113679. var _this = this;
  113680. if (value === this._captureSpritesRenderTime) {
  113681. return;
  113682. }
  113683. this._captureSpritesRenderTime = value;
  113684. if (!this.scene.spriteManagers) {
  113685. return;
  113686. }
  113687. if (value) {
  113688. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  113689. BABYLON.Tools.StartPerformanceCounter("Sprites");
  113690. _this._spritesRenderTime.beginMonitoring();
  113691. });
  113692. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  113693. BABYLON.Tools.EndPerformanceCounter("Sprites");
  113694. _this._spritesRenderTime.endMonitoring(false);
  113695. });
  113696. }
  113697. else {
  113698. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  113699. this._onBeforeSpritesRenderingObserver = null;
  113700. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  113701. this._onAfterSpritesRenderingObserver = null;
  113702. }
  113703. },
  113704. enumerable: true,
  113705. configurable: true
  113706. });
  113707. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  113708. /**
  113709. * Gets the perf counter used for physics time
  113710. */
  113711. get: function () {
  113712. return this._physicsTime;
  113713. },
  113714. enumerable: true,
  113715. configurable: true
  113716. });
  113717. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  113718. /**
  113719. * Gets the physics time capture status
  113720. */
  113721. get: function () {
  113722. return this._capturePhysicsTime;
  113723. },
  113724. /**
  113725. * Enable or disable the physics time capture
  113726. */
  113727. set: function (value) {
  113728. var _this = this;
  113729. if (value === this._capturePhysicsTime) {
  113730. return;
  113731. }
  113732. if (!this.scene.onBeforePhysicsObservable) {
  113733. return;
  113734. }
  113735. this._capturePhysicsTime = value;
  113736. if (value) {
  113737. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  113738. BABYLON.Tools.StartPerformanceCounter("Physics");
  113739. _this._physicsTime.beginMonitoring();
  113740. });
  113741. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  113742. BABYLON.Tools.EndPerformanceCounter("Physics");
  113743. _this._physicsTime.endMonitoring();
  113744. });
  113745. }
  113746. else {
  113747. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  113748. this._onBeforePhysicsObserver = null;
  113749. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  113750. this._onAfterPhysicsObserver = null;
  113751. }
  113752. },
  113753. enumerable: true,
  113754. configurable: true
  113755. });
  113756. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  113757. /**
  113758. * Gets the perf counter used for animations time
  113759. */
  113760. get: function () {
  113761. return this._animationsTime;
  113762. },
  113763. enumerable: true,
  113764. configurable: true
  113765. });
  113766. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  113767. /**
  113768. * Gets the animations time capture status
  113769. */
  113770. get: function () {
  113771. return this._captureAnimationsTime;
  113772. },
  113773. /**
  113774. * Enable or disable the animations time capture
  113775. */
  113776. set: function (value) {
  113777. var _this = this;
  113778. if (value === this._captureAnimationsTime) {
  113779. return;
  113780. }
  113781. this._captureAnimationsTime = value;
  113782. if (value) {
  113783. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  113784. _this._animationsTime.endMonitoring();
  113785. });
  113786. }
  113787. else {
  113788. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  113789. this._onAfterAnimationsObserver = null;
  113790. }
  113791. },
  113792. enumerable: true,
  113793. configurable: true
  113794. });
  113795. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  113796. /**
  113797. * Gets the perf counter used for frame time capture
  113798. */
  113799. get: function () {
  113800. return this._frameTime;
  113801. },
  113802. enumerable: true,
  113803. configurable: true
  113804. });
  113805. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  113806. /**
  113807. * Gets the frame time capture status
  113808. */
  113809. get: function () {
  113810. return this._captureFrameTime;
  113811. },
  113812. /**
  113813. * Enable or disable the frame time capture
  113814. */
  113815. set: function (value) {
  113816. this._captureFrameTime = value;
  113817. },
  113818. enumerable: true,
  113819. configurable: true
  113820. });
  113821. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  113822. /**
  113823. * Gets the perf counter used for inter-frames time capture
  113824. */
  113825. get: function () {
  113826. return this._interFrameTime;
  113827. },
  113828. enumerable: true,
  113829. configurable: true
  113830. });
  113831. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  113832. /**
  113833. * Gets the inter-frames time capture status
  113834. */
  113835. get: function () {
  113836. return this._captureInterFrameTime;
  113837. },
  113838. /**
  113839. * Enable or disable the inter-frames time capture
  113840. */
  113841. set: function (value) {
  113842. this._captureInterFrameTime = value;
  113843. },
  113844. enumerable: true,
  113845. configurable: true
  113846. });
  113847. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  113848. /**
  113849. * Gets the perf counter used for render time capture
  113850. */
  113851. get: function () {
  113852. return this._renderTime;
  113853. },
  113854. enumerable: true,
  113855. configurable: true
  113856. });
  113857. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  113858. /**
  113859. * Gets the render time capture status
  113860. */
  113861. get: function () {
  113862. return this._captureRenderTime;
  113863. },
  113864. /**
  113865. * Enable or disable the render time capture
  113866. */
  113867. set: function (value) {
  113868. var _this = this;
  113869. if (value === this._captureRenderTime) {
  113870. return;
  113871. }
  113872. this._captureRenderTime = value;
  113873. if (value) {
  113874. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  113875. _this._renderTime.beginMonitoring();
  113876. BABYLON.Tools.StartPerformanceCounter("Main render");
  113877. });
  113878. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  113879. _this._renderTime.endMonitoring(false);
  113880. BABYLON.Tools.EndPerformanceCounter("Main render");
  113881. });
  113882. }
  113883. else {
  113884. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  113885. this._onBeforeDrawPhaseObserver = null;
  113886. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  113887. this._onAfterDrawPhaseObserver = null;
  113888. }
  113889. },
  113890. enumerable: true,
  113891. configurable: true
  113892. });
  113893. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  113894. /**
  113895. * Gets the perf counter used for camera render time capture
  113896. */
  113897. get: function () {
  113898. return this._cameraRenderTime;
  113899. },
  113900. enumerable: true,
  113901. configurable: true
  113902. });
  113903. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  113904. /**
  113905. * Gets the camera render time capture status
  113906. */
  113907. get: function () {
  113908. return this._captureCameraRenderTime;
  113909. },
  113910. /**
  113911. * Enable or disable the camera render time capture
  113912. */
  113913. set: function (value) {
  113914. var _this = this;
  113915. if (value === this._captureCameraRenderTime) {
  113916. return;
  113917. }
  113918. this._captureCameraRenderTime = value;
  113919. if (value) {
  113920. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  113921. _this._cameraRenderTime.beginMonitoring();
  113922. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  113923. });
  113924. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  113925. _this._cameraRenderTime.endMonitoring(false);
  113926. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  113927. });
  113928. }
  113929. else {
  113930. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  113931. this._onBeforeCameraRenderObserver = null;
  113932. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  113933. this._onAfterCameraRenderObserver = null;
  113934. }
  113935. },
  113936. enumerable: true,
  113937. configurable: true
  113938. });
  113939. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  113940. /**
  113941. * Gets the perf counter used for draw calls
  113942. */
  113943. get: function () {
  113944. return this.scene.getEngine()._drawCalls;
  113945. },
  113946. enumerable: true,
  113947. configurable: true
  113948. });
  113949. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  113950. /**
  113951. * Gets the perf counter used for texture collisions
  113952. */
  113953. get: function () {
  113954. return this.scene.getEngine()._textureCollisions;
  113955. },
  113956. enumerable: true,
  113957. configurable: true
  113958. });
  113959. /**
  113960. * Dispose and release associated resources.
  113961. */
  113962. SceneInstrumentation.prototype.dispose = function () {
  113963. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  113964. this._onAfterRenderObserver = null;
  113965. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113966. this._onBeforeActiveMeshesEvaluationObserver = null;
  113967. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113968. this._onAfterActiveMeshesEvaluationObserver = null;
  113969. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113970. this._onBeforeRenderTargetsRenderObserver = null;
  113971. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113972. this._onAfterRenderTargetsRenderObserver = null;
  113973. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  113974. this._onBeforeAnimationsObserver = null;
  113975. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113976. this._onBeforeParticlesRenderingObserver = null;
  113977. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113978. this._onAfterParticlesRenderingObserver = null;
  113979. if (this._onBeforeSpritesRenderingObserver) {
  113980. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  113981. this._onBeforeSpritesRenderingObserver = null;
  113982. }
  113983. if (this._onAfterSpritesRenderingObserver) {
  113984. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  113985. this._onAfterSpritesRenderingObserver = null;
  113986. }
  113987. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  113988. this._onBeforeDrawPhaseObserver = null;
  113989. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  113990. this._onAfterDrawPhaseObserver = null;
  113991. if (this._onBeforePhysicsObserver) {
  113992. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  113993. this._onBeforePhysicsObserver = null;
  113994. }
  113995. if (this._onAfterPhysicsObserver) {
  113996. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  113997. this._onAfterPhysicsObserver = null;
  113998. }
  113999. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114000. this._onAfterAnimationsObserver = null;
  114001. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114002. this._onBeforeCameraRenderObserver = null;
  114003. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114004. this._onAfterCameraRenderObserver = null;
  114005. this.scene = null;
  114006. };
  114007. return SceneInstrumentation;
  114008. }());
  114009. BABYLON.SceneInstrumentation = SceneInstrumentation;
  114010. })(BABYLON || (BABYLON = {}));
  114011. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  114012. var BABYLON;
  114013. (function (BABYLON) {
  114014. /**
  114015. * @hidden
  114016. **/
  114017. var _TimeToken = /** @class */ (function () {
  114018. function _TimeToken() {
  114019. this._timeElapsedQueryEnded = false;
  114020. }
  114021. return _TimeToken;
  114022. }());
  114023. BABYLON._TimeToken = _TimeToken;
  114024. })(BABYLON || (BABYLON = {}));
  114025. //# sourceMappingURL=babylon.timeToken.js.map
  114026. var BABYLON;
  114027. (function (BABYLON) {
  114028. /**
  114029. * Background material defines definition.
  114030. * @hidden Mainly internal Use
  114031. */
  114032. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114033. __extends(BackgroundMaterialDefines, _super);
  114034. /**
  114035. * Constructor of the defines.
  114036. */
  114037. function BackgroundMaterialDefines() {
  114038. var _this = _super.call(this) || this;
  114039. /**
  114040. * True if the diffuse texture is in use.
  114041. */
  114042. _this.DIFFUSE = false;
  114043. /**
  114044. * The direct UV channel to use.
  114045. */
  114046. _this.DIFFUSEDIRECTUV = 0;
  114047. /**
  114048. * True if the diffuse texture is in gamma space.
  114049. */
  114050. _this.GAMMADIFFUSE = false;
  114051. /**
  114052. * True if the diffuse texture has opacity in the alpha channel.
  114053. */
  114054. _this.DIFFUSEHASALPHA = false;
  114055. /**
  114056. * True if you want the material to fade to transparent at grazing angle.
  114057. */
  114058. _this.OPACITYFRESNEL = false;
  114059. /**
  114060. * True if an extra blur needs to be added in the reflection.
  114061. */
  114062. _this.REFLECTIONBLUR = false;
  114063. /**
  114064. * True if you want the material to fade to reflection at grazing angle.
  114065. */
  114066. _this.REFLECTIONFRESNEL = false;
  114067. /**
  114068. * True if you want the material to falloff as far as you move away from the scene center.
  114069. */
  114070. _this.REFLECTIONFALLOFF = false;
  114071. /**
  114072. * False if the current Webgl implementation does not support the texture lod extension.
  114073. */
  114074. _this.TEXTURELODSUPPORT = false;
  114075. /**
  114076. * True to ensure the data are premultiplied.
  114077. */
  114078. _this.PREMULTIPLYALPHA = false;
  114079. /**
  114080. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114081. */
  114082. _this.USERGBCOLOR = false;
  114083. /**
  114084. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114085. * stays aligned with the desired configuration.
  114086. */
  114087. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114088. /**
  114089. * True to add noise in order to reduce the banding effect.
  114090. */
  114091. _this.NOISE = false;
  114092. /**
  114093. * is the reflection texture in BGR color scheme?
  114094. * Mainly used to solve a bug in ios10 video tag
  114095. */
  114096. _this.REFLECTIONBGR = false;
  114097. _this.IMAGEPROCESSING = false;
  114098. _this.VIGNETTE = false;
  114099. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114100. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114101. _this.TONEMAPPING = false;
  114102. _this.TONEMAPPING_ACES = false;
  114103. _this.CONTRAST = false;
  114104. _this.COLORCURVES = false;
  114105. _this.COLORGRADING = false;
  114106. _this.COLORGRADING3D = false;
  114107. _this.SAMPLER3DGREENDEPTH = false;
  114108. _this.SAMPLER3DBGRMAP = false;
  114109. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114110. _this.EXPOSURE = false;
  114111. // Reflection.
  114112. _this.REFLECTION = false;
  114113. _this.REFLECTIONMAP_3D = false;
  114114. _this.REFLECTIONMAP_SPHERICAL = false;
  114115. _this.REFLECTIONMAP_PLANAR = false;
  114116. _this.REFLECTIONMAP_CUBIC = false;
  114117. _this.REFLECTIONMAP_PROJECTION = false;
  114118. _this.REFLECTIONMAP_SKYBOX = false;
  114119. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114120. _this.REFLECTIONMAP_EXPLICIT = false;
  114121. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114122. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114123. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114124. _this.INVERTCUBICMAP = false;
  114125. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114126. _this.LODINREFLECTIONALPHA = false;
  114127. _this.GAMMAREFLECTION = false;
  114128. _this.RGBDREFLECTION = false;
  114129. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114130. // Default BJS.
  114131. _this.MAINUV1 = false;
  114132. _this.MAINUV2 = false;
  114133. _this.UV1 = false;
  114134. _this.UV2 = false;
  114135. _this.CLIPPLANE = false;
  114136. _this.CLIPPLANE2 = false;
  114137. _this.CLIPPLANE3 = false;
  114138. _this.CLIPPLANE4 = false;
  114139. _this.POINTSIZE = false;
  114140. _this.FOG = false;
  114141. _this.NORMAL = false;
  114142. _this.NUM_BONE_INFLUENCERS = 0;
  114143. _this.BonesPerMesh = 0;
  114144. _this.INSTANCES = false;
  114145. _this.SHADOWFLOAT = false;
  114146. _this.rebuild();
  114147. return _this;
  114148. }
  114149. return BackgroundMaterialDefines;
  114150. }(BABYLON.MaterialDefines));
  114151. /**
  114152. * Background material used to create an efficient environement around your scene.
  114153. */
  114154. var BackgroundMaterial = /** @class */ (function (_super) {
  114155. __extends(BackgroundMaterial, _super);
  114156. /**
  114157. * Instantiates a Background Material in the given scene
  114158. * @param name The friendly name of the material
  114159. * @param scene The scene to add the material to
  114160. */
  114161. function BackgroundMaterial(name, scene) {
  114162. var _this = _super.call(this, name, scene) || this;
  114163. /**
  114164. * Key light Color (multiply against the environement texture)
  114165. */
  114166. _this.primaryColor = BABYLON.Color3.White();
  114167. _this._primaryColorShadowLevel = 0;
  114168. _this._primaryColorHighlightLevel = 0;
  114169. /**
  114170. * Reflection Texture used in the material.
  114171. * Should be author in a specific way for the best result (refer to the documentation).
  114172. */
  114173. _this.reflectionTexture = null;
  114174. /**
  114175. * Reflection Texture level of blur.
  114176. *
  114177. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114178. * texture twice.
  114179. */
  114180. _this.reflectionBlur = 0;
  114181. /**
  114182. * Diffuse Texture used in the material.
  114183. * Should be author in a specific way for the best result (refer to the documentation).
  114184. */
  114185. _this.diffuseTexture = null;
  114186. _this._shadowLights = null;
  114187. /**
  114188. * Specify the list of lights casting shadow on the material.
  114189. * All scene shadow lights will be included if null.
  114190. */
  114191. _this.shadowLights = null;
  114192. /**
  114193. * Helps adjusting the shadow to a softer level if required.
  114194. * 0 means black shadows and 1 means no shadows.
  114195. */
  114196. _this.shadowLevel = 0;
  114197. /**
  114198. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114199. * It is usually zero but might be interesting to modify according to your setup.
  114200. */
  114201. _this.sceneCenter = BABYLON.Vector3.Zero();
  114202. /**
  114203. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114204. * This helps ensuring a nice transition when the camera goes under the ground.
  114205. */
  114206. _this.opacityFresnel = true;
  114207. /**
  114208. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114209. * This helps adding a mirror texture on the ground.
  114210. */
  114211. _this.reflectionFresnel = false;
  114212. /**
  114213. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114214. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114215. */
  114216. _this.reflectionFalloffDistance = 0.0;
  114217. /**
  114218. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114219. */
  114220. _this.reflectionAmount = 1.0;
  114221. /**
  114222. * This specifies the weight of the reflection at grazing angle.
  114223. */
  114224. _this.reflectionReflectance0 = 0.05;
  114225. /**
  114226. * This specifies the weight of the reflection at a perpendicular point of view.
  114227. */
  114228. _this.reflectionReflectance90 = 0.5;
  114229. /**
  114230. * Helps to directly use the maps channels instead of their level.
  114231. */
  114232. _this.useRGBColor = true;
  114233. /**
  114234. * This helps reducing the banding effect that could occur on the background.
  114235. */
  114236. _this.enableNoise = false;
  114237. _this._fovMultiplier = 1.0;
  114238. /**
  114239. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114240. */
  114241. _this.useEquirectangularFOV = false;
  114242. _this._maxSimultaneousLights = 4;
  114243. /**
  114244. * Number of Simultaneous lights allowed on the material.
  114245. */
  114246. _this.maxSimultaneousLights = 4;
  114247. /**
  114248. * Keep track of the image processing observer to allow dispose and replace.
  114249. */
  114250. _this._imageProcessingObserver = null;
  114251. /**
  114252. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114253. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114254. */
  114255. _this.switchToBGR = false;
  114256. // Temp values kept as cache in the material.
  114257. _this._renderTargets = new BABYLON.SmartArray(16);
  114258. _this._reflectionControls = BABYLON.Vector4.Zero();
  114259. _this._white = BABYLON.Color3.White();
  114260. _this._primaryShadowColor = BABYLON.Color3.Black();
  114261. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114262. // Setup the default processing configuration to the scene.
  114263. _this._attachImageProcessingConfiguration(null);
  114264. _this.getRenderTargetTextures = function () {
  114265. _this._renderTargets.reset();
  114266. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114267. _this._renderTargets.push(_this._diffuseTexture);
  114268. }
  114269. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114270. _this._renderTargets.push(_this._reflectionTexture);
  114271. }
  114272. return _this._renderTargets;
  114273. };
  114274. return _this;
  114275. }
  114276. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114277. /**
  114278. * Experimental Internal Use Only.
  114279. *
  114280. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114281. * This acts as a helper to set the primary color to a more "human friendly" value.
  114282. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114283. * output color as close as possible from the chosen value.
  114284. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114285. * part of lighting setup.)
  114286. */
  114287. get: function () {
  114288. return this.__perceptualColor;
  114289. },
  114290. set: function (value) {
  114291. this.__perceptualColor = value;
  114292. this._computePrimaryColorFromPerceptualColor();
  114293. this._markAllSubMeshesAsLightsDirty();
  114294. },
  114295. enumerable: true,
  114296. configurable: true
  114297. });
  114298. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114299. /**
  114300. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114301. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114302. */
  114303. get: function () {
  114304. return this._primaryColorShadowLevel;
  114305. },
  114306. set: function (value) {
  114307. this._primaryColorShadowLevel = value;
  114308. this._computePrimaryColors();
  114309. this._markAllSubMeshesAsLightsDirty();
  114310. },
  114311. enumerable: true,
  114312. configurable: true
  114313. });
  114314. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114315. /**
  114316. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114317. * The primary color is used at the level chosen to define what the white area would look.
  114318. */
  114319. get: function () {
  114320. return this._primaryColorHighlightLevel;
  114321. },
  114322. set: function (value) {
  114323. this._primaryColorHighlightLevel = value;
  114324. this._computePrimaryColors();
  114325. this._markAllSubMeshesAsLightsDirty();
  114326. },
  114327. enumerable: true,
  114328. configurable: true
  114329. });
  114330. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114331. /**
  114332. * Sets the reflection reflectance fresnel values according to the default standard
  114333. * empirically know to work well :-)
  114334. */
  114335. set: function (value) {
  114336. var reflectionWeight = value;
  114337. if (reflectionWeight < 0.5) {
  114338. reflectionWeight = reflectionWeight * 2.0;
  114339. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114340. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114341. }
  114342. else {
  114343. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114344. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114345. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114346. }
  114347. },
  114348. enumerable: true,
  114349. configurable: true
  114350. });
  114351. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114352. /**
  114353. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114354. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114355. * Recommended to be keep at 1.0 except for special cases.
  114356. */
  114357. get: function () {
  114358. return this._fovMultiplier;
  114359. },
  114360. set: function (value) {
  114361. if (isNaN(value)) {
  114362. value = 1.0;
  114363. }
  114364. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114365. },
  114366. enumerable: true,
  114367. configurable: true
  114368. });
  114369. /**
  114370. * Attaches a new image processing configuration to the PBR Material.
  114371. * @param configuration (if null the scene configuration will be use)
  114372. */
  114373. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114374. var _this = this;
  114375. if (configuration === this._imageProcessingConfiguration) {
  114376. return;
  114377. }
  114378. // Detaches observer.
  114379. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114380. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114381. }
  114382. // Pick the scene configuration if needed.
  114383. if (!configuration) {
  114384. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114385. }
  114386. else {
  114387. this._imageProcessingConfiguration = configuration;
  114388. }
  114389. // Attaches observer.
  114390. if (this._imageProcessingConfiguration) {
  114391. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114392. _this._computePrimaryColorFromPerceptualColor();
  114393. _this._markAllSubMeshesAsImageProcessingDirty();
  114394. });
  114395. }
  114396. };
  114397. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114398. /**
  114399. * Gets the image processing configuration used either in this material.
  114400. */
  114401. get: function () {
  114402. return this._imageProcessingConfiguration;
  114403. },
  114404. /**
  114405. * Sets the Default image processing configuration used either in the this material.
  114406. *
  114407. * If sets to null, the scene one is in use.
  114408. */
  114409. set: function (value) {
  114410. this._attachImageProcessingConfiguration(value);
  114411. // Ensure the effect will be rebuilt.
  114412. this._markAllSubMeshesAsTexturesDirty();
  114413. },
  114414. enumerable: true,
  114415. configurable: true
  114416. });
  114417. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114418. /**
  114419. * Gets wether the color curves effect is enabled.
  114420. */
  114421. get: function () {
  114422. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114423. },
  114424. /**
  114425. * Sets wether the color curves effect is enabled.
  114426. */
  114427. set: function (value) {
  114428. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114429. },
  114430. enumerable: true,
  114431. configurable: true
  114432. });
  114433. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114434. /**
  114435. * Gets wether the color grading effect is enabled.
  114436. */
  114437. get: function () {
  114438. return this.imageProcessingConfiguration.colorGradingEnabled;
  114439. },
  114440. /**
  114441. * Gets wether the color grading effect is enabled.
  114442. */
  114443. set: function (value) {
  114444. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114445. },
  114446. enumerable: true,
  114447. configurable: true
  114448. });
  114449. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114450. /**
  114451. * Gets wether tonemapping is enabled or not.
  114452. */
  114453. get: function () {
  114454. return this._imageProcessingConfiguration.toneMappingEnabled;
  114455. },
  114456. /**
  114457. * Sets wether tonemapping is enabled or not
  114458. */
  114459. set: function (value) {
  114460. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114461. },
  114462. enumerable: true,
  114463. configurable: true
  114464. });
  114465. ;
  114466. ;
  114467. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114468. /**
  114469. * The camera exposure used on this material.
  114470. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114471. * This corresponds to a photographic exposure.
  114472. */
  114473. get: function () {
  114474. return this._imageProcessingConfiguration.exposure;
  114475. },
  114476. /**
  114477. * The camera exposure used on this material.
  114478. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114479. * This corresponds to a photographic exposure.
  114480. */
  114481. set: function (value) {
  114482. this._imageProcessingConfiguration.exposure = value;
  114483. },
  114484. enumerable: true,
  114485. configurable: true
  114486. });
  114487. ;
  114488. ;
  114489. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114490. /**
  114491. * Gets The camera contrast used on this material.
  114492. */
  114493. get: function () {
  114494. return this._imageProcessingConfiguration.contrast;
  114495. },
  114496. /**
  114497. * Sets The camera contrast used on this material.
  114498. */
  114499. set: function (value) {
  114500. this._imageProcessingConfiguration.contrast = value;
  114501. },
  114502. enumerable: true,
  114503. configurable: true
  114504. });
  114505. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114506. /**
  114507. * Gets the Color Grading 2D Lookup Texture.
  114508. */
  114509. get: function () {
  114510. return this._imageProcessingConfiguration.colorGradingTexture;
  114511. },
  114512. /**
  114513. * Sets the Color Grading 2D Lookup Texture.
  114514. */
  114515. set: function (value) {
  114516. this.imageProcessingConfiguration.colorGradingTexture = value;
  114517. },
  114518. enumerable: true,
  114519. configurable: true
  114520. });
  114521. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114522. /**
  114523. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114524. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114525. * 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;
  114526. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114527. */
  114528. get: function () {
  114529. return this.imageProcessingConfiguration.colorCurves;
  114530. },
  114531. /**
  114532. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114533. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114534. * 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;
  114535. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114536. */
  114537. set: function (value) {
  114538. this.imageProcessingConfiguration.colorCurves = value;
  114539. },
  114540. enumerable: true,
  114541. configurable: true
  114542. });
  114543. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114544. /**
  114545. * Gets a boolean indicating that current material needs to register RTT
  114546. */
  114547. get: function () {
  114548. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114549. return true;
  114550. }
  114551. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114552. return true;
  114553. }
  114554. return false;
  114555. },
  114556. enumerable: true,
  114557. configurable: true
  114558. });
  114559. /**
  114560. * The entire material has been created in order to prevent overdraw.
  114561. * @returns false
  114562. */
  114563. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114564. return true;
  114565. };
  114566. /**
  114567. * The entire material has been created in order to prevent overdraw.
  114568. * @returns true if blending is enable
  114569. */
  114570. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114571. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114572. };
  114573. /**
  114574. * Checks wether the material is ready to be rendered for a given mesh.
  114575. * @param mesh The mesh to render
  114576. * @param subMesh The submesh to check against
  114577. * @param useInstances Specify wether or not the material is used with instances
  114578. * @returns true if all the dependencies are ready (Textures, Effects...)
  114579. */
  114580. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  114581. var _this = this;
  114582. if (useInstances === void 0) { useInstances = false; }
  114583. if (subMesh.effect && this.isFrozen) {
  114584. if (this._wasPreviouslyReady) {
  114585. return true;
  114586. }
  114587. }
  114588. if (!subMesh._materialDefines) {
  114589. subMesh._materialDefines = new BackgroundMaterialDefines();
  114590. }
  114591. var scene = this.getScene();
  114592. var defines = subMesh._materialDefines;
  114593. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  114594. if (defines._renderId === scene.getRenderId()) {
  114595. return true;
  114596. }
  114597. }
  114598. var engine = scene.getEngine();
  114599. // Lights
  114600. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  114601. defines._needNormals = true;
  114602. // Textures
  114603. if (defines._areTexturesDirty) {
  114604. defines._needUVs = false;
  114605. if (scene.texturesEnabled) {
  114606. if (scene.getEngine().getCaps().textureLOD) {
  114607. defines.TEXTURELODSUPPORT = true;
  114608. }
  114609. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114610. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  114611. return false;
  114612. }
  114613. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  114614. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  114615. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  114616. defines.OPACITYFRESNEL = this._opacityFresnel;
  114617. }
  114618. else {
  114619. defines.DIFFUSE = false;
  114620. defines.DIFFUSEHASALPHA = false;
  114621. defines.GAMMADIFFUSE = false;
  114622. defines.OPACITYFRESNEL = false;
  114623. }
  114624. var reflectionTexture = this._reflectionTexture;
  114625. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114626. if (!reflectionTexture.isReadyOrNotBlocking()) {
  114627. return false;
  114628. }
  114629. defines.REFLECTION = true;
  114630. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  114631. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  114632. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  114633. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  114634. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  114635. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  114636. defines.REFLECTIONBGR = this.switchToBGR;
  114637. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  114638. defines.INVERTCUBICMAP = true;
  114639. }
  114640. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  114641. switch (reflectionTexture.coordinatesMode) {
  114642. case BABYLON.Texture.EXPLICIT_MODE:
  114643. defines.REFLECTIONMAP_EXPLICIT = true;
  114644. break;
  114645. case BABYLON.Texture.PLANAR_MODE:
  114646. defines.REFLECTIONMAP_PLANAR = true;
  114647. break;
  114648. case BABYLON.Texture.PROJECTION_MODE:
  114649. defines.REFLECTIONMAP_PROJECTION = true;
  114650. break;
  114651. case BABYLON.Texture.SKYBOX_MODE:
  114652. defines.REFLECTIONMAP_SKYBOX = true;
  114653. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  114654. break;
  114655. case BABYLON.Texture.SPHERICAL_MODE:
  114656. defines.REFLECTIONMAP_SPHERICAL = true;
  114657. break;
  114658. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  114659. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  114660. break;
  114661. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  114662. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  114663. break;
  114664. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  114665. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  114666. break;
  114667. case BABYLON.Texture.CUBIC_MODE:
  114668. case BABYLON.Texture.INVCUBIC_MODE:
  114669. default:
  114670. defines.REFLECTIONMAP_CUBIC = true;
  114671. break;
  114672. }
  114673. if (this.reflectionFresnel) {
  114674. defines.REFLECTIONFRESNEL = true;
  114675. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  114676. this._reflectionControls.x = this.reflectionAmount;
  114677. this._reflectionControls.y = this.reflectionReflectance0;
  114678. this._reflectionControls.z = this.reflectionReflectance90;
  114679. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  114680. }
  114681. else {
  114682. defines.REFLECTIONFRESNEL = false;
  114683. defines.REFLECTIONFALLOFF = false;
  114684. }
  114685. }
  114686. else {
  114687. defines.REFLECTION = false;
  114688. defines.REFLECTIONFRESNEL = false;
  114689. defines.REFLECTIONFALLOFF = false;
  114690. defines.REFLECTIONBLUR = false;
  114691. defines.REFLECTIONMAP_3D = false;
  114692. defines.REFLECTIONMAP_SPHERICAL = false;
  114693. defines.REFLECTIONMAP_PLANAR = false;
  114694. defines.REFLECTIONMAP_CUBIC = false;
  114695. defines.REFLECTIONMAP_PROJECTION = false;
  114696. defines.REFLECTIONMAP_SKYBOX = false;
  114697. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114698. defines.REFLECTIONMAP_EXPLICIT = false;
  114699. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114700. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114701. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114702. defines.INVERTCUBICMAP = false;
  114703. defines.REFLECTIONMAP_OPPOSITEZ = false;
  114704. defines.LODINREFLECTIONALPHA = false;
  114705. defines.GAMMAREFLECTION = false;
  114706. defines.RGBDREFLECTION = false;
  114707. }
  114708. }
  114709. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  114710. defines.USERGBCOLOR = this._useRGBColor;
  114711. defines.NOISE = this._enableNoise;
  114712. }
  114713. if (defines._areLightsDirty) {
  114714. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  114715. }
  114716. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  114717. if (!this._imageProcessingConfiguration.isReady()) {
  114718. return false;
  114719. }
  114720. this._imageProcessingConfiguration.prepareDefines(defines);
  114721. }
  114722. // Misc.
  114723. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  114724. // Values that need to be evaluated on every frame
  114725. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  114726. // Attribs
  114727. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  114728. if (mesh) {
  114729. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  114730. mesh.createNormals(true);
  114731. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  114732. }
  114733. }
  114734. }
  114735. // Get correct effect
  114736. if (defines.isDirty) {
  114737. defines.markAsProcessed();
  114738. scene.resetCachedMaterial();
  114739. // Fallbacks
  114740. var fallbacks = new BABYLON.EffectFallbacks();
  114741. if (defines.FOG) {
  114742. fallbacks.addFallback(0, "FOG");
  114743. }
  114744. if (defines.POINTSIZE) {
  114745. fallbacks.addFallback(1, "POINTSIZE");
  114746. }
  114747. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  114748. if (defines.NUM_BONE_INFLUENCERS > 0) {
  114749. fallbacks.addCPUSkinningFallback(0, mesh);
  114750. }
  114751. //Attributes
  114752. var attribs = [BABYLON.VertexBuffer.PositionKind];
  114753. if (defines.NORMAL) {
  114754. attribs.push(BABYLON.VertexBuffer.NormalKind);
  114755. }
  114756. if (defines.UV1) {
  114757. attribs.push(BABYLON.VertexBuffer.UVKind);
  114758. }
  114759. if (defines.UV2) {
  114760. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  114761. }
  114762. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  114763. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  114764. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  114765. "vFogInfos", "vFogColor", "pointSize",
  114766. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  114767. "vPrimaryColor", "vPrimaryColorShadow",
  114768. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  114769. "shadowLevel", "alpha",
  114770. "vBackgroundCenter", "vReflectionControl",
  114771. "vDiffuseInfos", "diffuseMatrix",
  114772. ];
  114773. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  114774. var uniformBuffers = ["Material", "Scene"];
  114775. if (BABYLON.ImageProcessingConfiguration) {
  114776. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  114777. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  114778. }
  114779. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  114780. uniformsNames: uniforms,
  114781. uniformBuffersNames: uniformBuffers,
  114782. samplers: samplers,
  114783. defines: defines,
  114784. maxSimultaneousLights: this._maxSimultaneousLights
  114785. });
  114786. var onCompiled = function (effect) {
  114787. if (_this.onCompiled) {
  114788. _this.onCompiled(effect);
  114789. }
  114790. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  114791. };
  114792. var join = defines.toString();
  114793. subMesh.setEffect(scene.getEngine().createEffect("background", {
  114794. attributes: attribs,
  114795. uniformsNames: uniforms,
  114796. uniformBuffersNames: uniformBuffers,
  114797. samplers: samplers,
  114798. defines: join,
  114799. fallbacks: fallbacks,
  114800. onCompiled: onCompiled,
  114801. onError: this.onError,
  114802. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  114803. }, engine), defines);
  114804. this.buildUniformLayout();
  114805. }
  114806. if (!subMesh.effect || !subMesh.effect.isReady()) {
  114807. return false;
  114808. }
  114809. defines._renderId = scene.getRenderId();
  114810. this._wasPreviouslyReady = true;
  114811. return true;
  114812. };
  114813. /**
  114814. * Compute the primary color according to the chosen perceptual color.
  114815. */
  114816. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  114817. if (!this.__perceptualColor) {
  114818. return;
  114819. }
  114820. this._primaryColor.copyFrom(this.__perceptualColor);
  114821. // Revert gamma space.
  114822. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  114823. // Revert image processing configuration.
  114824. if (this._imageProcessingConfiguration) {
  114825. // Revert Exposure.
  114826. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  114827. }
  114828. this._computePrimaryColors();
  114829. };
  114830. /**
  114831. * Compute the highlights and shadow colors according to their chosen levels.
  114832. */
  114833. BackgroundMaterial.prototype._computePrimaryColors = function () {
  114834. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  114835. return;
  114836. }
  114837. // Find the highlight color based on the configuration.
  114838. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  114839. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  114840. // Find the shadow color based on the configuration.
  114841. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  114842. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  114843. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  114844. };
  114845. /**
  114846. * Build the uniform buffer used in the material.
  114847. */
  114848. BackgroundMaterial.prototype.buildUniformLayout = function () {
  114849. // Order is important !
  114850. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  114851. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  114852. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  114853. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  114854. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  114855. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  114856. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  114857. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  114858. this._uniformBuffer.addUniform("pointSize", 1);
  114859. this._uniformBuffer.addUniform("shadowLevel", 1);
  114860. this._uniformBuffer.addUniform("alpha", 1);
  114861. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  114862. this._uniformBuffer.addUniform("vReflectionControl", 4);
  114863. this._uniformBuffer.create();
  114864. };
  114865. /**
  114866. * Unbind the material.
  114867. */
  114868. BackgroundMaterial.prototype.unbind = function () {
  114869. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114870. this._uniformBuffer.setTexture("diffuseSampler", null);
  114871. }
  114872. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114873. this._uniformBuffer.setTexture("reflectionSampler", null);
  114874. }
  114875. _super.prototype.unbind.call(this);
  114876. };
  114877. /**
  114878. * Bind only the world matrix to the material.
  114879. * @param world The world matrix to bind.
  114880. */
  114881. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  114882. this._activeEffect.setMatrix("world", world);
  114883. };
  114884. /**
  114885. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  114886. * @param world The world matrix to bind.
  114887. * @param subMesh The submesh to bind for.
  114888. */
  114889. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  114890. var scene = this.getScene();
  114891. var defines = subMesh._materialDefines;
  114892. if (!defines) {
  114893. return;
  114894. }
  114895. var effect = subMesh.effect;
  114896. if (!effect) {
  114897. return;
  114898. }
  114899. this._activeEffect = effect;
  114900. // Matrices
  114901. this.bindOnlyWorldMatrix(world);
  114902. // Bones
  114903. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  114904. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  114905. if (mustRebind) {
  114906. this._uniformBuffer.bindToEffect(effect, "Material");
  114907. this.bindViewProjection(effect);
  114908. var reflectionTexture = this._reflectionTexture;
  114909. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  114910. // Texture uniforms
  114911. if (scene.texturesEnabled) {
  114912. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114913. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  114914. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  114915. }
  114916. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114917. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  114918. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  114919. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  114920. }
  114921. }
  114922. if (this.shadowLevel > 0) {
  114923. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  114924. }
  114925. this._uniformBuffer.updateFloat("alpha", this.alpha);
  114926. // Point size
  114927. if (this.pointsCloud) {
  114928. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  114929. }
  114930. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  114931. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  114932. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  114933. }
  114934. else {
  114935. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  114936. }
  114937. }
  114938. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  114939. // Textures
  114940. if (scene.texturesEnabled) {
  114941. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114942. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  114943. }
  114944. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114945. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  114946. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  114947. }
  114948. else if (!defines.REFLECTIONBLUR) {
  114949. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  114950. }
  114951. else {
  114952. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  114953. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  114954. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  114955. }
  114956. if (defines.REFLECTIONFRESNEL) {
  114957. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  114958. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  114959. }
  114960. }
  114961. }
  114962. // Clip plane
  114963. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  114964. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  114965. }
  114966. if (mustRebind || !this.isFrozen) {
  114967. if (scene.lightsEnabled) {
  114968. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  114969. }
  114970. // View
  114971. this.bindView(effect);
  114972. // Fog
  114973. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  114974. // image processing
  114975. if (this._imageProcessingConfiguration) {
  114976. this._imageProcessingConfiguration.bind(this._activeEffect);
  114977. }
  114978. }
  114979. this._uniformBuffer.update();
  114980. this._afterBind(mesh, this._activeEffect);
  114981. };
  114982. /**
  114983. * Dispose the material.
  114984. * @param forceDisposeEffect Force disposal of the associated effect.
  114985. * @param forceDisposeTextures Force disposal of the associated textures.
  114986. */
  114987. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  114988. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  114989. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  114990. if (forceDisposeTextures) {
  114991. if (this.diffuseTexture) {
  114992. this.diffuseTexture.dispose();
  114993. }
  114994. if (this.reflectionTexture) {
  114995. this.reflectionTexture.dispose();
  114996. }
  114997. }
  114998. this._renderTargets.dispose();
  114999. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  115000. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  115001. }
  115002. _super.prototype.dispose.call(this, forceDisposeEffect);
  115003. };
  115004. /**
  115005. * Clones the material.
  115006. * @param name The cloned name.
  115007. * @returns The cloned material.
  115008. */
  115009. BackgroundMaterial.prototype.clone = function (name) {
  115010. var _this = this;
  115011. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  115012. };
  115013. /**
  115014. * Serializes the current material to its JSON representation.
  115015. * @returns The JSON representation.
  115016. */
  115017. BackgroundMaterial.prototype.serialize = function () {
  115018. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  115019. serializationObject.customType = "BABYLON.BackgroundMaterial";
  115020. return serializationObject;
  115021. };
  115022. /**
  115023. * Gets the class name of the material
  115024. * @returns "BackgroundMaterial"
  115025. */
  115026. BackgroundMaterial.prototype.getClassName = function () {
  115027. return "BackgroundMaterial";
  115028. };
  115029. /**
  115030. * Parse a JSON input to create back a background material.
  115031. * @param source The JSON data to parse
  115032. * @param scene The scene to create the parsed material in
  115033. * @param rootUrl The root url of the assets the material depends upon
  115034. * @returns the instantiated BackgroundMaterial.
  115035. */
  115036. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115037. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115038. };
  115039. /**
  115040. * Standard reflectance value at parallel view angle.
  115041. */
  115042. BackgroundMaterial.StandardReflectance0 = 0.05;
  115043. /**
  115044. * Standard reflectance value at grazing angle.
  115045. */
  115046. BackgroundMaterial.StandardReflectance90 = 0.5;
  115047. __decorate([
  115048. BABYLON.serializeAsColor3()
  115049. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115050. __decorate([
  115051. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115052. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115053. __decorate([
  115054. BABYLON.serializeAsColor3()
  115055. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115056. __decorate([
  115057. BABYLON.serialize()
  115058. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115059. __decorate([
  115060. BABYLON.serialize()
  115061. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115062. __decorate([
  115063. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115064. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115065. __decorate([
  115066. BABYLON.serializeAsTexture()
  115067. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115068. __decorate([
  115069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115070. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115071. __decorate([
  115072. BABYLON.serialize()
  115073. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115074. __decorate([
  115075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115076. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115077. __decorate([
  115078. BABYLON.serializeAsTexture()
  115079. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115080. __decorate([
  115081. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115082. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115083. __decorate([
  115084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115085. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115086. __decorate([
  115087. BABYLON.serialize()
  115088. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115089. __decorate([
  115090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115091. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115092. __decorate([
  115093. BABYLON.serializeAsVector3()
  115094. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115095. __decorate([
  115096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115097. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115098. __decorate([
  115099. BABYLON.serialize()
  115100. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115101. __decorate([
  115102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115103. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115104. __decorate([
  115105. BABYLON.serialize()
  115106. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115107. __decorate([
  115108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115109. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115110. __decorate([
  115111. BABYLON.serialize()
  115112. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115113. __decorate([
  115114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115115. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115116. __decorate([
  115117. BABYLON.serialize()
  115118. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115119. __decorate([
  115120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115121. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115122. __decorate([
  115123. BABYLON.serialize()
  115124. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115125. __decorate([
  115126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115127. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115128. __decorate([
  115129. BABYLON.serialize()
  115130. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115131. __decorate([
  115132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115133. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115134. __decorate([
  115135. BABYLON.serialize()
  115136. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115137. __decorate([
  115138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115139. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115140. __decorate([
  115141. BABYLON.serialize()
  115142. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115143. __decorate([
  115144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115145. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115146. __decorate([
  115147. BABYLON.serialize()
  115148. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115149. __decorate([
  115150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115151. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115152. __decorate([
  115153. BABYLON.serializeAsImageProcessingConfiguration()
  115154. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115155. return BackgroundMaterial;
  115156. }(BABYLON.PushMaterial));
  115157. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115158. })(BABYLON || (BABYLON = {}));
  115159. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115160. var __assign = (this && this.__assign) || function () {
  115161. __assign = Object.assign || function(t) {
  115162. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115163. s = arguments[i];
  115164. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115165. t[p] = s[p];
  115166. }
  115167. return t;
  115168. };
  115169. return __assign.apply(this, arguments);
  115170. };
  115171. var BABYLON;
  115172. (function (BABYLON) {
  115173. /**
  115174. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115175. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115176. * It also helps with the default setup of your imageProcessing configuration.
  115177. */
  115178. var EnvironmentHelper = /** @class */ (function () {
  115179. /**
  115180. * constructor
  115181. * @param options
  115182. * @param scene The scene to add the material to
  115183. */
  115184. function EnvironmentHelper(options, scene) {
  115185. var _this = this;
  115186. this._errorHandler = function (message, exception) {
  115187. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115188. };
  115189. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115190. this._scene = scene;
  115191. this.onErrorObservable = new BABYLON.Observable();
  115192. this._setupBackground();
  115193. this._setupImageProcessing();
  115194. }
  115195. /**
  115196. * Creates the default options for the helper.
  115197. */
  115198. EnvironmentHelper._getDefaultOptions = function () {
  115199. return {
  115200. createGround: true,
  115201. groundSize: 15,
  115202. groundTexture: this._groundTextureCDNUrl,
  115203. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115204. groundOpacity: 0.9,
  115205. enableGroundShadow: true,
  115206. groundShadowLevel: 0.5,
  115207. enableGroundMirror: false,
  115208. groundMirrorSizeRatio: 0.3,
  115209. groundMirrorBlurKernel: 64,
  115210. groundMirrorAmount: 1,
  115211. groundMirrorFresnelWeight: 1,
  115212. groundMirrorFallOffDistance: 0,
  115213. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115214. groundYBias: 0.00001,
  115215. createSkybox: true,
  115216. skyboxSize: 20,
  115217. skyboxTexture: this._skyboxTextureCDNUrl,
  115218. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115219. backgroundYRotation: 0,
  115220. sizeAuto: true,
  115221. rootPosition: BABYLON.Vector3.Zero(),
  115222. setupImageProcessing: true,
  115223. environmentTexture: this._environmentTextureCDNUrl,
  115224. cameraExposure: 0.8,
  115225. cameraContrast: 1.2,
  115226. toneMappingEnabled: true,
  115227. };
  115228. };
  115229. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115230. /**
  115231. * Gets the root mesh created by the helper.
  115232. */
  115233. get: function () {
  115234. return this._rootMesh;
  115235. },
  115236. enumerable: true,
  115237. configurable: true
  115238. });
  115239. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115240. /**
  115241. * Gets the skybox created by the helper.
  115242. */
  115243. get: function () {
  115244. return this._skybox;
  115245. },
  115246. enumerable: true,
  115247. configurable: true
  115248. });
  115249. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115250. /**
  115251. * Gets the skybox texture created by the helper.
  115252. */
  115253. get: function () {
  115254. return this._skyboxTexture;
  115255. },
  115256. enumerable: true,
  115257. configurable: true
  115258. });
  115259. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115260. /**
  115261. * Gets the skybox material created by the helper.
  115262. */
  115263. get: function () {
  115264. return this._skyboxMaterial;
  115265. },
  115266. enumerable: true,
  115267. configurable: true
  115268. });
  115269. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115270. /**
  115271. * Gets the ground mesh created by the helper.
  115272. */
  115273. get: function () {
  115274. return this._ground;
  115275. },
  115276. enumerable: true,
  115277. configurable: true
  115278. });
  115279. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115280. /**
  115281. * Gets the ground texture created by the helper.
  115282. */
  115283. get: function () {
  115284. return this._groundTexture;
  115285. },
  115286. enumerable: true,
  115287. configurable: true
  115288. });
  115289. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115290. /**
  115291. * Gets the ground mirror created by the helper.
  115292. */
  115293. get: function () {
  115294. return this._groundMirror;
  115295. },
  115296. enumerable: true,
  115297. configurable: true
  115298. });
  115299. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115300. /**
  115301. * Gets the ground mirror render list to helps pushing the meshes
  115302. * you wish in the ground reflection.
  115303. */
  115304. get: function () {
  115305. if (this._groundMirror) {
  115306. return this._groundMirror.renderList;
  115307. }
  115308. return null;
  115309. },
  115310. enumerable: true,
  115311. configurable: true
  115312. });
  115313. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115314. /**
  115315. * Gets the ground material created by the helper.
  115316. */
  115317. get: function () {
  115318. return this._groundMaterial;
  115319. },
  115320. enumerable: true,
  115321. configurable: true
  115322. });
  115323. /**
  115324. * Updates the background according to the new options
  115325. * @param options
  115326. */
  115327. EnvironmentHelper.prototype.updateOptions = function (options) {
  115328. var newOptions = __assign({}, this._options, options);
  115329. if (this._ground && !newOptions.createGround) {
  115330. this._ground.dispose();
  115331. this._ground = null;
  115332. }
  115333. if (this._groundMaterial && !newOptions.createGround) {
  115334. this._groundMaterial.dispose();
  115335. this._groundMaterial = null;
  115336. }
  115337. if (this._groundTexture) {
  115338. if (this._options.groundTexture != newOptions.groundTexture) {
  115339. this._groundTexture.dispose();
  115340. this._groundTexture = null;
  115341. }
  115342. }
  115343. if (this._skybox && !newOptions.createSkybox) {
  115344. this._skybox.dispose();
  115345. this._skybox = null;
  115346. }
  115347. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115348. this._skyboxMaterial.dispose();
  115349. this._skyboxMaterial = null;
  115350. }
  115351. if (this._skyboxTexture) {
  115352. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115353. this._skyboxTexture.dispose();
  115354. this._skyboxTexture = null;
  115355. }
  115356. }
  115357. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115358. this._groundMirror.dispose();
  115359. this._groundMirror = null;
  115360. }
  115361. if (this._scene.environmentTexture) {
  115362. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115363. this._scene.environmentTexture.dispose();
  115364. }
  115365. }
  115366. this._options = newOptions;
  115367. this._setupBackground();
  115368. this._setupImageProcessing();
  115369. };
  115370. /**
  115371. * Sets the primary color of all the available elements.
  115372. * @param color the main color to affect to the ground and the background
  115373. */
  115374. EnvironmentHelper.prototype.setMainColor = function (color) {
  115375. if (this.groundMaterial) {
  115376. this.groundMaterial.primaryColor = color;
  115377. }
  115378. if (this.skyboxMaterial) {
  115379. this.skyboxMaterial.primaryColor = color;
  115380. }
  115381. if (this.groundMirror) {
  115382. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115383. }
  115384. };
  115385. /**
  115386. * Setup the image processing according to the specified options.
  115387. */
  115388. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115389. if (this._options.setupImageProcessing) {
  115390. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115391. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115392. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115393. this._setupEnvironmentTexture();
  115394. }
  115395. };
  115396. /**
  115397. * Setup the environment texture according to the specified options.
  115398. */
  115399. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115400. if (this._scene.environmentTexture) {
  115401. return;
  115402. }
  115403. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115404. this._scene.environmentTexture = this._options.environmentTexture;
  115405. return;
  115406. }
  115407. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115408. this._scene.environmentTexture = environmentTexture;
  115409. };
  115410. /**
  115411. * Setup the background according to the specified options.
  115412. */
  115413. EnvironmentHelper.prototype._setupBackground = function () {
  115414. if (!this._rootMesh) {
  115415. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115416. }
  115417. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115418. var sceneSize = this._getSceneSize();
  115419. if (this._options.createGround) {
  115420. this._setupGround(sceneSize);
  115421. this._setupGroundMaterial();
  115422. this._setupGroundDiffuseTexture();
  115423. if (this._options.enableGroundMirror) {
  115424. this._setupGroundMirrorTexture(sceneSize);
  115425. }
  115426. this._setupMirrorInGroundMaterial();
  115427. }
  115428. if (this._options.createSkybox) {
  115429. this._setupSkybox(sceneSize);
  115430. this._setupSkyboxMaterial();
  115431. this._setupSkyboxReflectionTexture();
  115432. }
  115433. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115434. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115435. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115436. };
  115437. /**
  115438. * Get the scene sizes according to the setup.
  115439. */
  115440. EnvironmentHelper.prototype._getSceneSize = function () {
  115441. var _this = this;
  115442. var groundSize = this._options.groundSize;
  115443. var skyboxSize = this._options.skyboxSize;
  115444. var rootPosition = this._options.rootPosition;
  115445. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115446. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115447. }
  115448. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115449. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115450. });
  115451. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115452. if (this._options.sizeAuto) {
  115453. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115454. this._scene.activeCamera.upperRadiusLimit) {
  115455. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115456. skyboxSize = groundSize;
  115457. }
  115458. var sceneDiagonalLenght = sceneDiagonal.length();
  115459. if (sceneDiagonalLenght > groundSize) {
  115460. groundSize = sceneDiagonalLenght * 2;
  115461. skyboxSize = groundSize;
  115462. }
  115463. // 10 % bigger.
  115464. groundSize *= 1.1;
  115465. skyboxSize *= 1.5;
  115466. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115467. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115468. }
  115469. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115470. };
  115471. /**
  115472. * Setup the ground according to the specified options.
  115473. */
  115474. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115475. var _this = this;
  115476. if (!this._ground || this._ground.isDisposed()) {
  115477. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115478. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115479. this._ground.parent = this._rootMesh;
  115480. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115481. }
  115482. this._ground.receiveShadows = this._options.enableGroundShadow;
  115483. };
  115484. /**
  115485. * Setup the ground material according to the specified options.
  115486. */
  115487. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115488. if (!this._groundMaterial) {
  115489. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115490. }
  115491. this._groundMaterial.alpha = this._options.groundOpacity;
  115492. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115493. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115494. this._groundMaterial.primaryColor = this._options.groundColor;
  115495. this._groundMaterial.useRGBColor = false;
  115496. this._groundMaterial.enableNoise = true;
  115497. if (this._ground) {
  115498. this._ground.material = this._groundMaterial;
  115499. }
  115500. };
  115501. /**
  115502. * Setup the ground diffuse texture according to the specified options.
  115503. */
  115504. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115505. if (!this._groundMaterial) {
  115506. return;
  115507. }
  115508. if (this._groundTexture) {
  115509. return;
  115510. }
  115511. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115512. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115513. return;
  115514. }
  115515. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115516. diffuseTexture.gammaSpace = false;
  115517. diffuseTexture.hasAlpha = true;
  115518. this._groundMaterial.diffuseTexture = diffuseTexture;
  115519. };
  115520. /**
  115521. * Setup the ground mirror texture according to the specified options.
  115522. */
  115523. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115524. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115525. if (!this._groundMirror) {
  115526. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115527. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115528. this._groundMirror.anisotropicFilteringLevel = 1;
  115529. this._groundMirror.wrapU = wrapping;
  115530. this._groundMirror.wrapV = wrapping;
  115531. this._groundMirror.gammaSpace = false;
  115532. if (this._groundMirror.renderList) {
  115533. for (var i = 0; i < this._scene.meshes.length; i++) {
  115534. var mesh = this._scene.meshes[i];
  115535. if (mesh !== this._ground &&
  115536. mesh !== this._skybox &&
  115537. mesh !== this._rootMesh) {
  115538. this._groundMirror.renderList.push(mesh);
  115539. }
  115540. }
  115541. }
  115542. }
  115543. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115544. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115545. };
  115546. /**
  115547. * Setup the ground to receive the mirror texture.
  115548. */
  115549. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115550. if (this._groundMaterial) {
  115551. this._groundMaterial.reflectionTexture = this._groundMirror;
  115552. this._groundMaterial.reflectionFresnel = true;
  115553. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115554. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115555. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115556. }
  115557. };
  115558. /**
  115559. * Setup the skybox according to the specified options.
  115560. */
  115561. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115562. var _this = this;
  115563. if (!this._skybox || this._skybox.isDisposed()) {
  115564. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115565. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115566. }
  115567. this._skybox.parent = this._rootMesh;
  115568. };
  115569. /**
  115570. * Setup the skybox material according to the specified options.
  115571. */
  115572. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115573. if (!this._skybox) {
  115574. return;
  115575. }
  115576. if (!this._skyboxMaterial) {
  115577. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  115578. }
  115579. this._skyboxMaterial.useRGBColor = false;
  115580. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  115581. this._skyboxMaterial.enableNoise = true;
  115582. this._skybox.material = this._skyboxMaterial;
  115583. };
  115584. /**
  115585. * Setup the skybox reflection texture according to the specified options.
  115586. */
  115587. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  115588. if (!this._skyboxMaterial) {
  115589. return;
  115590. }
  115591. if (this._skyboxTexture) {
  115592. return;
  115593. }
  115594. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  115595. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  115596. return;
  115597. }
  115598. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115599. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115600. this._skyboxTexture.gammaSpace = false;
  115601. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  115602. };
  115603. /**
  115604. * Dispose all the elements created by the Helper.
  115605. */
  115606. EnvironmentHelper.prototype.dispose = function () {
  115607. if (this._groundMaterial) {
  115608. this._groundMaterial.dispose(true, true);
  115609. }
  115610. if (this._skyboxMaterial) {
  115611. this._skyboxMaterial.dispose(true, true);
  115612. }
  115613. this._rootMesh.dispose(false);
  115614. };
  115615. /**
  115616. * Default ground texture URL.
  115617. */
  115618. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  115619. /**
  115620. * Default skybox texture URL.
  115621. */
  115622. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  115623. /**
  115624. * Default environment texture URL.
  115625. */
  115626. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  115627. return EnvironmentHelper;
  115628. }());
  115629. BABYLON.EnvironmentHelper = EnvironmentHelper;
  115630. })(BABYLON || (BABYLON = {}));
  115631. //# sourceMappingURL=babylon.environmentHelper.js.map
  115632. var BABYLON;
  115633. (function (BABYLON) {
  115634. /** Internal class used to store shapes for emitters */
  115635. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  115636. function ParticleSystemSetEmitterCreationOptions() {
  115637. }
  115638. return ParticleSystemSetEmitterCreationOptions;
  115639. }());
  115640. /**
  115641. * Represents a set of particle systems working together to create a specific effect
  115642. */
  115643. var ParticleSystemSet = /** @class */ (function () {
  115644. function ParticleSystemSet() {
  115645. /**
  115646. * Gets the particle system list
  115647. */
  115648. this.systems = new Array();
  115649. }
  115650. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  115651. /**
  115652. * Gets the emitter node used with this set
  115653. */
  115654. get: function () {
  115655. return this._emitterNode;
  115656. },
  115657. enumerable: true,
  115658. configurable: true
  115659. });
  115660. /**
  115661. * Creates a new emitter mesh as a sphere
  115662. * @param options defines the options used to create the sphere
  115663. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  115664. * @param scene defines the hosting scene
  115665. */
  115666. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  115667. if (this._emitterNode) {
  115668. this._emitterNode.dispose();
  115669. }
  115670. this._emitterCreationOptions = {
  115671. kind: "Sphere",
  115672. options: options,
  115673. renderingGroupId: renderingGroupId
  115674. };
  115675. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  115676. emitterMesh.renderingGroupId = renderingGroupId;
  115677. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  115678. material.emissiveColor = options.color;
  115679. emitterMesh.material = material;
  115680. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115681. var system = _a[_i];
  115682. system.emitter = emitterMesh;
  115683. }
  115684. this._emitterNode = emitterMesh;
  115685. };
  115686. /**
  115687. * Starts all particle systems of the set
  115688. * @param emitter defines an optional mesh to use as emitter for the particle systems
  115689. */
  115690. ParticleSystemSet.prototype.start = function (emitter) {
  115691. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115692. var system = _a[_i];
  115693. if (emitter) {
  115694. system.emitter = emitter;
  115695. }
  115696. system.start();
  115697. }
  115698. };
  115699. /**
  115700. * Release all associated resources
  115701. */
  115702. ParticleSystemSet.prototype.dispose = function () {
  115703. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115704. var system = _a[_i];
  115705. system.dispose();
  115706. }
  115707. this.systems = [];
  115708. if (this._emitterNode) {
  115709. this._emitterNode.dispose();
  115710. this._emitterNode = null;
  115711. }
  115712. };
  115713. /**
  115714. * Serialize the set into a JSON compatible object
  115715. * @returns a JSON compatible representation of the set
  115716. */
  115717. ParticleSystemSet.prototype.serialize = function () {
  115718. var result = {};
  115719. result.systems = [];
  115720. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115721. var system = _a[_i];
  115722. result.systems.push(system.serialize());
  115723. }
  115724. if (this._emitterNode) {
  115725. result.emitter = this._emitterCreationOptions;
  115726. }
  115727. return result;
  115728. };
  115729. /**
  115730. * Parse a new ParticleSystemSet from a serialized source
  115731. * @param data defines a JSON compatible representation of the set
  115732. * @param scene defines the hosting scene
  115733. * @param gpu defines if we want GPU particles or CPU particles
  115734. * @returns a new ParticleSystemSet
  115735. */
  115736. ParticleSystemSet.Parse = function (data, scene, gpu) {
  115737. if (gpu === void 0) { gpu = false; }
  115738. var result = new ParticleSystemSet();
  115739. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  115740. scene = scene || BABYLON.Engine.LastCreatedScene;
  115741. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  115742. var system = _a[_i];
  115743. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  115744. }
  115745. if (data.emitter) {
  115746. var options = data.emitter.options;
  115747. switch (data.emitter.kind) {
  115748. case "Sphere":
  115749. result.setEmitterAsSphere({
  115750. diameter: options.diameter,
  115751. segments: options.segments,
  115752. color: BABYLON.Color3.FromArray(options.color)
  115753. }, data.emitter.renderingGroupId, scene);
  115754. break;
  115755. }
  115756. }
  115757. return result;
  115758. };
  115759. return ParticleSystemSet;
  115760. }());
  115761. BABYLON.ParticleSystemSet = ParticleSystemSet;
  115762. })(BABYLON || (BABYLON = {}));
  115763. //# sourceMappingURL=babylon.particleSystemSet.js.map
  115764. var BABYLON;
  115765. (function (BABYLON) {
  115766. /**
  115767. * This class is made for on one-liner static method to help creating particle system set.
  115768. */
  115769. var ParticleHelper = /** @class */ (function () {
  115770. function ParticleHelper() {
  115771. }
  115772. /**
  115773. * Create a default particle system that you can tweak
  115774. * @param emitter defines the emitter to use
  115775. * @param capacity defines the system capacity (default is 500 particles)
  115776. * @param scene defines the hosting scene
  115777. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  115778. * @returns the new Particle system
  115779. */
  115780. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  115781. if (capacity === void 0) { capacity = 500; }
  115782. if (useGPU === void 0) { useGPU = false; }
  115783. var system;
  115784. if (useGPU) {
  115785. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  115786. }
  115787. else {
  115788. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  115789. }
  115790. system.emitter = emitter;
  115791. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  115792. system.createConeEmitter(0.1, Math.PI / 4);
  115793. // Particle color
  115794. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  115795. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  115796. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  115797. // Particle Size
  115798. system.minSize = 0.1;
  115799. system.maxSize = 0.1;
  115800. // Emission speed
  115801. system.minEmitPower = 2;
  115802. system.maxEmitPower = 2;
  115803. // Update speed
  115804. system.updateSpeed = 1 / 60;
  115805. system.emitRate = 30;
  115806. return system;
  115807. };
  115808. /**
  115809. * This is the main static method (one-liner) of this helper to create different particle systems
  115810. * @param type This string represents the type to the particle system to create
  115811. * @param scene The scene where the particle system should live
  115812. * @param gpu If the system will use gpu
  115813. * @returns the ParticleSystemSet created
  115814. */
  115815. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  115816. if (gpu === void 0) { gpu = false; }
  115817. if (!scene) {
  115818. scene = BABYLON.Engine.LastCreatedScene;
  115819. ;
  115820. }
  115821. var token = {};
  115822. scene._addPendingData(token);
  115823. return new Promise(function (resolve, reject) {
  115824. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  115825. scene._removePendingData(token);
  115826. return reject("Particle system with GPU is not supported.");
  115827. }
  115828. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  115829. scene._removePendingData(token);
  115830. var newData = JSON.parse(data.toString());
  115831. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  115832. }, undefined, undefined, undefined, function (req, exception) {
  115833. scene._removePendingData(token);
  115834. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  115835. });
  115836. });
  115837. };
  115838. /**
  115839. * Static function used to export a particle system to a ParticleSystemSet variable.
  115840. * Please note that the emitter shape is not exported
  115841. * @param systems defines the particle systems to export
  115842. * @returns the created particle system set
  115843. */
  115844. ParticleHelper.ExportSet = function (systems) {
  115845. var set = new BABYLON.ParticleSystemSet();
  115846. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  115847. var system = systems_1[_i];
  115848. set.systems.push(system);
  115849. }
  115850. return set;
  115851. };
  115852. /**
  115853. * Gets or sets base Assets URL
  115854. */
  115855. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  115856. return ParticleHelper;
  115857. }());
  115858. BABYLON.ParticleHelper = ParticleHelper;
  115859. })(BABYLON || (BABYLON = {}));
  115860. //# sourceMappingURL=babylon.particleHelper.js.map
  115861. var BABYLON;
  115862. (function (BABYLON) {
  115863. /**
  115864. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  115865. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  115866. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  115867. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  115868. */
  115869. var VideoDome = /** @class */ (function (_super) {
  115870. __extends(VideoDome, _super);
  115871. /**
  115872. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  115873. * @param name Element's name, child elements will append suffixes for their own names.
  115874. * @param urlsOrVideo defines the url(s) or the video element to use
  115875. * @param options An object containing optional or exposed sub element properties
  115876. */
  115877. function VideoDome(name, urlsOrVideo, options, scene) {
  115878. var _this = _super.call(this, name, scene) || this;
  115879. _this._useDirectMapping = false;
  115880. // set defaults and manage values
  115881. name = name || "videoDome";
  115882. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  115883. options.clickToPlay = Boolean(options.clickToPlay);
  115884. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  115885. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  115886. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  115887. if (options.useDirectMapping === undefined) {
  115888. _this._useDirectMapping = true;
  115889. }
  115890. else {
  115891. _this._useDirectMapping = options.useDirectMapping;
  115892. }
  115893. _this._setReady(false);
  115894. // create
  115895. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  115896. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  115897. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  115898. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  115899. texture.onLoadObservable.addOnce(function () {
  115900. _this._setReady(true);
  115901. });
  115902. // configure material
  115903. material.useEquirectangularFOV = true;
  115904. material.fovMultiplier = 1.0;
  115905. material.opacityFresnel = false;
  115906. if (_this._useDirectMapping) {
  115907. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115908. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115909. material.diffuseTexture = texture;
  115910. }
  115911. else {
  115912. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  115913. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115914. material.reflectionTexture = texture;
  115915. }
  115916. // configure mesh
  115917. _this._mesh.material = material;
  115918. _this._mesh.parent = _this;
  115919. // optional configuration
  115920. if (options.clickToPlay) {
  115921. scene.onPointerUp = function () {
  115922. _this._videoTexture.video.play();
  115923. };
  115924. }
  115925. return _this;
  115926. }
  115927. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  115928. /**
  115929. * Gets the video texture being displayed on the sphere
  115930. */
  115931. get: function () {
  115932. return this._videoTexture;
  115933. },
  115934. enumerable: true,
  115935. configurable: true
  115936. });
  115937. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  115938. /**
  115939. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  115940. * Also see the options.resolution property.
  115941. */
  115942. get: function () {
  115943. return this._material.fovMultiplier;
  115944. },
  115945. set: function (value) {
  115946. this._material.fovMultiplier = value;
  115947. },
  115948. enumerable: true,
  115949. configurable: true
  115950. });
  115951. /**
  115952. * Releases resources associated with this node.
  115953. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  115954. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  115955. */
  115956. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  115957. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  115958. this._videoTexture.dispose();
  115959. this._mesh.dispose();
  115960. this._material.dispose();
  115961. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  115962. };
  115963. return VideoDome;
  115964. }(BABYLON.TransformNode));
  115965. BABYLON.VideoDome = VideoDome;
  115966. })(BABYLON || (BABYLON = {}));
  115967. //# sourceMappingURL=babylon.videoDome.js.map
  115968. var BABYLON;
  115969. (function (BABYLON) {
  115970. /**
  115971. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  115972. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  115973. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  115974. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  115975. */
  115976. var PhotoDome = /** @class */ (function (_super) {
  115977. __extends(PhotoDome, _super);
  115978. /**
  115979. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  115980. * @param name Element's name, child elements will append suffixes for their own names.
  115981. * @param urlsOfPhoto defines the url of the photo to display
  115982. * @param options defines an object containing optional or exposed sub element properties
  115983. * @param onError defines a callback called when an error occured while loading the texture
  115984. */
  115985. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  115986. if (onError === void 0) { onError = null; }
  115987. var _this = _super.call(this, name, scene) || this;
  115988. _this._useDirectMapping = false;
  115989. /**
  115990. * Observable raised when an error occured while loading the 360 image
  115991. */
  115992. _this.onLoadErrorObservable = new BABYLON.Observable();
  115993. // set defaults and manage values
  115994. name = name || "photoDome";
  115995. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  115996. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  115997. if (options.useDirectMapping === undefined) {
  115998. _this._useDirectMapping = true;
  115999. }
  116000. else {
  116001. _this._useDirectMapping = options.useDirectMapping;
  116002. }
  116003. _this._setReady(false);
  116004. // create
  116005. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116006. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116007. // configure material
  116008. material.opacityFresnel = false;
  116009. material.useEquirectangularFOV = true;
  116010. material.fovMultiplier = 1.0;
  116011. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  116012. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  116013. if (onError) {
  116014. onError(message, exception);
  116015. }
  116016. });
  116017. _this.photoTexture.onLoadObservable.addOnce(function () {
  116018. _this._setReady(true);
  116019. });
  116020. // configure mesh
  116021. _this._mesh.material = material;
  116022. _this._mesh.parent = _this;
  116023. return _this;
  116024. }
  116025. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  116026. /**
  116027. * Gets or sets the texture being displayed on the sphere
  116028. */
  116029. get: function () {
  116030. return this._photoTexture;
  116031. },
  116032. set: function (value) {
  116033. if (this._photoTexture === value) {
  116034. return;
  116035. }
  116036. this._photoTexture = value;
  116037. if (this._useDirectMapping) {
  116038. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116039. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116040. this._material.diffuseTexture = this._photoTexture;
  116041. }
  116042. else {
  116043. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116044. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116045. this._material.reflectionTexture = this._photoTexture;
  116046. }
  116047. },
  116048. enumerable: true,
  116049. configurable: true
  116050. });
  116051. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116052. /**
  116053. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116054. * Also see the options.resolution property.
  116055. */
  116056. get: function () {
  116057. return this._material.fovMultiplier;
  116058. },
  116059. set: function (value) {
  116060. this._material.fovMultiplier = value;
  116061. },
  116062. enumerable: true,
  116063. configurable: true
  116064. });
  116065. /**
  116066. * Releases resources associated with this node.
  116067. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116068. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116069. */
  116070. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116071. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116072. this._photoTexture.dispose();
  116073. this._mesh.dispose();
  116074. this._material.dispose();
  116075. this.onLoadErrorObservable.clear();
  116076. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116077. };
  116078. return PhotoDome;
  116079. }(BABYLON.TransformNode));
  116080. BABYLON.PhotoDome = PhotoDome;
  116081. })(BABYLON || (BABYLON = {}));
  116082. //# sourceMappingURL=babylon.photoDome.js.map
  116083. var BABYLON;
  116084. (function (BABYLON) {
  116085. /** @hidden */
  116086. var _OcclusionDataStorage = /** @class */ (function () {
  116087. function _OcclusionDataStorage() {
  116088. /** @hidden */
  116089. this.occlusionInternalRetryCounter = 0;
  116090. /** @hidden */
  116091. this.isOcclusionQueryInProgress = false;
  116092. /** @hidden */
  116093. this.isOccluded = false;
  116094. /** @hidden */
  116095. this.occlusionRetryCount = -1;
  116096. /** @hidden */
  116097. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116098. /** @hidden */
  116099. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116100. }
  116101. return _OcclusionDataStorage;
  116102. }());
  116103. BABYLON.Engine.prototype.createQuery = function () {
  116104. return this._gl.createQuery();
  116105. };
  116106. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116107. this._gl.deleteQuery(query);
  116108. return this;
  116109. };
  116110. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116111. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116112. };
  116113. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116114. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116115. };
  116116. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116117. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116118. this._gl.beginQuery(glAlgorithm, query);
  116119. return this;
  116120. };
  116121. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116122. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116123. this._gl.endQuery(glAlgorithm);
  116124. return this;
  116125. };
  116126. BABYLON.Engine.prototype._createTimeQuery = function () {
  116127. var timerQuery = this.getCaps().timerQuery;
  116128. if (timerQuery.createQueryEXT) {
  116129. return timerQuery.createQueryEXT();
  116130. }
  116131. return this.createQuery();
  116132. };
  116133. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116134. var timerQuery = this.getCaps().timerQuery;
  116135. if (timerQuery.deleteQueryEXT) {
  116136. timerQuery.deleteQueryEXT(query);
  116137. return;
  116138. }
  116139. this.deleteQuery(query);
  116140. };
  116141. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116142. var timerQuery = this.getCaps().timerQuery;
  116143. if (timerQuery.getQueryObjectEXT) {
  116144. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116145. }
  116146. return this.getQueryResult(query);
  116147. };
  116148. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116149. var timerQuery = this.getCaps().timerQuery;
  116150. if (timerQuery.getQueryObjectEXT) {
  116151. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116152. }
  116153. return this.isQueryResultAvailable(query);
  116154. };
  116155. BABYLON.Engine.prototype.startTimeQuery = function () {
  116156. var caps = this.getCaps();
  116157. var timerQuery = caps.timerQuery;
  116158. if (!timerQuery) {
  116159. return null;
  116160. }
  116161. var token = new BABYLON._TimeToken();
  116162. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116163. if (caps.canUseTimestampForTimerQuery) {
  116164. token._startTimeQuery = this._createTimeQuery();
  116165. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116166. }
  116167. else {
  116168. if (this._currentNonTimestampToken) {
  116169. return this._currentNonTimestampToken;
  116170. }
  116171. token._timeElapsedQuery = this._createTimeQuery();
  116172. if (timerQuery.beginQueryEXT) {
  116173. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116174. }
  116175. else {
  116176. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116177. }
  116178. this._currentNonTimestampToken = token;
  116179. }
  116180. return token;
  116181. };
  116182. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116183. var caps = this.getCaps();
  116184. var timerQuery = caps.timerQuery;
  116185. if (!timerQuery || !token) {
  116186. return -1;
  116187. }
  116188. if (caps.canUseTimestampForTimerQuery) {
  116189. if (!token._startTimeQuery) {
  116190. return -1;
  116191. }
  116192. if (!token._endTimeQuery) {
  116193. token._endTimeQuery = this._createTimeQuery();
  116194. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116195. }
  116196. }
  116197. else if (!token._timeElapsedQueryEnded) {
  116198. if (!token._timeElapsedQuery) {
  116199. return -1;
  116200. }
  116201. if (timerQuery.endQueryEXT) {
  116202. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116203. }
  116204. else {
  116205. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116206. }
  116207. token._timeElapsedQueryEnded = true;
  116208. }
  116209. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116210. var available = false;
  116211. if (token._endTimeQuery) {
  116212. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116213. }
  116214. else if (token._timeElapsedQuery) {
  116215. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116216. }
  116217. if (available && !disjoint) {
  116218. var result = 0;
  116219. if (caps.canUseTimestampForTimerQuery) {
  116220. if (!token._startTimeQuery || !token._endTimeQuery) {
  116221. return -1;
  116222. }
  116223. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116224. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116225. result = timeEnd - timeStart;
  116226. this._deleteTimeQuery(token._startTimeQuery);
  116227. this._deleteTimeQuery(token._endTimeQuery);
  116228. token._startTimeQuery = null;
  116229. token._endTimeQuery = null;
  116230. }
  116231. else {
  116232. if (!token._timeElapsedQuery) {
  116233. return -1;
  116234. }
  116235. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116236. this._deleteTimeQuery(token._timeElapsedQuery);
  116237. token._timeElapsedQuery = null;
  116238. token._timeElapsedQueryEnded = false;
  116239. this._currentNonTimestampToken = null;
  116240. }
  116241. return result;
  116242. }
  116243. return -1;
  116244. };
  116245. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116246. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116247. };
  116248. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116249. get: function () {
  116250. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116251. },
  116252. enumerable: false,
  116253. configurable: true
  116254. });
  116255. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116256. get: function () {
  116257. if (!this.__occlusionDataStorage) {
  116258. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116259. }
  116260. return this.__occlusionDataStorage;
  116261. },
  116262. enumerable: false,
  116263. configurable: true
  116264. });
  116265. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116266. get: function () {
  116267. return this._occlusionDataStorage.isOccluded;
  116268. },
  116269. set: function (value) {
  116270. this._occlusionDataStorage.isOccluded = value;
  116271. },
  116272. enumerable: true,
  116273. configurable: true
  116274. });
  116275. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116276. get: function () {
  116277. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116278. },
  116279. set: function (value) {
  116280. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116281. },
  116282. enumerable: true,
  116283. configurable: true
  116284. });
  116285. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116286. get: function () {
  116287. return this._occlusionDataStorage.occlusionType;
  116288. },
  116289. set: function (value) {
  116290. this._occlusionDataStorage.occlusionType = value;
  116291. },
  116292. enumerable: true,
  116293. configurable: true
  116294. });
  116295. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116296. get: function () {
  116297. return this._occlusionDataStorage.occlusionRetryCount;
  116298. },
  116299. set: function (value) {
  116300. this._occlusionDataStorage.occlusionRetryCount = value;
  116301. },
  116302. enumerable: true,
  116303. configurable: true
  116304. });
  116305. // We also need to update AbstractMesh as there is a portion of the code there
  116306. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116307. var dataStorage = this._occlusionDataStorage;
  116308. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116309. dataStorage.isOccluded = false;
  116310. return false;
  116311. }
  116312. var engine = this.getEngine();
  116313. if (engine.webGLVersion < 2) {
  116314. dataStorage.isOccluded = false;
  116315. return false;
  116316. }
  116317. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116318. dataStorage.isOccluded = false;
  116319. return false;
  116320. }
  116321. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116322. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116323. if (isOcclusionQueryAvailable) {
  116324. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116325. dataStorage.isOcclusionQueryInProgress = false;
  116326. dataStorage.occlusionInternalRetryCounter = 0;
  116327. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116328. }
  116329. else {
  116330. dataStorage.occlusionInternalRetryCounter++;
  116331. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116332. dataStorage.isOcclusionQueryInProgress = false;
  116333. dataStorage.occlusionInternalRetryCounter = 0;
  116334. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116335. // if strict continue the last state of the object.
  116336. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116337. }
  116338. else {
  116339. return false;
  116340. }
  116341. }
  116342. }
  116343. var scene = this.getScene();
  116344. if (scene.getBoundingBoxRenderer) {
  116345. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116346. if (!this._occlusionQuery) {
  116347. this._occlusionQuery = engine.createQuery();
  116348. }
  116349. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116350. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116351. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116352. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116353. }
  116354. return dataStorage.isOccluded;
  116355. };
  116356. })(BABYLON || (BABYLON = {}));
  116357. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116358. var BABYLON;
  116359. (function (BABYLON) {
  116360. /**
  116361. * Class used to generate noise procedural textures
  116362. */
  116363. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116364. __extends(NoiseProceduralTexture, _super);
  116365. /**
  116366. * Creates a new NoiseProceduralTexture
  116367. * @param name defines the name fo the texture
  116368. * @param size defines the size of the texture (default is 256)
  116369. * @param scene defines the hosting scene
  116370. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116371. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116372. */
  116373. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116374. if (size === void 0) { size = 256; }
  116375. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116376. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116377. _this._time = 0;
  116378. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116379. _this.brightness = 0.2;
  116380. /** Defines the number of octaves to process */
  116381. _this.octaves = 3;
  116382. /** Defines the level of persistence (0.8 by default) */
  116383. _this.persistence = 0.8;
  116384. /** Gets or sets animation speed factor (default is 1) */
  116385. _this.animationSpeedFactor = 1;
  116386. _this._updateShaderUniforms();
  116387. return _this;
  116388. }
  116389. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116390. var scene = this.getScene();
  116391. if (!scene) {
  116392. return;
  116393. }
  116394. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116395. this.setFloat("brightness", this.brightness);
  116396. this.setFloat("persistence", this.persistence);
  116397. this.setFloat("timeScale", this._time);
  116398. };
  116399. NoiseProceduralTexture.prototype._getDefines = function () {
  116400. return "#define OCTAVES " + (this.octaves | 0);
  116401. };
  116402. /** Generate the current state of the procedural texture */
  116403. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116404. this._updateShaderUniforms();
  116405. _super.prototype.render.call(this, useCameraPostProcess);
  116406. };
  116407. /**
  116408. * Serializes this noise procedural texture
  116409. * @returns a serialized noise procedural texture object
  116410. */
  116411. NoiseProceduralTexture.prototype.serialize = function () {
  116412. var serializationObject = {};
  116413. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116414. serializationObject.brightness = this.brightness;
  116415. serializationObject.octaves = this.octaves;
  116416. serializationObject.persistence = this.persistence;
  116417. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116418. serializationObject.size = this.getSize().width;
  116419. serializationObject.generateMipMaps = this._generateMipMaps;
  116420. return serializationObject;
  116421. };
  116422. /**
  116423. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116424. * @param parsedTexture defines parsed texture data
  116425. * @param scene defines the current scene
  116426. * @param rootUrl defines the root URL containing noise procedural texture information
  116427. * @returns a parsed NoiseProceduralTexture
  116428. */
  116429. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116430. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116431. texture.brightness = parsedTexture.brightness;
  116432. texture.octaves = parsedTexture.octaves;
  116433. texture.persistence = parsedTexture.persistence;
  116434. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116435. return texture;
  116436. };
  116437. return NoiseProceduralTexture;
  116438. }(BABYLON.ProceduralTexture));
  116439. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116440. })(BABYLON || (BABYLON = {}));
  116441. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116442. var __assign = (this && this.__assign) || function () {
  116443. __assign = Object.assign || function(t) {
  116444. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116445. s = arguments[i];
  116446. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116447. t[p] = s[p];
  116448. }
  116449. return t;
  116450. };
  116451. return __assign.apply(this, arguments);
  116452. };
  116453. var BABYLON;
  116454. (function (BABYLON) {
  116455. /**
  116456. * This can helps recording videos from BabylonJS.
  116457. * This is based on the available WebRTC functionalities of the browser.
  116458. *
  116459. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116460. */
  116461. var VideoRecorder = /** @class */ (function () {
  116462. /**
  116463. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116464. * a video file.
  116465. * @param engine Defines the BabylonJS Engine you wish to record
  116466. * @param options Defines options that can be used to customized the capture
  116467. */
  116468. function VideoRecorder(engine, options) {
  116469. if (options === void 0) { options = null; }
  116470. if (!VideoRecorder.IsSupported(engine)) {
  116471. throw "Your browser does not support recording so far.";
  116472. }
  116473. var canvas = engine.getRenderingCanvas();
  116474. if (!canvas) {
  116475. throw "The babylon engine must have a canvas to be recorded";
  116476. }
  116477. this._canvas = canvas;
  116478. this._canvas.isRecording = false;
  116479. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116480. var stream = this._canvas.captureStream(this._options.fps);
  116481. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116482. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116483. this._mediaRecorder.onerror = this._handleError.bind(this);
  116484. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116485. }
  116486. /**
  116487. * Returns wehther or not the VideoRecorder is available in your browser.
  116488. * @param engine Defines the Babylon Engine to check the support for
  116489. * @returns true if supported otherwise false
  116490. */
  116491. VideoRecorder.IsSupported = function (engine) {
  116492. var canvas = engine.getRenderingCanvas();
  116493. return (!!canvas && typeof canvas.captureStream === "function");
  116494. };
  116495. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116496. /**
  116497. * True wether a recording is already in progress.
  116498. */
  116499. get: function () {
  116500. return !!this._canvas && this._canvas.isRecording;
  116501. },
  116502. enumerable: true,
  116503. configurable: true
  116504. });
  116505. /**
  116506. * Stops the current recording before the default capture timeout passed in the startRecording
  116507. * functions.
  116508. */
  116509. VideoRecorder.prototype.stopRecording = function () {
  116510. if (!this._canvas || !this._mediaRecorder) {
  116511. return;
  116512. }
  116513. if (!this.isRecording) {
  116514. return;
  116515. }
  116516. this._canvas.isRecording = false;
  116517. this._mediaRecorder.stop();
  116518. };
  116519. /**
  116520. * Starts recording the canvas for a max duration specified in parameters.
  116521. * @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.
  116522. * @param maxDuration Defines the maximum recording time in seconds.
  116523. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116524. * @return a promise callback at the end of the recording with the video data in Blob.
  116525. */
  116526. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116527. var _this = this;
  116528. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116529. if (maxDuration === void 0) { maxDuration = 7; }
  116530. if (!this._canvas || !this._mediaRecorder) {
  116531. throw "Recorder has already been disposed";
  116532. }
  116533. if (this.isRecording) {
  116534. throw "Recording already in progress";
  116535. }
  116536. if (maxDuration > 0) {
  116537. setTimeout(function () {
  116538. _this.stopRecording();
  116539. }, maxDuration * 1000);
  116540. }
  116541. this._fileName = fileName;
  116542. this._recordedChunks = [];
  116543. this._resolve = null;
  116544. this._reject = null;
  116545. this._canvas.isRecording = true;
  116546. this._mediaRecorder.start(this._options.recordChunckSize);
  116547. return new Promise(function (resolve, reject) {
  116548. _this._resolve = resolve;
  116549. _this._reject = reject;
  116550. });
  116551. };
  116552. /**
  116553. * Releases internal resources used during the recording.
  116554. */
  116555. VideoRecorder.prototype.dispose = function () {
  116556. this._canvas = null;
  116557. this._mediaRecorder = null;
  116558. this._recordedChunks = [];
  116559. this._fileName = null;
  116560. this._resolve = null;
  116561. this._reject = null;
  116562. };
  116563. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116564. if (event.data.size > 0) {
  116565. this._recordedChunks.push(event.data);
  116566. }
  116567. };
  116568. VideoRecorder.prototype._handleError = function (event) {
  116569. this.stopRecording();
  116570. if (this._reject) {
  116571. this._reject(event.error);
  116572. }
  116573. else {
  116574. throw new event.error;
  116575. }
  116576. };
  116577. VideoRecorder.prototype._handleStop = function () {
  116578. this.stopRecording();
  116579. var superBuffer = new Blob(this._recordedChunks);
  116580. if (this._resolve) {
  116581. this._resolve(superBuffer);
  116582. }
  116583. window.URL.createObjectURL(superBuffer);
  116584. if (this._fileName) {
  116585. BABYLON.Tools.Download(superBuffer, this._fileName);
  116586. }
  116587. };
  116588. VideoRecorder._defaultOptions = {
  116589. mimeType: "video/webm",
  116590. fps: 25,
  116591. recordChunckSize: 3000
  116592. };
  116593. return VideoRecorder;
  116594. }());
  116595. BABYLON.VideoRecorder = VideoRecorder;
  116596. })(BABYLON || (BABYLON = {}));
  116597. //# sourceMappingURL=babylon.videoRecorder.js.map
  116598. var BABYLON;
  116599. (function (BABYLON) {
  116600. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  116601. if (replace === void 0) { replace = false; }
  116602. // Dispose existing light in replace mode.
  116603. if (replace) {
  116604. if (this.lights) {
  116605. for (var i = 0; i < this.lights.length; i++) {
  116606. this.lights[i].dispose();
  116607. }
  116608. }
  116609. }
  116610. // Light
  116611. if (this.lights.length === 0) {
  116612. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  116613. }
  116614. };
  116615. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  116616. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116617. if (replace === void 0) { replace = false; }
  116618. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116619. // Dispose existing camera in replace mode.
  116620. if (replace) {
  116621. if (this.activeCamera) {
  116622. this.activeCamera.dispose();
  116623. this.activeCamera = null;
  116624. }
  116625. }
  116626. // Camera
  116627. if (!this.activeCamera) {
  116628. var worldExtends = this.getWorldExtends();
  116629. var worldSize = worldExtends.max.subtract(worldExtends.min);
  116630. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  116631. var camera;
  116632. var radius = worldSize.length() * 1.5;
  116633. // empty scene scenario!
  116634. if (!isFinite(radius)) {
  116635. radius = 1;
  116636. worldCenter.copyFromFloats(0, 0, 0);
  116637. }
  116638. if (createArcRotateCamera) {
  116639. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  116640. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  116641. arcRotateCamera.wheelPrecision = 100 / radius;
  116642. camera = arcRotateCamera;
  116643. }
  116644. else {
  116645. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  116646. freeCamera.setTarget(worldCenter);
  116647. camera = freeCamera;
  116648. }
  116649. camera.minZ = radius * 0.01;
  116650. camera.maxZ = radius * 1000;
  116651. camera.speed = radius * 0.2;
  116652. this.activeCamera = camera;
  116653. var canvas = this.getEngine().getRenderingCanvas();
  116654. if (attachCameraControls && canvas) {
  116655. camera.attachControl(canvas);
  116656. }
  116657. }
  116658. };
  116659. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  116660. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116661. if (replace === void 0) { replace = false; }
  116662. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116663. this.createDefaultLight(replace);
  116664. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  116665. };
  116666. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  116667. if (pbr === void 0) { pbr = false; }
  116668. if (scale === void 0) { scale = 1000; }
  116669. if (blur === void 0) { blur = 0; }
  116670. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  116671. if (!environmentTexture) {
  116672. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  116673. return null;
  116674. }
  116675. if (setGlobalEnvTexture) {
  116676. if (environmentTexture) {
  116677. this.environmentTexture = environmentTexture;
  116678. }
  116679. }
  116680. // Skybox
  116681. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  116682. if (pbr) {
  116683. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  116684. hdrSkyboxMaterial.backFaceCulling = false;
  116685. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  116686. if (hdrSkyboxMaterial.reflectionTexture) {
  116687. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116688. }
  116689. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  116690. hdrSkyboxMaterial.disableLighting = true;
  116691. hdrSkyboxMaterial.twoSidedLighting = true;
  116692. hdrSkybox.infiniteDistance = true;
  116693. hdrSkybox.material = hdrSkyboxMaterial;
  116694. }
  116695. else {
  116696. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  116697. skyboxMaterial.backFaceCulling = false;
  116698. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  116699. if (skyboxMaterial.reflectionTexture) {
  116700. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116701. }
  116702. skyboxMaterial.disableLighting = true;
  116703. hdrSkybox.infiniteDistance = true;
  116704. hdrSkybox.material = skyboxMaterial;
  116705. }
  116706. return hdrSkybox;
  116707. };
  116708. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  116709. if (BABYLON.EnvironmentHelper) {
  116710. return new BABYLON.EnvironmentHelper(options, this);
  116711. }
  116712. return null;
  116713. };
  116714. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  116715. if (webVROptions === void 0) { webVROptions = {}; }
  116716. return new BABYLON.VRExperienceHelper(this, webVROptions);
  116717. };
  116718. })(BABYLON || (BABYLON = {}));
  116719. //# sourceMappingURL=babylon.sceneHelpers.js.map
  116720. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(positionUpdated,1.0)).xyz;\n#else\nvPositionUVW=positionUpdated;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\npointLightingInfo pointInfo;\nspotLightingInfo spotInfo;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef AMBIENT\nvec3 ambientOcclusionForDirectDiffuse=mix(vec3(1.),ambientOcclusionColor,vAmbientInfos.w);\n#else\nvec3 ambientOcclusionForDirectDiffuse=ambientOcclusionColor;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionForDirectDiffuse*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\n#ifdef BILLBOARDSTRETCHED\nattribute vec3 direction; \n#endif\n#ifdef RAMPGRADIENT\nattribute vec4 remapData;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\n#endif\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration>\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n#ifdef RAMPGRADIENT\nremapRanges=remapData;\n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*vec4(viewPos,1.0);\n#endif\n#include<clipPlaneVertex>\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#include<clipPlaneFragmentDeclaration>\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n#ifdef RAMPGRADIENT\nvarying vec4 remapRanges;\nuniform sampler2D rampSampler;\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec4 textureColor=texture2D(diffuseSampler,vUV);\nvec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n#ifdef RAMPGRADIENT\nfloat alpha=baseColor.a;\nfloat remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);\nvec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));\nbaseColor.rgb*=rampColor.rgb;\n\nfloat finalAlpha=baseColor.a;\nbaseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0);\n#endif\n#ifdef BLENDMULTIPLYMODE\nfloat sourceAlpha=vColor.a*textureColor.a;\nbaseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha);\n#endif\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\nbaseColor.rgb=toLinearSpace(baseColor.rgb);\nbaseColor=applyImageProcessing(baseColor);\n#endif\n#endif\ngl_FragColor=baseColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef BILLBOARDSTRETCHED\nin vec3 direction;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nuniform mat4 invView;\n#endif\n#include<clipPlaneVertexDeclaration2>\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\n#ifdef BILLBOARDSTRETCHED\nvec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {\nvec3 normalizedToCamera=normalize(toCamera);\nvec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));\nvec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));\nvec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);\nvec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);\nvec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#elif defined(BILLBOARDSTRETCHED)\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 toCamera=position-eyePosition; \nvec3 worldPos=rotateAlign(toCamera,rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4)\nvec4 worldPos=invView*viewPosition;\n#endif \n#include<clipPlaneVertex>\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#include<clipPlaneFragmentDeclaration2> \n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main() {\n#include<clipPlaneFragment> \nvec4 textureColor=texture(textureSampler,vUV);\noutFragColor=textureColor*vColor;\n#ifdef BLENDMULTIPLYMODE\nfloat alpha=vColor.a*textureColor.a;\noutFragColor.rgb=outFragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); \n#endif \n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\n#else\n#ifdef IMAGEPROCESSING\noutFragColor.rgb=toLinearSpace(outFragColor.rgb);\noutFragColor=applyImageProcessing(outFragColor);\n#endif\n#endif\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef POINTEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#endif\n#ifdef HEMISPHERICEMITTER\nuniform float radius;\nuniform float radiusRange;\nuniform float directionRandomizer;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CYLINDEREMITTER\nuniform float radius;\nuniform float height;\nuniform float radiusRange;\n#ifdef DIRECTEDCYLINDEREMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nin float cellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nin vec3 noiseCoordinates1;\nin vec3 noiseCoordinates2;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#ifdef ANIMATESHEETRANDOMSTART\nout float outCellStartOffset;\n#endif\n#endif\n#ifdef NOISE\nout vec3 outNoiseCoordinates1;\nout vec3 outNoiseCoordinates2;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef VELOCITYGRADIENTS\nuniform sampler2D velocityGradientSampler;\n#endif\n#ifdef LIMITVELOCITYGRADIENTS\nuniform sampler2D limitVelocityGradientSampler;\nuniform float limitVelocityDamping;\n#endif\n#ifdef DRAGGRADIENTS\nuniform sampler2D dragGradientSampler;\n#endif\n#ifdef NOISE\nuniform vec3 noiseStrength;\nuniform sampler2D noiseSampler;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nfloat newAge=age+timeDelta; \n\nif (newAge>=life && stopFactor != 0.) {\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\noutAge=mod(newAge,outLife);\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef POINTEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=vec3(0,0,0);\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(BOXEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3; \n#elif defined(HEMISPHERICEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,abs(randY),randZ);\ndirection=position+directionRandomizer*randoms3; \n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CYLINDEREMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat yPos=(randoms2.x-0.5)*height;\nfloat angle=randoms2.y*PI*2.;\nfloat inverseRadiusRangeSquared=((1.-radiusRange)*(1.-radiusRange));\nfloat positionRadius=radius*sqrt(inverseRadiusRangeSquared+(randoms2.z*(1.-inverseRadiusRangeSquared)));\nfloat xPos=positionRadius*cos(angle);\nfloat zPos=positionRadius*sin(angle);\nposition=vec3(xPos,yPos,zPos);\n#ifdef DIRECTEDCYLINDEREMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\nangle=angle+((randoms3.x-0.5)*PI);\ndirection=vec3(cos(angle),randoms3.y-0.5,sin(angle));\ndirection=normalize(direction);\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\n#ifdef CONEEMITTERSPAWNPOINT\nfloat h=0.00001;\n#else\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h; \n#endif\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=randoms.a*outLife;\n#endif \n#endif\n#ifdef NOISE\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif\n} else {\nfloat directionScale=timeDelta;\noutAge=newAge;\nfloat ageGradient=newAge/life;\n#ifdef VELOCITYGRADIENTS\ndirectionScale*=texture(velocityGradientSampler,vec2(ageGradient,0)).r;\n#endif\n#ifdef DRAGGRADIENTS\ndirectionScale*=1.0-texture(dragGradientSampler,vec2(ageGradient,0)).r;\n#endif\noutPosition=position+direction*directionScale;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(ageGradient,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\nvec3 updatedDirection=direction+gravity*timeDelta;\n#ifdef LIMITVELOCITYGRADIENTS\nfloat limitVelocity=texture(limitVelocityGradientSampler,vec2(ageGradient,0)).r;\nfloat currentVelocity=length(updatedDirection);\nif (currentVelocity>limitVelocity) {\nupdatedDirection=updatedDirection*limitVelocityDamping;\n}\n#endif\noutDirection=updatedDirection;\n#ifdef NOISE\nvec3 localPosition=outPosition-emitterWM[3].xyz;\nfloat fetchedR=texture(noiseSampler,vec2(noiseCoordinates1.x,noiseCoordinates1.y)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedG=texture(noiseSampler,vec2(noiseCoordinates1.z,noiseCoordinates2.x)*vec2(0.5)+vec2(0.5)).r;\nfloat fetchedB=texture(noiseSampler,vec2(noiseCoordinates2.y,noiseCoordinates2.z)*vec2(0.5)+vec2(0.5)).r;\nvec3 force=vec3(2.*fetchedR-1.,2.*fetchedG-1.,2.*fetchedB-1.)*noiseStrength;\noutDirection=outDirection+force*timeDelta;\noutNoiseCoordinates1=noiseCoordinates1;\noutNoiseCoordinates2=noiseCoordinates2;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(ageGradient,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat offsetAge=outAge;\nfloat dist=cellInfos.y-cellInfos.x;\n#ifdef ANIMATESHEETRANDOMSTART\noutCellStartOffset=cellStartOffset;\noffsetAge+=cellStartOffset;\n#endif \nfloat ratio=clamp(mod(offsetAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nfloat scales[16]=float[16](\n0.1,\n0.11406250000000001,\n0.131640625,\n0.15625,\n0.187890625,\n0.2265625,\n0.272265625,\n0.325,\n0.384765625,\n0.4515625,\n0.525390625,\n0.60625,\n0.694140625,\n0.7890625,\n0.891015625,\n1.0\n);\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\n\nfloat dotProduct=dot(rvec,normal);\nrvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=scales[(i+int(random.x*16.0)) % 16]*tbn*sampleSphere[(i+int(random.y*16.0)) % 16];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\ndifference=depthSign*samplePosition.z-sampleDepth;\nfloat rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);\nocclusion+=(difference>=0.0 ? 1.0 : 0.0)*rangeCheck;\n}\nocclusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\n#ifdef REFLECTIONMAP_SKYBOX_TRANSFORMED\nvPositionUVW=(reflectionMatrix*vec4(position,1.0)).xyz;\n#else\nvPositionUVW=position;\n#endif\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n","noisePixelShader":"\n\nuniform float brightness;\nuniform float persistence;\nuniform float timeScale;\n\nvarying vec2 vUV;\n\nvec2 hash22(vec2 p)\n{\np=p*mat2(127.1,311.7,269.5,183.3);\np=-1.0+2.0*fract(sin(p)*43758.5453123);\nreturn sin(p*6.283+timeScale);\n}\nfloat interpolationNoise(vec2 p)\n{\nvec2 pi=floor(p);\nvec2 pf=p-pi;\nvec2 w=pf*pf*(3.-2.*pf);\nfloat f00=dot(hash22(pi+vec2(.0,.0)),pf-vec2(.0,.0));\nfloat f01=dot(hash22(pi+vec2(.0,1.)),pf-vec2(.0,1.));\nfloat f10=dot(hash22(pi+vec2(1.0,0.)),pf-vec2(1.0,0.));\nfloat f11=dot(hash22(pi+vec2(1.0,1.)),pf-vec2(1.0,1.));\nfloat xm1=mix(f00,f10,w.x);\nfloat xm2=mix(f01,f11,w.x);\nfloat ym=mix(xm1,xm2,w.y); \nreturn ym;\n}\nfloat perlinNoise2D(float x,float y)\n{\nfloat sum=0.0;\nfloat frequency=0.0;\nfloat amplitude=0.0;\nfor(int i=0; i<OCTAVES; i++)\n{\nfrequency=pow(2.0,float(i));\namplitude=pow(persistence,float(i));\nsum=sum+interpolationNoise(vec2(x*frequency,y*frequency))*amplitude;\n}\nreturn sum;\n}\n\nvoid main(void)\n{\nfloat x=abs(vUV.x);\nfloat y=abs(vUV.y);\nfloat noise=brightness+(1.0-brightness)*perlinNoise2D(x,y);\ngl_FragColor=vec4(noise,noise,noise,1.0);\n}\n"};
  116721. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nvarying float fClipDistance4;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n#ifdef CLIPPLANE2\nfClipDistance2=dot(worldPos,vClipPlane2);\n#endif\n#ifdef CLIPPLANE3\nfClipDistance3=dot(worldPos,vClipPlane3);\n#endif\n#ifdef CLIPPLANE4\nfClipDistance4=dot(worldPos,vClipPlane4);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\nuniform vec4 vLightFalloff{X};\n#elif defined(POINTLIGHT{X})\nuniform vec4 vLightFalloff{X};\n#elif defined(HEMILIGHT{X})\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\nvec4 vLightFalloff;\n#elif defined(POINTLIGHT{X})\nvec4 vLightFalloff;\n#elif defined(HEMILIGHT{X})\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef REFLECTION\nuniform mat4 reflectionMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\n#ifdef TONEMAPPING_ACES\n\n\n\n\n\nconst mat3 ACESInputMat=mat3(\nvec3(0.59719,0.07600,0.02840),\nvec3(0.35458,0.90834,0.13383),\nvec3(0.04823,0.01566,0.83777)\n);\n\nconst mat3 ACESOutputMat=mat3(\nvec3( 1.60475,-0.10208,-0.00327),\nvec3(-0.53108,1.10813,-0.07276),\nvec3(-0.07367,-0.00605,1.07602)\n);\nvec3 RRTAndODTFit(vec3 v)\n{\nvec3 a=v*(v+0.0245786)-0.000090537;\nvec3 b=v*(0.983729*v+0.4329510)+0.238081;\nreturn a/b;\n}\nvec3 ACESFitted(vec3 color)\n{\ncolor=ACESInputMat*color;\n\ncolor=RRTAndODTFit(color);\ncolor=ACESOutputMat*color;\n\ncolor=clamp(color,0.0,1.0);\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\n#ifdef TONEMAPPING_ACES\nresult.rgb=ACESFitted(result.rgb);\n#else\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nvarying float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nvarying float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nvarying float fClipDistance4;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE2\nif (fClipDistance2>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE3\nif (fClipDistance3>0.0)\n{\ndiscard;\n}\n#endif\n#ifdef CLIPPLANE4\nif (fClipDistance4>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\nspotInfo=computeSpotLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\nspotInfo.attenuation=computeDistanceLightFalloff_GLTF(spotInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Physical(spotInfo.lightDistanceSquared);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\nspotInfo.attenuation=computeDistanceLightFalloff_Standard(spotInfo.lightOffset,light{X}.vLightFalloff.x);\nspotInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w);\n#else\nspotInfo.attenuation=computeDistanceLightFalloff(spotInfo.lightOffset,spotInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\nspotInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,spotInfo.directionToLightCenterW,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w);\n#endif\ninfo=computeSpotLighting(spotInfo,viewDirectionW,normalW,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(POINTLIGHT{X})\npointInfo=computePointLightingInfo(light{X}.vLightData);\n#ifdef LIGHT_FALLOFF_GLTF{X}\npointInfo.attenuation=computeDistanceLightFalloff_GLTF(pointInfo.lightDistanceSquared,light{X}.vLightFalloff.y);\n#elif defined(LIGHT_FALLOFF_PHYSICAL{X})\npointInfo.attenuation=computeDistanceLightFalloff_Physical(pointInfo.lightDistanceSquared);\n#elif defined(LIGHT_FALLOFF_STANDARD{X})\npointInfo.attenuation=computeDistanceLightFalloff_Standard(pointInfo.lightOffset,light{X}.vLightFalloff.x);\n#else\npointInfo.attenuation=computeDistanceLightFalloff(pointInfo.lightOffset,pointInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y);\n#endif\ninfo=computePointLighting(pointInfo,viewDirectionW,normalW,light{X}.vLightDiffuse.rgb,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#elif defined(DIRLIGHT{X})\ninfo=computeDirectionalLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#elif defined(HEMILIGHT{X})\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec4 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec4 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#if defined(USEPHYSICALLIGHTFALLOFF) || defined(USEGLTFLIGHTFALLOFF)\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nstruct pointLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nfloat attenuation;\n};\nstruct spotLightingInfo\n{\nvec3 lightOffset;\nfloat lightDistanceSquared;\nvec3 directionToLightCenterW;\nfloat attenuation;\n};\nfloat computeDistanceLightFalloff_Standard(vec3 lightOffset,float range)\n{\nreturn max(0.,1.0-length(lightOffset)/range);\n}\nfloat computeDistanceLightFalloff_Physical(float lightDistanceSquared)\n{\nreturn 1.0/((lightDistanceSquared+0.001));\n}\nfloat computeDistanceLightFalloff_GLTF(float lightDistanceSquared,float inverseSquaredRange)\n{\nconst float minDistanceSquared=0.01*0.01;\nfloat lightDistanceFalloff=1.0/(max(lightDistanceSquared,minDistanceSquared));\nfloat factor=lightDistanceSquared*inverseSquaredRange;\nfloat attenuation=clamp(1.0-factor*factor,0.,1.);\nattenuation*=attenuation;\n\nlightDistanceFalloff*=attenuation;\nreturn lightDistanceFalloff;\n}\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range,float inverseSquaredRange)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDistanceLightFalloff_Physical(lightDistanceSquared);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDistanceLightFalloff_GLTF(lightDistanceSquared,inverseSquaredRange);\n#else\nreturn computeDistanceLightFalloff_Standard(lightOffset,range);\n#endif\n}\nfloat computeDirectionalLightFalloff_Standard(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_Physical(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle)\n{\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfloat falloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff_GLTF(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngleScale,float lightAngleOffset)\n{\n\n\n\nfloat cd=dot(-lightDirection,directionToLightCenterW);\nfloat falloff=clamp(cd*lightAngleScale+lightAngleOffset,0.,1.);\n\nfalloff*=falloff;\nreturn falloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent,float lightAngleScale,float lightAngleOffset)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\nreturn computeDirectionalLightFalloff_Physical(lightDirection,directionToLightCenterW,cosHalfAngle);\n#elif defined(USEGLTFLIGHTFALLOFF)\nreturn computeDirectionalLightFalloff_GLTF(lightDirection,directionToLightCenterW,lightAngleScale,lightAngleOffset);\n#else\nreturn computeDirectionalLightFalloff_Standard(lightDirection,directionToLightCenterW,cosHalfAngle,exponent);\n#endif\n}\npointLightingInfo computePointLightingInfo(vec4 lightData) {\npointLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nspotLightingInfo computeSpotLightingInfo(vec4 lightData) {\nspotLightingInfo result;\nresult.lightOffset=lightData.xyz-vPositionW;\nresult.directionToLightCenterW=normalize(result.lightOffset);\nresult.lightDistanceSquared=dot(result.lightOffset,result.lightOffset);\nreturn result;\n}\nlightingInfo computePointLighting(pointLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nvec3 lightDirection=normalize(info.lightOffset);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(spotLightingInfo info,vec3 viewDirectionW,vec3 vNormal,vec4 lightDirection,vec3 diffuseColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\nfloat lightDistance=sqrt(info.lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+info.directionToLightCenterW);\nNdotL=clamp(dot(vNormal,info.directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*info.attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*info.attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeDirectionalLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float lightRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nfloat lightDistance=length(-lightData.xyz);\nvec3 lightDirection=normalize(-lightData.xyz);\n\nroughness=adjustRoughnessFromLightProperties(roughness,lightRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","clipPlaneVertexDeclaration2":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nout float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nuniform vec4 vClipPlane2;\nout float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nuniform vec4 vClipPlane3;\nout float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nuniform vec4 vClipPlane4;\nout float fClipDistance4;\n#endif","clipPlaneFragmentDeclaration2":"#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\n#ifdef CLIPPLANE2\nin float fClipDistance2;\n#endif\n#ifdef CLIPPLANE3\nin float fClipDistance3;\n#endif\n#ifdef CLIPPLANE4\nin float fClipDistance4;\n#endif","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};